import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type { User } from "@/types/api";
import type { UserPayload } from "@/api/users";

const ROLES = ["admin", "manager", "user", "auditor"] as const;

const userSchema = z.object({
  email: z.string().email("Email invalide"),
  name: z.string().min(1, "Le nom est requis"),
  department: z.string(),
  role: z.enum(ROLES),
  is_active: z.boolean(),
  password: z.string().optional(),
});

type UserFormData = z.infer<typeof userSchema>;

interface UserFormProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  user?: User;
  onSubmit: (payload: UserPayload) => void;
  isPending: boolean;
}

export function UserForm({ open, onOpenChange, user, onSubmit, isPending }: UserFormProps) {
  const {
    register,
    handleSubmit,
    reset,
    watch,
    setValue,
    formState: { errors },
  } = useForm<UserFormData>({
    resolver: zodResolver(userSchema),
    defaultValues: { email: "", name: "", department: "", role: "user", is_active: true, password: "" },
  });

  useEffect(() => {
    if (open) {
      reset(
        user
          ? { email: user.email, name: user.name, department: user.department, role: user.role as typeof ROLES[number], is_active: user.is_active, password: "" }
          : { email: "", name: "", department: "", role: "user", is_active: true, password: "" }
      );
    }
  }, [user, open, reset]);

  const isActive = watch("is_active");
  const role = watch("role");

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{user ? "Modifier l'utilisateur" : "Nouvel utilisateur"}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2">
          <div className="space-y-1">
            <Label>Email *</Label>
            <Input {...register("email")} type="email" placeholder="prenom.nom@entreprise.com" />
            {errors.email && <p className="text-xs text-destructive">{errors.email.message}</p>}
          </div>

          <div className="space-y-1">
            <Label>Nom complet *</Label>
            <Input {...register("name")} placeholder="Prénom Nom" />
            {errors.name && <p className="text-xs text-destructive">{errors.name.message}</p>}
          </div>

          <div className="space-y-1">
            <Label>Département</Label>
            <Input {...register("department")} placeholder="ex: finance, engineering, hr" />
          </div>

          <div className="space-y-1">
            <Label>Rôle</Label>
            <Select value={role} onValueChange={(v) => setValue("role", v as typeof ROLES[number])}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {ROLES.map((r) => (
                  <SelectItem key={r} value={r} className="capitalize">{r}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1">
            <Label>
              {user ? "Nouveau mot de passe (laisser vide pour ne pas changer)" : "Mot de passe (optionnel)"}
            </Label>
            <Input {...register("password")} type="password" placeholder="••••••••" autoComplete="new-password" />
          </div>

          <div className="flex items-center gap-3 pt-1">
            <Switch checked={isActive} onCheckedChange={(v) => setValue("is_active", v)} />
            <Label className="cursor-pointer" onClick={() => setValue("is_active", !isActive)}>
              Compte actif
            </Label>
          </div>

          <DialogFooter className="pt-2">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Annuler
            </Button>
            <Button type="submit" disabled={isPending}>
              {isPending ? "Enregistrement..." : user ? "Mettre à jour" : "Créer"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
