import { useLoginFlow } from '@/hooks/useLoginFlow';
import { LocalLoginForm } from '@/components/auth/LocalLoginForm';
import { MfaForm } from '@/components/auth/MfaForm';
import { Card, CardContent } from '@/components/ui/Card';
import LogoGise from '@/components/ui/LogoGise';
import { Button } from '@/components/ui/Button';
import { GlobeLock } from 'lucide-react';
import Badge from '@/components/ui/Badge';

interface LoginProps {
  onLoginSuccess: () => void;
}

export default function Login({ onLoginSuccess }: LoginProps) {
  const {
    step, isLoading, error, mfaConfig,
    loginWithZitadel, loginWithLocal, verifyMfa, cancelMfa
  } = useLoginFlow(onLoginSuccess);

  return (
    <div className="min-h-screen bg-[#e8e8e8] dark:bg-[#1e293b] flex flex-col justify-center py-12 sm:px-6 lg:px-8 font-sans selection:bg-blue-900 selection:text-white">

      {/* HEADER LOGO */}
      <LogoGise />

      {/* BOÎTE CENTRALE DÉCLINÉE AVEC NOTRE OBJET CARD */}
      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md justify-center flex">
        <Card>
          <CardContent className="p-6 sm:p-10">

            {/* AFFICHAGE DES ERREURS GLOBALES */}
            {error && (
              <div className="mb-6 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm font-medium animate-in fade-in slide-in-from-top-1">
                {error}
              </div>
            )}

            {/* ROUTAGE INTERNE DES ÉTAPES */}
            {step === 1 ? (
              <div className="space-y-6 items-center">
                <Button
                  type="button"
                  onClick={loginWithZitadel}
                  disabled={isLoading}
                  leftIcon={<GlobeLock className="w-5 h-5 mr-2 text-blue-900" />}>
                  {isLoading ? 'Connexion en cours...' : 'Connexion via GISE Identity'}
                </Button>

                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <div className="w-full border-t border-slate-200" />
                  </div>
                  <div className="relative flex justify-center text-sm">
                    <Badge name="Ou via authentification classique"></Badge>
                  </div>
                </div>

                <LocalLoginForm onSubmit={loginWithLocal} isLoading={isLoading} />
              </div>
            ) : (
              <MfaForm
                isFirstSetup={mfaConfig?.isFirstSetup || false}
                qrUrl={mfaConfig?.qrUrl || ''}
                isLoading={isLoading}
                onVerify={verifyMfa}
                onCancel={cancelMfa}
              />
            )}

          </CardContent>
        </Card>
      </div>

    </div>
  );
}