'use client'

import { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
import Select from 'react-select'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import {
    Dialog,
    DialogTrigger,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogFooter,
} from '@/components/ui/dialog'
import {
    Form,
    FormField,
    FormItem,
    FormControl,
    FormLabel,
    FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Plus, Pencil, Loader2 } from 'lucide-react'
import { useRoutes } from '@/contexts/RoutesContext'
import { getAllCities } from '@/lib/cities'
import { getCompanies } from '@/lib/companies'

const routeSchema = z.object({
    departureCityId: z.number().min(1, 'Ville de départ requise'),
    arrivalCityId: z.number().min(1, 'Ville d\'arrivée requise'),
    basePrice: z.number().positive('Le prix doit être positif'),
    companyId: z.number().min(1, 'Compagnie requise'),
}).refine(data => data.departureCityId !== data.arrivalCityId, {
    message: 'Les villes de départ et d\'arrivée doivent être différentes',
    path: ['arrivalCityId'],
})

type RouteFormValues = z.infer<typeof routeSchema>

type RouteDialogProps = {
    route?: RouteFormValues & { id: number }
    onSuccess?: () => void
}

// Type pour les erreurs d'API
interface ApiError {
    response?: {
        status?: number;
        data?: { message?: string };
    };
    message?: string;
}

export function RouteDialog({ route, onSuccess }: RouteDialogProps) {
    const isEditing = Boolean(route)
    const { addRoute, editRoute } = useRoutes()
    const [open, setOpen] = useState(false)
    const [loading, setLoading] = useState(false)
    const [serverError, setServerError] = useState<string | null>(null)
    const [cities, setCities] = useState<{ id: number; name: string }[]>([])
    const [companies, setCompanies] = useState<{ id: number; name: string }[]>([])
    const [citiesLoading, setCitiesLoading] = useState(true)
    const [companiesLoading, setCompaniesLoading] = useState(true)

    useEffect(() => {
        setCitiesLoading(true)
        setCompaniesLoading(true)

        getAllCities()
            .then(setCities)
            .catch(() => { })
            .finally(() => setCitiesLoading(false))

        getCompanies({ perPage: 1000 })
            .then(res => setCompanies(res.data))
            .catch(() => { })
            .finally(() => setCompaniesLoading(false))
    }, [])

    const cityOptions = cities.map(c => ({ value: c.id, label: c.name }))
    const companyOptions = companies.map(c => ({ value: c.id, label: c.name }))

    const form = useForm<RouteFormValues>({
        resolver: zodResolver(routeSchema),
        defaultValues: {
            departureCityId: route?.departureCityId ?? 0,
            arrivalCityId: route?.arrivalCityId ?? 0,
            basePrice: route?.basePrice ?? (undefined as unknown as number),
            companyId: route?.companyId ?? 0,
        },
    })

    const onSubmit = async (values: RouteFormValues) => {
        setLoading(true)
        setServerError(null)
        try {
            if (isEditing && route) {
                await editRoute(route.id, values)
                toast.success('Route mise à jour !')
            } else {
                await addRoute(values)
                toast.success('Route créée !')
            }
            form.reset()
            setOpen(false)
            onSuccess?.()
        } catch (err: unknown) {
            const error = err as ApiError
            setServerError(error.message || error.response?.data?.message || 'Une erreur inconnue est survenue')
        } finally {
            setLoading(false)
        }
    }

    return (
        <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) setServerError(null) }}>
            <DialogTrigger asChild>
                {isEditing ? (
                    <Button variant="ghost" size="icon">
                        <Pencil className="h-4 w-4" />
                    </Button>
                ) : (
                    <Button size="sm" className="gap-2 text-xs bg-red-600 hover:bg-red-700 text-white">
                        <Plus className="w-3.5 h-3.5" /> Nouvelle route
                    </Button>
                )}
            </DialogTrigger>
            <DialogContent className="sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle>{isEditing ? 'Modifier la route' : 'Ajouter une route'}</DialogTitle>
                    <DialogDescription>
                        {isEditing
                            ? 'Mettez à jour les informations de la route.'
                            : 'Remplissez le formulaire pour créer une nouvelle route.'}
                    </DialogDescription>
                </DialogHeader>

                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        {/* Ville de départ */}
                        <FormField
                            control={form.control}
                            name="departureCityId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Ville de départ*</FormLabel>
                                    <FormControl>
                                        <Select
                                            isSearchable
                                            isDisabled={loading || citiesLoading}
                                            isLoading={citiesLoading}
                                            options={cityOptions}
                                            value={cityOptions.find(o => o.value === field.value) ?? null}
                                            onChange={opt => field.onChange(opt?.value ?? 0)}
                                            placeholder={citiesLoading ? 'Chargement des villes...' : 'Choisissez une ville'}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {/* Ville d'arrivée */}
                        <FormField
                            control={form.control}
                            name="arrivalCityId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Ville d&apos;arrivée*</FormLabel>
                                    <FormControl>
                                        <Select
                                            isSearchable
                                            isDisabled={loading || citiesLoading}
                                            isLoading={citiesLoading}
                                            options={cityOptions}
                                            value={cityOptions.find(o => o.value === field.value) ?? null}
                                            onChange={opt => field.onChange(opt?.value ?? 0)}
                                            placeholder={citiesLoading ? 'Chargement des villes...' : 'Choisissez une ville'}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {/* Compagnie */}
                        <FormField
                            control={form.control}
                            name="companyId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Compagnie*</FormLabel>
                                    <FormControl>
                                        <Select
                                            isSearchable
                                            isDisabled={loading || companiesLoading}
                                            isLoading={companiesLoading}
                                            options={companyOptions}
                                            value={companyOptions.find(o => o.value === field.value) ?? null}
                                            onChange={opt => field.onChange(opt?.value ?? 0)}
                                            placeholder={companiesLoading ? 'Chargement des compagnies...' : 'Choisissez une compagnie'}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {/* Prix de base */}
                        <FormField
                            control={form.control}
                            name="basePrice"
                            render={({ field: { value, onChange, ...fieldRest } }) => (
                                <FormItem>
                                    <FormLabel>Prix de base (FCFA)*</FormLabel>
                                    <FormControl>
                                        <input
                                            type="number"
                                            min={0}
                                            disabled={loading}
                                            placeholder="Ex: 5000"
                                            value={value || value === 0 ? String(value) : ''}
                                            onChange={(e) => {
                                                const v = e.target.value
                                                onChange(v === '' ? undefined : Number(v))
                                            }}
                                            className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
                                            {...fieldRest}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {serverError && (
                            <div className="flex items-start gap-2 rounded-md bg-rose-50 border border-rose-200 px-3 py-2.5 text-sm text-rose-700">
                                <span className="mt-0.5 shrink-0">⚠</span>
                                {serverError}
                            </div>
                        )}

                        <DialogFooter className="justify-between">
                            <Button
                                variant="outline"
                                type="button"
                                onClick={() => setOpen(false)}
                                disabled={loading}
                            >
                                Annuler
                            </Button>
                            <Button type="submit" disabled={loading}>
                                {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                {isEditing ? 'Enregistrer' : 'Créer'}
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    )
}
