import Form from '@admin/components/form/Form';
import FormField from '@admin/components/form/FormField';
import { Button } from '@admin/components/ui/button';
import { Card } from '@admin/components/ui/card';
import AppLayout from '@admin/layouts/app-layout';
import SettingsLayout from '@admin/layouts/settings/layout';
import { yupResolver } from '@hookform/resolvers/yup';
import { Head, router, usePage } from '@inertiajs/react';
import { ArrowLeft, ChevronRight, Plus } from 'lucide-react';
import * as yup from 'yup';

// Validation schema
const schema = yup.object({
    country: yup.string().required('Country is required'),
    status: yup.number().oneOf([1, 0], 'Invalid status').required('Status is required'),
});

const defaultValues = {
    country: '',
    status: 1,
};

export default function Create() {
    const { errors, countries } = usePage<any>().props;

    // Transform countries object to options array
    const countryOptions = countries
        ? Object.entries(countries).map(([code, data]: [string, any]) => ({
              label: `${data.flag} ${data.name}`,
              value: code,
          }))
        : [];

    const handleSubmit = (formData: any) => {
        console.log('🚀 ~ handleSubmit ~ formData:', formData);

        // Handle file upload - extract first file from array if it exists
        const payload: any = { ...formData };

        // Extract country code, name, and flag from selection
        if (payload.country && countries) {
            const selectedCountry = countries[payload.country];
            payload.name = selectedCountry.name; // Country name becomes language name
            payload.code = payload.country; // Country code becomes language code
            payload.icon = selectedCountry.flag; // Flag emoji becomes icon
            delete payload.country; // Remove temporary country field
        }

        // Icon is now just the flag emoji string, no need for file handling

        console.log('🚀 ~ Final payload to submit:', payload);

        router.post(route('language.store'), payload, {
            forceFormData: true,
            onSuccess: () => {
                console.log('✅ Language created successfully');
            },
            onError: (errors) => {
                console.error('❌ Form submission errors:', errors);
            },
        });
    };

    return (
        <>
            <Head title="Create Language" />
            <SettingsLayout tab="platform">
                <div className="mx-auto flex w-full flex-1 flex-col gap-4 p-3 sm:gap-6 sm:p-2">
                    {/* Simple header */}
                    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <div className="flex items-start gap-3 sm:gap-4">
                            <Button
                                variant="outline"
                                size="icon"
                                onClick={() => history.back()}
                                className="shrink-0 border-none bg-muted hover:bg-muted/80"
                            >
                                <ArrowLeft className="h-4 w-4" color="black" />
                            </Button>
                            <div>
                                <h1 className="text-xl font-bold tracking-tight sm:text-2xl">Create Language</h1>
                                <p className="text-sm text-gray-600">Add a new language to your application</p>
                            </div>
                        </div>
                        <div className="hidden items-center space-x-2 text-sm text-gray-500 sm:flex">
                            <span>Language</span>
                            <ChevronRight className="h-4 w-4" />
                            <span className="font-medium text-primary">Create</span>
                        </div>
                    </div>

                    {/* Main content */}
                    <Card className="p-4">
                        <Form
                            resolver={yupResolver(schema)}
                            defaultValues={defaultValues}
                            submitHandler={handleSubmit}
                            externalErrors={errors}
                            className="space-y-6"
                        >
                            <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
                                <FormField
                                    type="searchable"
                                    name="country"
                                    label="Country"
                                    placeholder="Select a country"
                                    required
                                    options={countryOptions}
                                />

                                <FormField
                                    type="select"
                                    name="status"
                                    label="Status"
                                    required
                                    options={[
                                        { label: 'Active', value: 1 },
                                        { label: 'Inactive', value: 0 },
                                    ]}
                                />
                            </div>

                            <div className="mt-6 flex justify-end gap-3">
                                <Button type="button" variant="outline" onClick={() => history.back()}>
                                    Cancel
                                </Button>
                                <Button type="submit">
                                    <Plus className="h-4 w-4" />
                                    Create Language
                                </Button>
                            </div>
                        </Form>
                    </Card>
                </div>
            </SettingsLayout>
        </>
    );
}

Create.layout = (page: React.ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Settings', href: route('settings.company.edit') },
            { title: 'Languages', href: route('language.index') },
            { title: 'Create', href: '#' },
        ]}
        title="Create Language"
    >
        {page}
    </AppLayout>
);
