import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, Key, Eye, EyeOff, Loader2 } from 'lucide-react';
import { useBodyScrollLock } from '../hooks/useBodyScrollLock';

interface ApiKeyModalProps {
  isOpen: boolean;
  onClose: () => void;
  apiKey: string | undefined;
  onSave: (key: string | undefined) => Promise<void>;
  saving: boolean;
  hasAIAccess: boolean;
}

export const ApiKeyModal: React.FC<ApiKeyModalProps> = ({
  isOpen,
  onClose,
  apiKey,
  onSave,
  saving,
  hasAIAccess,
}) => {
  useBodyScrollLock(isOpen);
  const [localApiKey, setLocalApiKey] = useState(apiKey || '');
  const [showApiKey, setShowApiKey] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setLocalApiKey(apiKey || '');
    }
  }, [isOpen, apiKey]);

  if (!isOpen) return null;

  const handleSave = async () => {
    await onSave(localApiKey || undefined);
    onClose();
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.9, opacity: 0 }}
        className="bg-white rounded-2xl max-w-md w-full shadow-xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="p-6 border-b border-gray-100 flex items-center justify-between bg-gradient-to-r from-gray-800 to-gray-900">
          <div className="flex items-center gap-3 text-white">
            <div className="p-2 bg-white/20 rounded-xl">
              <Key size={24} />
            </div>
            <div>
              <h2 className="text-xl font-black">Account Settings</h2>
              <p className="text-sm opacity-80">Manage your API access</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-white/20 rounded-xl transition text-white"
          >
            <X size={24} />
          </button>
        </div>

        <div className="p-6 bg-gray-50">
          {hasAIAccess ? (
            <div>
              <h3 className="font-bold text-gray-800 mb-3 flex items-center gap-2">
                <Key size={18} />
                Custom Gemini API Key
              </h3>
              <p className="text-sm text-gray-500 mb-3">
                Use your own API key for quiz generation. Leave empty to use the system key.
              </p>
              <div className="relative">
                <input
                  type={showApiKey ? 'text' : 'password'}
                  value={localApiKey}
                  onChange={(e) => setLocalApiKey(e.target.value)}
                  placeholder="AIza..."
                  className="w-full px-4 py-3 pr-12 rounded-xl border-2 border-gray-200 focus:border-theme-primary focus:outline-none text-gray-800"
                />
                <button
                  type="button"
                  onClick={() => setShowApiKey(!showApiKey)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showApiKey ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>
            </div>
          ) : (
            <div className="text-center py-4">
              <Key size={32} className="mx-auto mb-3 text-gray-400" />
              <p className="text-gray-500 font-bold">API access not available</p>
              <p className="text-sm text-gray-400 mt-1">Contact an administrator for access</p>
            </div>
          )}
        </div>

        <div className="p-6 border-t border-gray-100 flex gap-3">
          <button
            onClick={onClose}
            className="flex-1 py-3 rounded-xl font-bold border-2 border-gray-200 text-gray-600 hover:bg-gray-50 transition"
          >
            Cancel
          </button>
          {hasAIAccess && (
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex-1 py-3 rounded-xl font-bold bg-gray-800 text-white hover:bg-gray-700 transition disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {saving ? (
                <>
                  <Loader2 size={20} className="animate-spin" />
                  Saving...
                </>
              ) : (
                'Save'
              )}
            </button>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
};
