import { useState, useEffect } from 'react';
import { Button } from './ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Alert, AlertDescription } from './ui/alert';
import { Fingerprint, Eye, ShieldCheck, AlertCircle } from 'lucide-react';
import { motion } from 'motion/react';

interface BiometricAuthProps {
  onSuccess: () => void;
  onCancel?: () => void;
  title?: string;
  description?: string;
  showCancel?: boolean;
}

export function BiometricAuth({ 
  onSuccess, 
  onCancel, 
  title = "Biometric Authentication",
  description = "Use your fingerprint or face ID to authenticate",
  showCancel = true 
}: BiometricAuthProps) {
  const [isSupported, setIsSupported] = useState(false);
  const [isAuthenticating, setIsAuthenticating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [availableAuthenticators, setAvailableAuthenticators] = useState<string[]>([]);

  useEffect(() => {
    checkBiometricSupport();
  }, []);

  const checkBiometricSupport = async () => {
    if (!window.PublicKeyCredential) {
      setError("Biometric authentication is not supported on this device");
      return;
    }

    try {
      const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
      setIsSupported(available);

      if (available) {
        // Check which authenticators are available
        const authenticators = [];
        
        // Check for fingerprint
        if (navigator.userAgent.includes('Android') || navigator.userAgent.includes('iPhone')) {
          authenticators.push('fingerprint');
        }
        
        // Check for face ID (iOS Safari)
        if (navigator.userAgent.includes('iPhone') && navigator.userAgent.includes('Safari')) {
          authenticators.push('face-id');
        }
        
        // Check for Windows Hello
        if (navigator.userAgent.includes('Windows NT')) {
          authenticators.push('windows-hello');
        }

        setAvailableAuthenticators(authenticators);
      } else {
        setError("No biometric authenticators available on this device");
      }
    } catch (err) {
      console.error('Error checking biometric support:', err);
      setError("Unable to check biometric support");
    }
  };

  const authenticateWithBiometrics = async () => {
    if (!isSupported) {
      setError("Biometric authentication is not supported");
      return;
    }

    setIsAuthenticating(true);
    setError(null);

    try {
      // Create a WebAuthn credential request
      const credential = await navigator.credentials.create({
        publicKey: {
          challenge: new Uint8Array(32), // In production, get this from your server
          rp: {
            name: "Enamel Wallets",
            id: window.location.hostname,
          },
          user: {
            id: new Uint8Array(16),
            name: "user@enamelwallets.com", // In production, use actual user data
            displayName: "User",
          },
          pubKeyCredParams: [
            {
              alg: -7, // ES256
              type: "public-key"
            }
          ],
          authenticatorSelection: {
            authenticatorAttachment: "platform",
            userVerification: "required"
          },
          timeout: 30000,
        }
      });

      if (credential) {
        // Biometric authentication successful
        onSuccess();
      } else {
        throw new Error("Authentication failed");
      }
    } catch (err: any) {
      console.error('Biometric authentication error:', err);
      
      let errorMessage = "Authentication failed";
      
      if (err.name === 'NotAllowedError') {
        errorMessage = "Authentication was cancelled or not allowed";
      } else if (err.name === 'InvalidStateError') {
        errorMessage = "Biometric authentication is already in progress";
      } else if (err.name === 'NotSupportedError') {
        errorMessage = "Biometric authentication is not supported";
      } else if (err.name === 'SecurityError') {
        errorMessage = "Security error occurred during authentication";
      } else if (err.name === 'TimeoutError') {
        errorMessage = "Authentication timed out";
      }
      
      setError(errorMessage);
    } finally {
      setIsAuthenticating(false);
    }
  };

  const getAuthenticatorIcon = () => {
    if (availableAuthenticators.includes('face-id')) {
      return <Eye className="w-8 h-8" />;
    } else if (availableAuthenticators.includes('fingerprint')) {
      return <Fingerprint className="w-8 h-8" />;
    } else {
      return <ShieldCheck className="w-8 h-8" />;
    }
  };

  const getAuthenticatorText = () => {
    if (availableAuthenticators.includes('face-id')) {
      return "Use Face ID";
    } else if (availableAuthenticators.includes('fingerprint')) {
      return "Use Fingerprint";
    } else if (availableAuthenticators.includes('windows-hello')) {
      return "Use Windows Hello";
    } else {
      return "Use Biometric Authentication";
    }
  };

  if (!isSupported && !error) {
    return (
      <Card className="w-full max-w-md mx-auto">
        <CardHeader className="text-center">
          <AlertCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
          <CardTitle>Biometric Authentication Unavailable</CardTitle>
          <CardDescription>
            Your device doesn't support biometric authentication or it's not set up.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {showCancel && (
            <Button onClick={onCancel} variant="outline" className="w-full">
              Continue without Biometrics
            </Button>
          )}
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <motion.div
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ duration: 0.3 }}
          className="flex justify-center mb-4"
        >
          <div className={`w-16 h-16 rounded-full flex items-center justify-center ${
            isAuthenticating ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'
          }`}>
            {getAuthenticatorIcon()}
          </div>
        </motion.div>
        
        <CardTitle>{title}</CardTitle>
        <CardDescription>{description}</CardDescription>
      </CardHeader>
      
      <CardContent className="space-y-4">
        {error && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <Button
          onClick={authenticateWithBiometrics}
          disabled={isAuthenticating || !isSupported}
          className="w-full"
          size="lg"
        >
          {isAuthenticating ? (
            <motion.div
              animate={{ rotate: 360 }}
              transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
              className="w-4 h-4 border-2 border-current border-t-transparent rounded-full mr-2"
            />
          ) : (
            getAuthenticatorIcon()
          )}
          <span className="ml-2">
            {isAuthenticating ? "Authenticating..." : getAuthenticatorText()}
          </span>
        </Button>

        {showCancel && (
          <Button 
            onClick={onCancel} 
            variant="outline" 
            className="w-full"
            disabled={isAuthenticating}
          >
            Cancel
          </Button>
        )}

        {isSupported && (
          <div className="text-center text-xs text-muted-foreground">
            <p>Secure authentication using your device's biometric sensors</p>
            {availableAuthenticators.length > 0 && (
              <p className="mt-1">
                Available: {availableAuthenticators.join(", ").replace("-", " ")}
              </p>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// Hook for biometric authentication
export function useBiometricAuth() {
  const [isSupported, setIsSupported] = useState(false);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    checkSupport();
  }, []);

  const checkSupport = async () => {
    setIsChecking(true);
    try {
      if (window.PublicKeyCredential) {
        const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
        setIsSupported(available);
      }
    } catch (error) {
      console.error('Error checking biometric support:', error);
      setIsSupported(false);
    } finally {
      setIsChecking(false);
    }
  };

  const authenticate = async (): Promise<boolean> => {
    if (!isSupported) {
      throw new Error('Biometric authentication not supported');
    }

    try {
      const credential = await navigator.credentials.create({
        publicKey: {
          challenge: crypto.getRandomValues(new Uint8Array(32)),
          rp: {
            name: "Enamel Wallets",
            id: window.location.hostname,
          },
          user: {
            id: crypto.getRandomValues(new Uint8Array(16)),
            name: "user@enamelwallets.com",
            displayName: "User",
          },
          pubKeyCredParams: [{ alg: -7, type: "public-key" }],
          authenticatorSelection: {
            authenticatorAttachment: "platform",
            userVerification: "required"
          },
          timeout: 30000,
        }
      });

      return !!credential;
    } catch (error) {
      console.error('Biometric authentication failed:', error);
      return false;
    }
  };

  return {
    isSupported,
    isChecking,
    authenticate
  };
}