import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { UserAccountDTO } from '@/types/backend';

const userSchema = z.object({
  username: z.string().min(3, 'Username deve ter no mínimo 3 caracteres').max(50, 'Username deve ter no máximo 50 caracteres'),
  fullName: z.string().min(1, 'Nome completo é obrigatório').max(200, 'Nome completo deve ter no máximo 200 caracteres'),
  email: z.string().email('Email inválido').min(1, 'Email é obrigatório').max(100, 'Email deve ter no máximo 100 caracteres'),
  password: z.string().min(6, 'Password deve ter no mínimo 6 caracteres').max(100, 'Password deve ter no máximo 100 caracteres').optional().or(z.literal('')),
  isActive: z.boolean().default(true),
});

type UserFormData = z.infer<typeof userSchema>;

interface UserFormModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  user?: UserAccountDTO | null;
  onSubmit: (data: UserFormData) => Promise<void>;
}

export function UserFormModal({ open, onOpenChange, user, onSubmit }: UserFormModalProps) {
  const form = useForm<UserFormData>({
    resolver: zodResolver(userSchema),
    defaultValues: {
      username: '',
      fullName: '',
      email: '',
      password: '',
      isActive: true,
    },
  });

  useEffect(() => {
    if (user) {
      form.reset({
        username: user.username,
        fullName: user.fullName,
        email: user.email,
        password: '', // Não preencher password ao editar
        isActive: user.isActive,
      });
    } else {
      form.reset({
        username: '',
        fullName: '',
        email: '',
        password: '',
        isActive: true,
      });
    }
  }, [user, open, form]);

  const handleSubmit = async (data: UserFormData) => {
    // Se é edição e password está vazio, remover do payload
    const submitData = { ...data };
    if (user && !submitData.password) {
      delete submitData.password;
    }
    await onSubmit(submitData);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>{user ? 'Editar Utilizador' : 'Novo Utilizador'}</DialogTitle>
          <DialogDescription>
            {user
              ? 'Atualize as informações do utilizador'
              : 'Preencha os dados para criar um novo utilizador'}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Username</FormLabel>
                  <FormControl>
                    <Input placeholder="johndoe" {...field} disabled={!!user} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="fullName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Nome Completo</FormLabel>
                  <FormControl>
                    <Input placeholder="João Silva" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input type="email" placeholder="joao@example.com" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Password {user && '(deixe em branco para manter)'}</FormLabel>
                  <FormControl>
                    <Input type="password" placeholder="••••••••" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="isActive"
              render={({ field }) => (
                <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                  <FormControl>
                    <Checkbox
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                  <div className="space-y-1 leading-none">
                    <FormLabel>Utilizador Activo</FormLabel>
                  </div>
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
              >
                Cancelar
              </Button>
              <Button type="submit" disabled={form.formState.isSubmitting}>
                {form.formState.isSubmitting
                  ? 'A guardar...'
                  : user
                  ? 'Atualizar'
                  : 'Criar'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}

