import { useNavigate, Link } from 'react-router-dom';
import {
  RegisterForm,
  RegisterFormData,
} from '@/components/forms/RegisterForm';
import { useAuthStore } from '@/features/auth/store/authStore';
import { formatErrorMessage, parseApiError } from '@/utils/apiErrorHandler';
import { useToast } from '@/hooks/useToast';
import type { ApiError } from '@/schemas/apiSchemas';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useState } from 'react';

export function Register() {
  const navigate = useNavigate();
  const { success, error: showToastError } = useToast();
  const { register: registerStore, error: storeError } = useAuthStore();
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (data: RegisterFormData) => {
    try {
      setError(null);

      // Le store gère déjà le register et le stockage des tokens
      await registerStore({
        email: data.email,
        username: data.username,
        password: data.password,
        password_confirm: data.passwordConfirm,
      });

      // Show success message
      success('Registration successful! Welcome to Veza.');

      // Redirect to dashboard
      navigate('/dashboard');
    } catch (err: unknown) {
      // Handle error avec formatErrorMessage
      const apiError = parseApiError(err);
      const errorMessage = formatErrorMessage(apiError);
      setError(errorMessage);
      showToastError(errorMessage);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="space-y-1">
          <CardTitle className="text-2xl text-center">
            Create an account
          </CardTitle>
          <CardDescription className="text-center">
            Enter your information to create your account
          </CardDescription>
        </CardHeader>
        <CardContent>
          {(error || storeError) && (
            <Alert variant="destructive" className="mb-4">
              <AlertDescription>
                {error || formatErrorMessage(storeError as ApiError)}
              </AlertDescription>
            </Alert>
          )}
          <RegisterForm onSubmit={handleSubmit} />
          <div className="mt-4 text-center text-sm">
            Already have an account?{' '}
            <Link to="/login" className="text-primary hover:underline">
              Sign in
            </Link>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
