import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { Lock, Eye, EyeOff, AlertCircle } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useSecurity } from '@/contexts/SecurityContext';
import { toast } from 'sonner';
import { appleFadeIn, appleSpring } from '@/lib/apple-animations';

interface SecureUnlockDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  itemId: string;
  itemName: string;
  itemType: 'note' | 'folder';
  onUnlocked: (password?: string) => void;
}

export function SecureUnlockDialog({
  open,
  onOpenChange,
  itemId,
  itemName,
  itemType,
  onUnlocked,
}: SecureUnlockDialogProps) {
  const { unlockItem } = useSecurity();
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isUnlocking, setIsUnlocking] = useState(false);
  const [error, setError] = useState('');

  const handleUnlock = async () => {
    const trimmedPassword = password.trim();
    if (!trimmedPassword) {
      setError('Please enter your security password');
      return;
    }

    setIsUnlocking(true);
    setError('');

    try {
      const success = await unlockItem(itemId, trimmedPassword);
      if (success) {
        setPassword('');
        setError('');
        toast.success(`${itemType === 'note' ? 'Note' : 'Folder'} unlocked`);
        onUnlocked(trimmedPassword);
        onOpenChange(false);
      } else {
        setError('Incorrect password. Please try again.');
      }
    } catch (err: any) {
      console.error('Unlock error:', err);
      setError(err.message || 'Failed to unlock. Please try again.');
    } finally {
      setIsUnlocking(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isUnlocking) {
      handleUnlock();
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange} modal={true}>
      <DialogContent 
        className="sm:max-w-md"
        onInteractOutside={(e) => {
          if (isUnlocking) {
            e.preventDefault();
          }
        }}
        onEscapeKeyDown={(e) => {
          if (isUnlocking) {
            e.preventDefault();
          }
        }}
      >
        <DialogHeader>
          <motion.div 
            {...appleFadeIn}
            transition={appleSpring}
            className="flex items-center gap-3 mb-2"
          >
            <div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center">
              <Lock className="h-6 w-6 text-primary" />
            </div>
            <div>
              <DialogTitle>Unlock Secure {itemType === 'note' ? 'Note' : 'Folder'}</DialogTitle>
              <DialogDescription className="mt-1">
                This {itemType} is protected. Enter your security password to access it.
              </DialogDescription>
            </div>
          </motion.div>
        </DialogHeader>

        <form 
          onSubmit={(e) => {
            e.preventDefault();
            handleUnlock();
          }}
          className="space-y-4 py-4"
        >
          <div className="p-3 rounded-lg bg-muted/50 border border-border">
            <p className="text-sm font-medium mb-1">{itemName}</p>
            <p className="text-xs text-muted-foreground">
              This {itemType} will remain unlocked for 10 minutes
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="security-password">Security Password</Label>
            <div className="relative">
              <Input
                id="security-password"
                type={showPassword ? 'text' : 'password'}
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value);
                  setError('');
                }}
                onKeyPress={handleKeyPress}
                placeholder="Enter your security password"
                className={error ? 'border-destructive' : ''}
                disabled={isUnlocking}
                autoFocus
                autoComplete="current-password"
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? (
                  <EyeOff className="h-4 w-4" />
                ) : (
                  <Eye className="h-4 w-4" />
                )}
              </Button>
            </div>
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex items-center gap-2 text-sm text-destructive"
              >
                <AlertCircle className="h-4 w-4" />
                <span>{error}</span>
              </motion.div>
            )}
          </div>

          <div className="flex gap-2 pt-2">
            <Button
              type="button"
              variant="outline"
              className="flex-1"
              onClick={() => {
                onOpenChange(false);
                setPassword('');
                setError('');
              }}
              disabled={isUnlocking}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              className="flex-1"
              disabled={isUnlocking || !password.trim()}
            >
              {isUnlocking ? (
                <>
                  <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin mr-2" />
                  Unlocking...
                </>
              ) : (
                <>
                  <Lock className="h-4 w-4 mr-2" />
                  Unlock
                </>
              )}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
