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, CheckCircle, XCircle } from 'lucide-react';

interface ApiEndpoint {
  id: number;
  chainId: number;
  endpointType: string;
  endpointName: string;
  endpointUrl: string;
  isPrimary: boolean;
  isActive: boolean;
  healthCheckStatus?: string;
  lastHealthCheck?: string;
}

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

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

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      await api.put(`/api/v1/admin/endpoints/${id}`, { isActive: false });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['endpoints'] });
      toast.success('Endpoint deactivated');
    },
  });

  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 Endpoints</h1>
          <p className="mt-2 text-sm text-gray-600">Manage RPC and API endpoints for chains</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 Endpoint
        </button>
      </div>

      <div className="bg-white shadow overflow-hidden sm:rounded-md">
        <ul className="divide-y divide-gray-200">
          {data?.endpoints.map((endpoint) => (
            <li key={endpoint.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">{endpoint.endpointName}</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">
                      Chain {endpoint.chainId}
                    </span>
                    <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {endpoint.endpointType}
                    </span>
                    {endpoint.isPrimary && (
                      <span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                        Primary
                      </span>
                    )}
                    {endpoint.healthCheckStatus && (
                      <span className="ml-2">
                        {endpoint.healthCheckStatus === 'healthy' ? (
                          <CheckCircle className="h-5 w-5 text-green-500" />
                        ) : (
                          <XCircle className="h-5 w-5 text-red-500" />
                        )}
                      </span>
                    )}
                  </div>
                  <div className="mt-2 text-sm text-gray-500">{endpoint.endpointUrl}</div>
                </div>
                <button
                  onClick={() => deleteMutation.mutate(endpoint.id)}
                  className="text-red-400 hover:text-red-600"
                >
                  <Trash2 className="h-5 w-5" />
                </button>
              </div>
            </li>
          ))}
        </ul>
        {data?.endpoints.length === 0 && (
          <div className="text-center py-12 text-gray-500">No endpoints configured</div>
        )}
      </div>

      {showAddModal && (
        <AddEndpointModal
          onClose={() => {
            setShowAddModal(false);
            queryClient.invalidateQueries({ queryKey: ['endpoints'] });
          }}
        />
      )}
    </div>
  );
}

function AddEndpointModal({ onClose }: { onClose: () => void }) {
  const [formData, setFormData] = useState({
    chainId: '138',
    endpointType: 'rpc',
    endpointName: '',
    endpointUrl: '',
    isPrimary: false,
  });

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createMutation.mutate({
      ...formData,
      chainId: parseInt(formData.chainId, 10),
    });
  };

  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 Endpoint</h3>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700">Chain ID</label>
            <select
              value={formData.chainId}
              onChange={(e) => setFormData({ ...formData, chainId: 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="138">138 (DeFi Oracle Meta Mainnet)</option>
              <option value="651940">651940 (ALL Mainnet)</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Endpoint Type</label>
            <select
              value={formData.endpointType}
              onChange={(e) => setFormData({ ...formData, endpointType: 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="rpc">RPC</option>
              <option value="explorer">Explorer</option>
              <option value="indexer">Indexer</option>
              <option value="custom">Custom</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Endpoint Name</label>
            <input
              type="text"
              required
              value={formData.endpointName}
              onChange={(e) => setFormData({ ...formData, endpointName: 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">Endpoint URL</label>
            <input
              type="url"
              required
              value={formData.endpointUrl}
              onChange={(e) => setFormData({ ...formData, endpointUrl: 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 items-center">
            <input
              type="checkbox"
              id="isPrimary"
              checked={formData.isPrimary}
              onChange={(e) => setFormData({ ...formData, isPrimary: e.target.checked })}
              className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
            />
            <label htmlFor="isPrimary" className="ml-2 block text-sm text-gray-900">
              Set as primary endpoint
            </label>
          </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>
  );
}
