'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useForm, type Resolver } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
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, Eye, EyeOff, AlertCircle } from 'lucide-react'
import Select from 'react-select'
import { useUsers } from '@/contexts/UsersContext'
import { useCompanies } from '@/contexts/CompaniesContext'
import { Checkbox } from '@/components/ui/checkbox'

const roles = [
  { value: 'validation_agent', label: 'Agent de validation' },
  { value: 'kalale_agent', label: 'Agent Kalalé' },
  { value: 'company_admin', label: 'Admin Compagnie' },
  { value: 'company_agent', label: 'Agent Compagnie' },
  { value: 'ticketing_agent', label: 'Guichetier' },
  { value: 'customer', label: 'Client' },
]

const emptyToUndefined = <T extends z.ZodTypeAny>(schema: T) =>
  z.preprocess(value => {
    if (typeof value === 'string') {
      const trimmed = value.trim()
      return trimmed === '' ? undefined : trimmed
    }
    return value
  }, schema)

const createUserSchema = z.object({
  email: z.string().email('Email invalide'),
  phone: z
    .string()
    .min(8, 'Numéro trop court')
    .regex(/^\+?\d{8,15}$/, 'Numéro de téléphone invalide'),
  password: z
    .string()
    .min(4, 'Le mot de passe doit contenir au moins 4 caractères')
    .max(8, 'Le mot de passe doit contenir au plus 8 caractères'),
  password_confirmation: z.string(),
  firstName: z.string().min(2, 'Prénom requis'),
  lastName: z.string().min(2, 'Nom requis'),
  role: z.string().min(1, 'Rôle requis'),
  companyId: z.number().optional(),
}).refine(data => data.password === data.password_confirmation, {
  message: 'Les mots de passe ne correspondent pas',
  path: ['password_confirmation'],
}).refine(data => {
  // Si le rôle nécessite une compagnie, companyId est requis
  if (['company_admin', 'company_agent', 'ticketing_agent'].includes(data.role)) {
    return data.companyId !== undefined && data.companyId > 0;
  }
  return true;
}, {
  message: 'Une compagnie est requise pour ce rôle',
  path: ['companyId'],
})

const updateSchema = z.object({
  email: emptyToUndefined(z.string().email('Email invalide').optional()),
  phone: z.string().min(8),
  password: emptyToUndefined(
    z
      .string()
      .min(4, 'Le mot de passe doit contenir au moins 4 caractères')
      .max(8, 'Le mot de passe doit contenir au plus 8 caractères')
      .optional()
  ),
  password_confirmation: emptyToUndefined(z.string().optional()),
  firstName: z.string().min(2),
  lastName: z.string().min(2),
  role: z.string().min(1),
  companyId: z.number().optional(),
}).refine(data => !data.password || data.password === data.password_confirmation, {
  message: 'Les mots de passe ne correspondent pas',
  path: ['password_confirmation'],
})

type CreateUserFormValues = z.infer<typeof createUserSchema>
type UpdateUserFormValues = z.infer<typeof updateSchema>
type FormValues = {
  email?: string
  phone: string
  password?: string
  password_confirmation?: string
  firstName: string
  lastName: string
  role: string
  companyId?: number
}

// Type pour les utilisateurs
interface User {
  id: number;
  email: string;
  phone: string;
  firstName: string;
  lastName: string;
  role: string;
  companyId?: number;
  companyName?: string | null;
}

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

export function UserDialog({ user, onSuccess }: { user?: User; onSuccess?: () => void }) {
  const isEditing = Boolean(user)
  const { addUser, editUser } = useUsers()
  const { companies, fetchCompanies } = useCompanies()
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [formError, setFormError] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)
  const [editPassword, setEditPassword] = useState(false)
  const router = useRouter()

  const form = useForm<FormValues>({
    resolver: zodResolver(isEditing ? updateSchema : createUserSchema) as unknown as Resolver<FormValues>,
    defaultValues: {
      email: user?.email ?? '',
      phone: user?.phone ?? '',
      password: '',
      password_confirmation: '',
      firstName: user?.firstName ?? '',
      lastName: user?.lastName ?? '',
      role: user?.role ?? '',
      companyId: user?.companyId ?? undefined,
    },
  })

  // Charger les compagnies au montage du composant
  useEffect(() => {
    fetchCompanies()
  }, [fetchCompanies])

  const onSubmit = async (values: FormValues) => {
    setLoading(true)
    setFormError(null)
    try {
      if (isEditing && user) {
        const updateValues: Partial<UpdateUserFormValues> = { ...(values as UpdateUserFormValues) }
        if (!editPassword) {
          delete updateValues.password;
          delete updateValues.password_confirmation;
        }
        if (!updateValues.email) {
          delete updateValues.email;
        }
        await editUser(user.id, updateValues as Parameters<typeof editUser>[1])
        toast.success('Utilisateur modifié')
      } else {
        await addUser(values as CreateUserFormValues)
        toast.success('Utilisateur créé')
      }
      form.reset()
      setEditPassword(false)
      setShowPassword(false)
      setOpen(false)
      onSuccess?.()
      router.refresh()
    } catch (err: unknown) {
      const error = err as ApiError
      setFormError(error.message || error.response?.data?.message || 'Une erreur est survenue')
    } finally {
      setLoading(false)
    }
  }
  

  return (
    <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) setFormError(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" /> Nouvel utilisateur
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{isEditing ? 'Modifier utilisateur' : 'Ajouter un utilisateur'}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? 'Modifiez les informations de l&apos;utilisateur.'
              : 'Remplissez les champs pour créer un nouvel utilisateur.'}
          </DialogDescription>
        </DialogHeader>

        {formError && (
          <div className="flex items-start gap-2.5 bg-red-50 border border-red-100 rounded-lg px-3 py-2.5 -mt-1">
            <AlertCircle className="w-4 h-4 text-red-500 mt-0.5 flex-shrink-0" />
            <p className="text-sm text-red-600">{formError}</p>
          </div>
        )}

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField control={form.control} name="email" render={({ field }) => (
              <FormItem>
                <FormLabel>Email{isEditing ? '' : '*'}</FormLabel>
                <FormControl><Input disabled={loading} {...field} /></FormControl>
                <FormMessage />
              </FormItem>
            )} />

            <FormField control={form.control} name="phone" render={({ field }) => (
              <FormItem>
                <FormLabel>Téléphone*</FormLabel>
                <FormControl><Input disabled={loading} {...field} /></FormControl>
                <FormMessage />
              </FormItem>
            )} />

            {!isEditing || editPassword ? (
              <div className="flex gap-4">
                <FormField control={form.control} name="password" render={({ field }) => (
                  <FormItem className="flex-1">
                    <FormLabel>Mot de passe*</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input type={showPassword ? 'text' : 'password'} disabled={loading} {...field} />
                        <Button
                          type="button"
                          variant="ghost"
                          className="absolute right-2 top-1/2 -translate-y-1/2"
                          onClick={() => setShowPassword(prev => !prev)}
                        >
                          {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </Button>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
                <FormField control={form.control} name="password_confirmation" render={({ field }) => (
                  <FormItem className="flex-1">
                    <FormLabel>Confirmation*</FormLabel>
                    <FormControl>
                      <Input type={showPassword ? 'text' : 'password'} disabled={loading} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
              </div>
            ) : isEditing && (
              <div className="flex items-center space-x-2">
                <Checkbox id="editPassword" checked={editPassword} onCheckedChange={() => setEditPassword(!editPassword)} />
                <label htmlFor="editPassword" className="text-sm">Modifier le mot de passe</label>
              </div>
            )}

            <FormField control={form.control} name="firstName" render={({ field }) => (
              <FormItem>
                <FormLabel>Prénom*</FormLabel>
                <FormControl><Input disabled={loading} {...field} /></FormControl>
                <FormMessage />
              </FormItem>
            )} />

            <FormField control={form.control} name="lastName" render={({ field }) => (
              <FormItem>
                <FormLabel>Nom*</FormLabel>
                <FormControl><Input disabled={loading} {...field} /></FormControl>
                <FormMessage />
              </FormItem>
            )} />

            <FormField control={form.control} name="role" render={({ field }) => (
              <FormItem>
                <FormLabel>Rôle*</FormLabel>
                <FormControl>
                  <Select
                    isSearchable
                    options={roles}
                    value={roles.find(o => o.value === field.value) ?? null}
                    onChange={opt => {
                      field.onChange(opt?.value ?? '')
                      // Réinitialiser companyId si le rôle change
                      if (opt?.value && !['company_admin', 'company_agent', 'ticketing_agent'].includes(opt.value)) {
                        form.setValue('companyId', undefined)
                      }
                    }}
                    placeholder="Sélectionner un rôle"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )} />

            {/* Champ compagnie - affiché seulement pour les rôles qui nécessitent une compagnie */}
            {['company_admin', 'company_agent', 'ticketing_agent'].includes(form.watch('role')) && (
              <FormField control={form.control} name="companyId" render={({ field }) => (
                <FormItem>
                  <FormLabel>Compagnie*</FormLabel>
                  <FormControl>
                    <Select
                      isSearchable
                      options={companies.map(company => ({
                        value: company.id,
                        label: company.name
                      }))}
                      value={companies.find(c => c.id === field.value) ? {
                        value: field.value,
                        label: companies.find(c => c.id === field.value)?.name || ''
                      } : null}
                      onChange={opt => field.onChange(opt?.value)}
                      placeholder="Sélectionner une compagnie"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />
            )}

            <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>
  )
}
