// components/stations/station-dialog.tsx
'use client'

import { useState, useEffect } from 'react'
import { Controller, 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 { useStations } from '@/contexts/StationsContext'
import { getAllCities } from '@/lib/cities'
import { getCompanies } from '@/lib/companies'
import { Plus, Pencil, Loader2 } from 'lucide-react'

// Zod schema
const stationSchema = z.object({
  name: z.string().min(2, 'Le nom doit contenir au moins 2 caractères'),
  address: z.string().min(5, 'L\'adresse doit contenir au moins 5 caractères'),
  cityId: z.number({ invalid_type_error: 'La ville est requise' }),
  companyId: z.number().optional(),
})

type StationFormValues = z.infer<typeof stationSchema>

type StationDialogProps = {
  station?: {
    id: number
    name: string
    address: string
    cityId: number
    companyId?: number | null
  }
  onSuccess?: () => void
}

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

export function StationDialog({ station, onSuccess }: StationDialogProps) {
  const isEditing = Boolean(station)
  const { addStation, editStation } = useStations()
  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 }[]>([])

  // Load options once
  useEffect(() => {
    getAllCities()
      .then(list => setCities(list))
      .catch(() => {})
    getCompanies({ perPage: 1000 })
      .then(res => setCompanies(res.data))
      .catch(() => {})
  }, [])

  // Map to react-select options
  const cityOptions = cities.map(c => ({ value: c.id, label: c.name }))
  const companyOptions = companies.map(c => ({ value: c.id, label: c.name }))

  // Form setup
  const form = useForm<StationFormValues>({
    resolver: zodResolver(stationSchema),
    defaultValues: {
      name: station?.name ?? '',
      address: station?.address ?? '',
      cityId: station?.cityId ?? 0,
      companyId: station?.companyId ?? undefined,
    },
  })

  const onSubmit = async (values: StationFormValues) => {
    setLoading(true)
    setServerError(null)
    try {
      const payload = {
        name: values.name.trim(),
        address: values.address.trim(),
        cityId: values.cityId,
        companyId: values.companyId,
      }
      if (isEditing && station) {
        await editStation(station.id, payload)
        toast.success('Station mise à jour !')
      } else {
        await addStation(payload)
        toast.success('Station 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 station
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{isEditing ? 'Modifier la station' : 'Ajouter une station'}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? 'Mettez à jour les informations de la station.'
              : 'Remplissez le formulaire pour créer une nouvelle station.'}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            {/* Nom */}
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Nom*</FormLabel>
                  <FormControl>
                    <Input disabled={loading} placeholder="Ex: Station A" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Adresse */}
            <FormField
              control={form.control}
              name="address"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Adresse*</FormLabel>
                  <FormControl>
                    <Input disabled={loading} placeholder="Ex: 123 rue..." {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Ville */}
            <FormField
              control={form.control}
              name="cityId"
              render={() => (
                <FormItem>
                  <FormLabel>Ville*</FormLabel>
                  <FormControl>
                    <Controller
                      control={form.control}
                      name="cityId"
                      render={({ field }) => (
                        <Select
                          isSearchable
                          options={cityOptions}
                          value={cityOptions.find(o => o.value === field.value) ?? null}
                          onChange={opt => field.onChange(opt?.value ?? 0)}
                          placeholder="Recherchez une ville..."
                        />
                      )}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Compagnie */}
            <FormField
              control={form.control}
              name="companyId"
              render={() => (
                <FormItem>
                  <FormLabel>Compagnie</FormLabel>
                  <FormControl>
                    <Controller
                      control={form.control}
                      name="companyId"
                      render={({ field }) => (
                        <Select
                          isClearable
                          isSearchable
                          options={companyOptions}
                          value={companyOptions.find(o => o.value === field.value) ?? null}
                          onChange={opt => field.onChange(opt?.value)}
                          placeholder="Recherchez une compagnie..."
                        />
                      )}
                    />
                  </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>
  )
}
