import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../services/api';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { Plus, Trash2, Eye, EyeOff } from 'lucide-react';

interface ApiKey {
  id: number;
  provider: string;
  keyName: string;
  isActive: boolean;
  rateLimitPerMinute?: number;
  rateLimitPerDay?: number;
  expiresAt?: string;
  createdAt: string;
}

export default function ApiKeys() {
  const [showAddModal, setShowAddModal] = useState(false);
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery<{ apiKeys: ApiKey[] }>({
    queryKey: ['api-keys'],
    queryFn: async () => {
      const response = await api.get('/api/v1/admin/api-keys');
      return response.data;
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      await api.delete(`/api/v1/admin/api-keys/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['api-keys'] });
      toast.success('API key deleted');
    },
    onError: () => {
      toast.error('Failed to delete API key');
    },
  });

  const toggleActiveMutation = useMutation({
    mutationFn: async ({ id, isActive }: { id: number; isActive: boolean }) => {
      await api.put(`/api/v1/admin/api-keys/${id}`, { isActive: !isActive });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['api-keys'] });
      toast.success('API key updated');
    },
  });

  if (isLoading) {
    return <div className="text-center py-12">Loading...</div>;
  }

  return (
    <div className="px-4 py-6 sm:px-0">
      <div className="mb-6 flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">API Keys</h1>
          <p className="mt-2 text-sm text-gray-600">Manage external API keys for data enrichment</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add API Key
        </button>
      </div>

      <div className="bg-white shadow overflow-hidden sm:rounded-md">
        <ul className="divide-y divide-gray-200">
          {data?.apiKeys.map((key) => (
            <li key={key.id} className="px-6 py-4">
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center">
                    <span className="text-sm font-medium text-gray-900">{key.keyName}</span>
                    <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                      {key.provider}
                    </span>
                    {key.isActive ? (
                      <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                        Active
                      </span>
                    ) : (
                      <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                        Inactive
                      </span>
                    )}
                  </div>
                  <div className="mt-2 text-sm text-gray-500">
                    Created: {new Date(key.createdAt).toLocaleDateString()}
                    {key.expiresAt && ` • Expires: ${new Date(key.expiresAt).toLocaleDateString()}`}
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => toggleActiveMutation.mutate({ id: key.id, isActive: key.isActive })}
                    className="text-gray-400 hover:text-gray-600"
                  >
                    {key.isActive ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                  </button>
                  <button
                    onClick={() => deleteMutation.mutate(key.id)}
                    className="text-red-400 hover:text-red-600"
                  >
                    <Trash2 className="h-5 w-5" />
                  </button>
                </div>
              </div>
            </li>
          ))}
        </ul>
        {data?.apiKeys.length === 0 && (
          <div className="text-center py-12 text-gray-500">No API keys configured</div>
        )}
      </div>

      {showAddModal && (
        <AddApiKeyModal
          onClose={() => {
            setShowAddModal(false);
            queryClient.invalidateQueries({ queryKey: ['api-keys'] });
          }}
        />
      )}
    </div>
  );
}

function AddApiKeyModal({ onClose }: { onClose: () => void }) {
  const [formData, setFormData] = useState({
    provider: 'coingecko',
    keyName: '',
    apiKey: '',
    rateLimitPerMinute: '',
    rateLimitPerDay: '',
    expiresAt: '',
  });

  const createMutation = useMutation({
    mutationFn: async (data: any) => {
      await api.post('/api/v1/admin/api-keys', data);
    },
    onSuccess: () => {
      toast.success('API key added');
      onClose();
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.error || 'Failed to add API key');
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createMutation.mutate({
      ...formData,
      rateLimitPerMinute: formData.rateLimitPerMinute ? parseInt(formData.rateLimitPerMinute, 10) : undefined,
      rateLimitPerDay: formData.rateLimitPerDay ? parseInt(formData.rateLimitPerDay, 10) : undefined,
      expiresAt: formData.expiresAt || undefined,
    });
  };

  return (
    <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <h3 className="text-lg font-bold text-gray-900 mb-4">Add API Key</h3>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700">Provider</label>
            <select
              value={formData.provider}
              onChange={(e) => setFormData({ ...formData, provider: e.target.value })}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
            >
              <option value="coingecko">CoinGecko</option>
              <option value="coinmarketcap">CoinMarketCap</option>
              <option value="dexscreener">DexScreener</option>
              <option value="custom">Custom</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Key Name</label>
            <input
              type="text"
              required
              value={formData.keyName}
              onChange={(e) => setFormData({ ...formData, keyName: e.target.value })}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">API Key</label>
            <input
              type="password"
              required
              value={formData.apiKey}
              onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
            />
          </div>
          <div className="flex justify-end space-x-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={createMutation.isPending}
              className="px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-md hover:bg-primary-700 disabled:opacity-50"
            >
              {createMutation.isPending ? 'Adding...' : 'Add'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
