import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@components/atoms/Button';
import { FormField } from '@components/molecules/FormField';
import { Select } from '@components/organisms/Select';
import { useRoles } from '../hooks';
import type { User, CreateUserDto, UpdateUserDto } from '../types';

const createUserSchema = z.object({
  email: z.string().email('Email inválido'),
  password: z.string().min(8, 'Mínimo 8 caracteres'),
  firstName: z.string().min(2, 'Mínimo 2 caracteres'),
  lastName: z.string().min(2, 'Mínimo 2 caracteres'),
  phone: z.string().optional(),
  roleId: z.string().min(1, 'Selecciona un rol'),
});

const updateUserSchema = z.object({
  firstName: z.string().min(2, 'Mínimo 2 caracteres'),
  lastName: z.string().min(2, 'Mínimo 2 caracteres'),
  phone: z.string().optional(),
  roleId: z.string().min(1, 'Selecciona un rol'),
});

type CreateFormData = z.infer<typeof createUserSchema>;
type UpdateFormData = z.infer<typeof updateUserSchema>;

interface UserFormProps {
  user?: User;
  onSubmit: (data: CreateUserDto | UpdateUserDto) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
}

export function UserForm({ user, onSubmit, onCancel, isLoading }: UserFormProps) {
  const isEditing = !!user;
  const { roles, isLoading: rolesLoading } = useRoles();

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<CreateFormData | UpdateFormData>({
    resolver: zodResolver(isEditing ? updateUserSchema : createUserSchema),
    defaultValues: user
      ? {
          firstName: user.firstName,
          lastName: user.lastName,
          phone: user.phone || '',
          roleId: user.roleId,
        }
      : {
          email: '',
          password: '',
          firstName: '',
          lastName: '',
          phone: '',
          roleId: '',
        },
  });

  const selectedRoleId = watch('roleId');

  const roleOptions = roles.map((role) => ({
    value: role.id,
    label: role.name,
  }));

  const handleFormSubmit = async (data: CreateFormData | UpdateFormData) => {
    await onSubmit(data);
  };

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-4">
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <FormField
          label="Nombre"
          error={errors.firstName?.message}
          required
        >
          <input
            {...register('firstName')}
            type="text"
            className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
            placeholder="Juan"
          />
        </FormField>

        <FormField
          label="Apellido"
          error={errors.lastName?.message}
          required
        >
          <input
            {...register('lastName')}
            type="text"
            className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
            placeholder="Pérez"
          />
        </FormField>
      </div>

      {!isEditing && (
        <>
          <FormField
            label="Email"
            error={(errors as { email?: { message?: string } }).email?.message}
            required
          >
            <input
              {...register('email')}
              type="email"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="juan@ejemplo.com"
            />
          </FormField>

          <FormField
            label="Contraseña"
            error={(errors as { password?: { message?: string } }).password?.message}
            required
          >
            <input
              {...register('password')}
              type="password"
              className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
              placeholder="••••••••"
            />
          </FormField>
        </>
      )}

      <FormField label="Teléfono" error={errors.phone?.message}>
        <input
          {...register('phone')}
          type="tel"
          className="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
          placeholder="+52 55 1234 5678"
        />
      </FormField>

      <FormField label="Rol" error={errors.roleId?.message} required>
        <Select
          options={roleOptions}
          value={selectedRoleId}
          onChange={(value) => setValue('roleId', value as string)}
          placeholder="Seleccionar rol..."
          disabled={rolesLoading}
        />
      </FormField>

      <div className="flex justify-end gap-3 pt-4">
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancelar
        </Button>
        <Button type="submit" isLoading={isLoading}>
          {isEditing ? 'Guardar cambios' : 'Crear usuario'}
        </Button>
      </div>
    </form>
  );
}
