import { useNavigate, Link } from 'react-router-dom';
import { RegisterForm, RegisterFormData } from '@/components/forms/RegisterForm';
import { register } from '@/services/api/auth';
import { tokenManager } from '@/utils/token-manager';
import { useToast } from '@/hooks/useToast';
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: showErrorToast } = useToast();
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

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

      // Call registration API
      const response = await register({
        email: data.email,
        password: data.password,
        password_confirm: data.passwordConfirm,
      });

      // Store tokens using tokenManager (already done by register service, but we ensure it)
      // The register service already stores tokens in localStorage, but we use tokenManager for consistency
      tokenManager.setTokens(
        response.token.access_token,
        response.token.refresh_token,
        false
      );

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

      // Redirect to dashboard
      navigate('/dashboard');
    } catch (err: any) {
      // Handle error
      const errorMessage = err?.message || err?.response?.data?.error || 'Registration failed. Please try again.';
      setError(errorMessage);
      showErrorToast(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  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 && (
            <Alert variant="destructive" className="mb-4">
              <AlertDescription>{error}</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>
  );
}

