'use client'

import { useState } from 'react'
import * as z from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { createInfluencer } from '@/lib/influencers'
import { Loader2, Megaphone, Plus, AlertCircle, Eye, EyeOff } from 'lucide-react'

const TRANSLATIONS: Record<string, string> = {
  'the phone has already been taken':  'Ce numéro de téléphone est déjà utilisé',
  'the email has already been taken':  'Cet email est déjà utilisé',
  'the promo code has already been taken': 'Ce code promo est déjà utilisé',
}

function parseApiError(error: unknown): string {
  const e = error as { response?: { data?: { errors?: { message: string }[]; message?: string } } }
  const data = e?.response?.data

  if (Array.isArray(data?.errors) && data.errors.length > 0) {
    return data.errors
      .map(err => TRANSLATIONS[err.message.toLowerCase()] ?? err.message)
      .join(' · ')
  }
  if (data?.message) return data.message
  return "Une erreur est survenue. Veuillez réessayer."
}

const emptyToUndefined = (value: unknown) => {
  if (typeof value === 'string') {
    const trimmed = value.trim()
    return trimmed === '' ? undefined : trimmed
  }
  return value
}

const schema = z.object({
  firstName: z.string().min(2, 'Prénom requis'),
  lastName: z.string().min(2, 'Nom requis'),
  email: z.string().email('Email invalide').optional().transform((v) => emptyToUndefined(v) as string | undefined),
  phone: z.string().min(8, 'Téléphone invalide'),
  password: z.string().min(4, '4 caractères min').max(8, '8 caractères max'),
  password_confirmation: z.string().min(4, 'Confirmation requise'),
  promoCode: z
    .string()
    .trim()
    .min(3, 'Au moins 3 caractères')
    .max(50, '50 caractères max')
    .regex(/^[A-Za-z0-9_-]+$/, 'Lettres, chiffres, - et _ uniquement'),
  payoutPerSignup: z.coerce
    .number({ invalid_type_error: 'Montant requis' })
    .min(1, "Doit être supérieur à 0, sinon l'influenceur ne gagne rien"),
  status: z.enum(['active', 'inactive']),
  socialHandle: z.string().max(120).optional().transform((v) => emptyToUndefined(v) as string | undefined),
  notes: z.string().max(255).optional().transform((v) => emptyToUndefined(v) as string | undefined),
}).refine((data) => data.password === data.password_confirmation, {
  message: 'Les mots de passe doivent correspondre',
  path: ['password_confirmation'],
})

type FormValues = z.infer<typeof schema>

export function NewInfluencerDialog({ onCreated }: { onCreated?: () => void }) {
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [formError, setFormError] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)
  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      firstName: '',
      lastName: '',
      email: '',
      phone: '',
      password: '',
      password_confirmation: '',
      promoCode: '',
      payoutPerSignup: 100,
      status: 'active',
      socialHandle: '',
      notes: '',
    },
  })

  const onSubmit = async (values: FormValues) => {
    setLoading(true)
    setFormError(null)
    try {
      await createInfluencer({
        ...values,
        promoCode: values.promoCode.toUpperCase(),
      })
      toast.success('Influenceur créé')
      setOpen(false)
      form.reset()
      onCreated?.()
    } catch (error: unknown) {
      setFormError(parseApiError(error))
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={v => { setOpen(v); if (!v) setFormError(null) }}>
      <DialogTrigger asChild>
        <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 influenceur
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>Ajouter un influenceur</DialogTitle>
          <DialogDescription>Créez un compte et assignez un code promo unique.</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="grid gap-4">
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="firstName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Prénom</FormLabel>
                    <FormControl>
                      <Input placeholder="Aminata" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="lastName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Nom</FormLabel>
                    <FormControl>
                      <Input placeholder="Traoré" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email (optionnel)</FormLabel>
                    <FormControl>
                      <Input type="email" placeholder="email@exemple.com" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="phone"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Téléphone</FormLabel>
                    <FormControl>
                      <Input placeholder="70 00 00 00" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Mot de passe</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input type={showPassword ? 'text' : 'password'} {...field} className="pr-10" />
                        <button
                          type="button"
                          onClick={() => setShowPassword(v => !v)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                          tabIndex={-1}
                        >
                          {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>
                    <FormLabel>Confirmation</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input type={showPassword ? 'text' : 'password'} {...field} className="pr-10" />
                        <button
                          type="button"
                          onClick={() => setShowPassword(v => !v)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                          tabIndex={-1}
                        >
                          {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="promoCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Code promo</FormLabel>
                    <FormControl>
                      <Input placeholder="SAPSAPTIK" {...field} className="uppercase" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="payoutPerSignup"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Gain par inscription (F CFA)</FormLabel>
                    <FormControl>
                      <Input type="number" step="100" min="100" placeholder="1000" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Statut</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Sélectionner" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="active">Actif</SelectItem>
                        <SelectItem value="inactive">Inactif</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="socialHandle"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Profil social (optionnel)</FormLabel>
                    <FormControl>
                      <Input placeholder="@sap_influence" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="notes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Notes internes</FormLabel>
                  <FormControl>
                    <textarea
                      rows={3}
                      placeholder="Canal, partenaire, etc."
                      {...field}
                      className="min-h-[90px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="submit" disabled={loading} className="gap-2">
                {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Megaphone className="h-4 w-4" />}
                {loading ? 'Création...' : 'Créer'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
