'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Button, Input, Label, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@horux/shared-ui';
import { register } from '@/lib/api/auth';
import { useAuthStore } from '@/stores/auth-store';

export default function RegisterPage() {
  const router = useRouter();
  const { setUser, setTokens } = useAuthStore();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [acceptedTerms, setAcceptedTerms] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!acceptedTerms) {
      setError('Debes aceptar los términos y condiciones para continuar.');
      return;
    }
    setIsLoading(true);
    setError('');

    const formData = new FormData(e.currentTarget);

    try {
      const response = await register({
        empresa: {
          nombre: formData.get('empresaNombre') as string,
          rfc: formData.get('empresaRfc') as string,
        },
        usuario: {
          nombre: formData.get('nombre') as string,
          email: formData.get('email') as string,
          password: formData.get('password') as string,
        },
      });
      setTokens(response.accessToken, response.refreshToken);
      setUser(response.user);
      router.push('/dashboard');
    } catch (err: any) {
      setError(err.response?.data?.message || 'Error al registrarse');
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
    <Card className="w-full max-w-md">
      <CardHeader className="text-center">
        <CardTitle className="text-2xl">Crear Cuenta</CardTitle>
        <CardDescription>
          Registra tu empresa y comienza tu prueba gratuita
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit}>
        <CardContent className="space-y-4">
          {error && (
            <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
              {error}
            </div>
          )}

          <div className="space-y-2">
            <Label className="text-xs text-muted-foreground uppercase tracking-wide">
              Datos de la Empresa
            </Label>
            <Input
              name="empresaNombre"
              placeholder="Nombre de la empresa"
              required
            />
            <Input
              name="empresaRfc"
              placeholder="RFC (ej: ABC123456XY1)"
              maxLength={13}
              required
            />
          </div>

          <div className="space-y-2">
            <Label className="text-xs text-muted-foreground uppercase tracking-wide">
              Datos del Dueño
            </Label>
            <Input
              name="nombre"
              placeholder="Tu nombre completo"
              required
            />
            <Input
              name="email"
              type="email"
              placeholder="tu@email.com"
              required
            />
            <Input
              name="password"
              type="password"
              placeholder="Contraseña (mín. 8 caracteres)"
              minLength={8}
              required
            />
          </div>

          <label className="flex items-start gap-2 text-sm cursor-pointer select-none pt-2">
            <input
              type="checkbox"
              checked={acceptedTerms}
              onChange={(e) => setAcceptedTerms(e.target.checked)}
              className="mt-0.5 h-4 w-4 rounded border-input accent-primary cursor-pointer"
              required
            />
            <span className="text-muted-foreground">
              Acepto los{' '}
              <Link
                href="/terminos"
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary underline hover:no-underline"
              >
                Términos y Condiciones
              </Link>
              {' '}de Horux 360.
            </span>
          </label>
        </CardContent>
        <CardFooter className="flex flex-col gap-4">
          <Button type="submit" className="w-full" disabled={isLoading || !acceptedTerms}>
            {isLoading ? 'Creando cuenta...' : 'Crear Cuenta Gratis'}
          </Button>
          <p className="text-sm text-muted-foreground text-center">
            ¿Ya tienes cuenta?{' '}
            <Link href="/login" className="text-primary hover:underline">
              Inicia sesión
            </Link>
          </p>
        </CardFooter>
      </form>
    </Card>
    </div>
  );
}
