import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Mail, Lock, User, Building2, Eye, EyeOff } from 'lucide-react';
import { AuthLayout } from '@app/layouts/AuthLayout';
import { Button } from '@components/atoms/Button';
import { FormField } from '@components/molecules/FormField';
import { Alert } from '@components/molecules/Alert';
import { useAuthStore } from '@stores/useAuthStore';

const registerSchema = z.object({
  firstName: z.string().min(2, 'Nombre debe tener al menos 2 caracteres'),
  lastName: z.string().min(2, 'Apellido debe tener al menos 2 caracteres'),
  email: z.string().email('Email inválido'),
  password: z
    .string()
    .min(8, 'La contraseña debe tener al menos 8 caracteres')
    .regex(/[A-Z]/, 'Debe contener al menos una mayúscula')
    .regex(/[a-z]/, 'Debe contener al menos una minúscula')
    .regex(/[0-9]/, 'Debe contener al menos un número'),
  confirmPassword: z.string(),
  companyName: z.string().optional(),
}).refine((data) => data.password === data.confirmPassword, {
  message: 'Las contraseñas no coinciden',
  path: ['confirmPassword'],
});

type RegisterFormData = z.infer<typeof registerSchema>;

export default function RegisterPage() {
  const navigate = useNavigate();
  const { register: registerUser, isLoading, error, clearError } = useAuthStore();
  const [showPassword, setShowPassword] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema),
  });

  const onSubmit = async (data: RegisterFormData) => {
    try {
      await registerUser({
        email: data.email,
        password: data.password,
        firstName: data.firstName,
        lastName: data.lastName,
        companyName: data.companyName,
      });
      navigate('/dashboard', { replace: true });
    } catch {
      // Error is handled in the store
    }
  };

  return (
    <AuthLayout
      title="Crear cuenta"
      subtitle="Completa el formulario para registrarte"
    >
      {error && (
        <Alert variant="danger" onClose={clearError} className="mb-4">
          {error}
        </Alert>
      )}

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <FormField
            label="Nombre"
            placeholder="Juan"
            error={errors.firstName?.message}
            leftIcon={<User className="h-5 w-5" />}
            {...register('firstName')}
          />

          <FormField
            label="Apellido"
            placeholder="Pérez"
            error={errors.lastName?.message}
            {...register('lastName')}
          />
        </div>

        <FormField
          label="Email"
          type="email"
          placeholder="tu@email.com"
          error={errors.email?.message}
          leftIcon={<Mail className="h-5 w-5" />}
          {...register('email')}
        />

        <FormField
          label="Empresa (opcional)"
          placeholder="Mi Empresa S.A."
          error={errors.companyName?.message}
          leftIcon={<Building2 className="h-5 w-5" />}
          {...register('companyName')}
        />

        <FormField
          label="Contraseña"
          type={showPassword ? 'text' : 'password'}
          placeholder="••••••••"
          error={errors.password?.message}
          hint="Mínimo 8 caracteres, con mayúscula, minúscula y número"
          leftIcon={<Lock className="h-5 w-5" />}
          rightIcon={
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="text-gray-400 hover:text-gray-600"
            >
              {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
            </button>
          }
          {...register('password')}
        />

        <FormField
          label="Confirmar contraseña"
          type={showPassword ? 'text' : 'password'}
          placeholder="••••••••"
          error={errors.confirmPassword?.message}
          leftIcon={<Lock className="h-5 w-5" />}
          {...register('confirmPassword')}
        />

        <Button type="submit" fullWidth isLoading={isLoading}>
          Crear cuenta
        </Button>
      </form>

      <p className="mt-6 text-center text-sm text-gray-600">
        ¿Ya tienes cuenta?{' '}
        <Link
          to="/login"
          className="font-medium text-primary-600 hover:text-primary-500"
        >
          Inicia sesión
        </Link>
      </p>
    </AuthLayout>
  );
}
