import { useState } from 'react';
import { toast } from 'sonner';
import { KeyRound } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/Card';
import { useAuth } from 'hooks/useAuth';

export const PasskeyGate = () => {
  const { user, createPasskeyCredentials } = useAuth();
  const [isRegistering, setIsRegistering] = useState(false);

  const handleRegister = async () => {
    if (!user || isRegistering) return;

    setIsRegistering(true);
    try {
      await createPasskeyCredentials(user);
    } catch (ex) {
      const error = ex as { message?: string };
      toast.error(error.message || 'Failed to register passkey. Please try again.');
    } finally {
      setIsRegistering(false);
    }
  };

  return (
    <div className="flex items-center justify-center h-full px-4">
      <Card className="w-full max-w-md p-8">
        <div className="flex flex-col items-center text-center gap-4">
          <div className="rounded-full bg-duck-teal/10 p-4">
            <KeyRound className="h-8 w-8 text-duck-teal" />
          </div>

          <h2 className="text-2xl font-bold text-duck-dark">Set up your passkey</h2>

          <p className="text-duck-dark/70">
            Passkeys provide a secure, passwordless way to access your account. Each device or browser needs its own
            passkey.
          </p>

          <Button
            onClick={handleRegister}
            disabled={isRegistering}
            className="w-full h-11 mt-2 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
          >
            {isRegistering ? 'Registering...' : 'Register Passkey'}
          </Button>
        </div>
      </Card>
    </div>
  );
};
