import React, { useEffect, useState } from 'react';
import { Plus, Trash2, Copy, Edit } from 'lucide-react';
import apiKeyService, { APIKey, CreateAPIKeyData, UpdateAPIKeyData } from '../../features/integrations/services/apiKeyService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { formatDate } from '../../shared/utils/format';

const APIKeyManagementPage: React.FC = () => {
  const [apiKeys, setApiKeys] = useState<APIKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingKey, setEditingKey] = useState<APIKey | null>(null);
  const [newKey, setNewKey] = useState<string | null>(null);
  const [_showFullKey, _setShowFullKey] = useState<{ [key: number]: boolean }>({});
  const [formData, setFormData] = useState<CreateAPIKeyData>({
    name: '',
    scopes: [],
    description: '',
    rate_limit: 100,
  });

  const availableScopes = [
    'read:bookings',
    'write:bookings',
    'read:payments',
    'write:payments',
    'read:invoices',
    'write:invoices',
    'read:users',
    'write:users',
  ];

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

  const fetchAPIKeys = async () => {
    try {
      setLoading(true);
      const response = await apiKeyService.getAPIKeys();
      setApiKeys(response.data.api_keys || []);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load API keys');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingKey) {
        await apiKeyService.updateAPIKey(editingKey.id, formData as UpdateAPIKeyData);
        toast.success('API key updated successfully');
        setShowModal(false);
        setEditingKey(null);
        resetForm();
        fetchAPIKeys();
      } else {
        const response = await apiKeyService.createAPIKey(formData);
        toast.success('API key created successfully');
        // SECURITY: Store key temporarily, clear after 5 minutes or on close
        setNewKey(response.data.key);
        setTimeout(() => {
          setNewKey(null);
        }, 5 * 60 * 1000); // Clear after 5 minutes
        setShowModal(false);
        resetForm();
        fetchAPIKeys();
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || `Unable to ${editingKey ? 'update' : 'create'} API key`);
    }
  };

  const handleEdit = (key: APIKey) => {
    setEditingKey(key);
    setFormData({
      name: key.name,
      scopes: key.scopes,
      description: key.description || '',
      rate_limit: key.rate_limit,
      expires_at: key.expires_at || undefined,
    });
    setShowModal(true);
  };

  const handleRevoke = async (id: number) => {
    if (!confirm('Are you sure you want to revoke this API key?')) return;

    try {
      await apiKeyService.revokeAPIKey(id);
      toast.success('API key revoked');
      fetchAPIKeys();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to revoke API key');
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast.success('Copied to clipboard');
  };

  const resetForm = () => {
    setFormData({
      name: '',
      scopes: [],
      description: '',
      rate_limit: 100,
    });
    setEditingKey(null);
  };

  const toggleScope = (scope: string) => {
    setFormData({
      ...formData,
      scopes: formData.scopes.includes(scope)
        ? formData.scopes.filter(s => s !== scope)
        : [...formData.scopes, scope],
    });
  };

  if (loading && apiKeys.length === 0) {
    return <Loading fullScreen text="Loading API keys..." />;
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 sm:gap-6 mb-6 sm:mb-8 md:mb-10 animate-fade-in">
        <div className="w-full lg:w-auto">
          <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
            <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-indigo-400 via-purple-500 to-pink-600 rounded-full"></div>
            <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              API Key Management
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">Manage API keys for third-party access</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="w-full sm:w-auto px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl font-semibold hover:from-blue-700 hover:to-blue-800 shadow-lg hover:shadow-xl transition-all duration-200 flex items-center justify-center gap-2 text-xs sm:text-sm"
        >
          <Plus className="w-4 h-4 sm:w-5 sm:h-5" />
          Create API Key
        </button>
      </div>

      {newKey && (
        <div className="bg-gradient-to-r from-amber-50 to-yellow-50 border-2 border-amber-200 rounded-xl sm:rounded-2xl p-3 sm:p-4 mb-4 sm:mb-6 animate-fade-in shadow-lg">
          <p className="font-semibold mb-2 text-sm sm:text-base text-amber-900">
            ⚠️ SECURITY WARNING: API Key Created (save this now - it will be hidden automatically)
          </p>
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3">
            <code className="flex-1 bg-white p-2 sm:p-3 rounded-lg sm:rounded-xl border-2 border-amber-200 text-xs sm:text-sm font-mono break-all">
              {newKey}
            </code>
            <div className="flex gap-2">
              <button
                onClick={() => {
                  copyToClipboard(newKey);
                  // SECURITY: Clear key from state after copying
                  setTimeout(() => setNewKey(null), 30000); // Clear after 30 seconds
                }}
                className="p-2 sm:p-2.5 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg sm:rounded-xl hover:from-blue-700 hover:to-blue-800 shadow-md hover:shadow-lg transition-all duration-200"
                title="Copy and hide key"
              >
                <Copy className="w-4 h-4" />
              </button>
              <button
                onClick={() => setNewKey(null)}
                className="p-2 sm:p-2.5 bg-slate-200 hover:bg-slate-300 rounded-lg sm:rounded-xl transition-colors"
                title="Hide key immediately"
              >
                ✕
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300">
        {apiKeys.length === 0 ? (
          <div className="text-center py-8 sm:py-12">
            <p className="text-slate-500 text-sm sm:text-base">No API keys configured</p>
          </div>
        ) : (
          <div className="space-y-3 sm:space-y-4">
            {apiKeys.map((key) => (
              <div
                key={key.id}
                className="bg-gradient-to-r from-slate-50 to-white border border-slate-200 rounded-lg sm:rounded-xl p-3 sm:p-4 hover:from-indigo-50 hover:to-purple-50 hover:border-indigo-300 hover:shadow-lg transition-all duration-200"
              >
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-2">
                      <h3 className="font-semibold text-sm sm:text-base md:text-lg truncate">{key.name}</h3>
                      <span className="px-2 sm:px-3 py-1 bg-slate-100 text-slate-700 rounded-lg text-xs font-mono border border-slate-200">
                        {key.key_prefix}...
                      </span>
                      <span className={`px-2 sm:px-3 py-1 rounded-full text-xs font-semibold border shadow-sm ${
                        key.is_active ? 'bg-gradient-to-r from-emerald-50 to-green-50 text-emerald-800 border-emerald-200' :
                        'bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-200'
                      }`}>
                        {key.is_active ? 'Active' : 'Revoked'}
                      </span>
                    </div>
                    <p className="text-slate-600 text-xs sm:text-sm mb-1 sm:mb-2 line-clamp-1">
                      Scopes: {key.scopes.join(', ')}
                    </p>
                    <p className="text-slate-500 text-xs">
                      Rate Limit: {key.rate_limit}/min • Created: {formatDate(key.created_at)}
                      {key.last_used_at && ` • Last Used: ${formatDate(key.last_used_at)}`}
                    </p>
                  </div>
                  <div className="flex gap-2 w-full sm:w-auto">
                    {key.is_active && (
                      <>
                        <button
                          onClick={() => handleEdit(key)}
                          className="p-2 sm:p-2.5 text-blue-600 hover:bg-blue-50 rounded-lg sm:rounded-xl transition-colors flex-shrink-0"
                          title="Edit API key"
                        >
                          <Edit className="w-4 h-4 sm:w-5 sm:h-5" />
                        </button>
                        <button
                          onClick={() => handleRevoke(key.id)}
                          className="px-3 sm:px-4 py-2 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-lg sm:rounded-xl hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl transition-all duration-200 text-xs sm:text-sm font-semibold flex items-center justify-center gap-2"
                        >
                          <Trash2 className="w-4 h-4" />
                          Revoke
                        </button>
                      </>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {showModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-3 sm:p-4">
          <div className="bg-white/95 backdrop-blur-md rounded-xl sm:rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-4 sm:p-5 md:p-6 shadow-2xl border border-slate-200/60">
            <h2 className="text-xl sm:text-2xl font-bold mb-4 sm:mb-5 md:mb-6 text-slate-900">
              {editingKey ? 'Edit API Key' : 'Create API Key'}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">Name</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 sm:px-4 py-2 bg-white border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">Scopes</label>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
                  {availableScopes.map((scope) => (
                    <label key={scope} className="flex items-center gap-2 p-2 hover:bg-slate-50 rounded-lg cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.scopes.includes(scope)}
                        onChange={() => toggleScope(scope)}
                        className="w-4 h-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500"
                      />
                      <span className="text-xs sm:text-sm text-slate-700">{scope}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">Rate Limit (per minute)</label>
                <input
                  type="number"
                  value={formData.rate_limit}
                  onChange={(e) => setFormData({ ...formData, rate_limit: parseInt(e.target.value) })}
                  className="w-full px-3 sm:px-4 py-2 bg-white border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
                  min="1"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">Description</label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 sm:px-4 py-2 bg-white border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
                  rows={3}
                />
              </div>
              <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 sm:gap-4 pt-2">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="flex-1 sm:flex-none px-4 py-2 border-2 border-slate-300 rounded-xl hover:bg-slate-50 transition-all duration-200 text-slate-700 font-medium text-sm sm:text-base"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 sm:flex-none px-4 sm:px-6 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl font-semibold hover:from-blue-700 hover:to-blue-800 shadow-lg hover:shadow-xl transition-all duration-200 text-sm sm:text-base"
                >
                  {editingKey ? 'Update' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default APIKeyManagementPage;

