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

interface DexFactory {
  id: number;
  chainId: number;
  dexType: string;
  factoryAddress: string;
  routerAddress?: string;
  poolManagerAddress?: string;
  startBlock: number;
  isActive: boolean;
  description?: string;
}

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

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

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      await api.put(`/api/v1/admin/dex-factories/${id}`, { isActive: false });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['dex-factories'] });
      toast.success('DEX factory 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">DEX Factories</h1>
          <p className="mt-2 text-sm text-gray-600">Manage DEX factory addresses for pool discovery</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 Factory
        </button>
      </div>

      <div className="bg-white shadow overflow-hidden sm:rounded-md">
        <ul className="divide-y divide-gray-200">
          {data?.factories.map((factory) => (
            <li key={factory.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">{factory.dexType}</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 {factory.chainId}
                    </span>
                    {factory.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">
                    Factory: {factory.factoryAddress}
                    {factory.routerAddress && ` • Router: ${factory.routerAddress}`}
                    {factory.poolManagerAddress && ` • Pool Manager: ${factory.poolManagerAddress}`}
                  </div>
                  {factory.description && (
                    <div className="mt-1 text-sm text-gray-400">{factory.description}</div>
                  )}
                </div>
                <button
                  onClick={() => deleteMutation.mutate(factory.id)}
                  className="text-red-400 hover:text-red-600"
                >
                  <Trash2 className="h-5 w-5" />
                </button>
              </div>
            </li>
          ))}
        </ul>
        {data?.factories.length === 0 && (
          <div className="text-center py-12 text-gray-500">No DEX factories configured</div>
        )}
      </div>

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

function AddFactoryModal({ onClose }: { onClose: () => void }) {
  const [formData, setFormData] = useState({
    chainId: '138',
    dexType: 'uniswap_v2',
    factoryAddress: '',
    routerAddress: '',
    poolManagerAddress: '',
    startBlock: '0',
    description: '',
  });

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createMutation.mutate({
      ...formData,
      chainId: parseInt(formData.chainId, 10),
      startBlock: parseInt(formData.startBlock, 10),
      routerAddress: formData.routerAddress || undefined,
      poolManagerAddress: formData.poolManagerAddress || undefined,
      description: formData.description || 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 DEX Factory</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">DEX Type</label>
            <select
              value={formData.dexType}
              onChange={(e) => setFormData({ ...formData, dexType: 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="uniswap_v2">Uniswap V2</option>
              <option value="uniswap_v3">Uniswap V3</option>
              <option value="dodo">DODO</option>
              <option value="custom">Custom</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Factory Address</label>
            <input
              type="text"
              required
              value={formData.factoryAddress}
              onChange={(e) => setFormData({ ...formData, factoryAddress: e.target.value })}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
              placeholder="0x..."
            />
          </div>
          {formData.dexType !== 'dodo' && (
            <div>
              <label className="block text-sm font-medium text-gray-700">Router Address (optional)</label>
              <input
                type="text"
                value={formData.routerAddress}
                onChange={(e) => setFormData({ ...formData, routerAddress: e.target.value })}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
                placeholder="0x..."
              />
            </div>
          )}
          {formData.dexType === 'dodo' && (
            <div>
              <label className="block text-sm font-medium text-gray-700">Pool Manager Address</label>
              <input
                type="text"
                value={formData.poolManagerAddress}
                onChange={(e) => setFormData({ ...formData, poolManagerAddress: e.target.value })}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
                placeholder="0x..."
              />
            </div>
          )}
          <div>
            <label className="block text-sm font-medium text-gray-700">Start Block</label>
            <input
              type="number"
              value={formData.startBlock}
              onChange={(e) => setFormData({ ...formData, startBlock: 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">Description (optional)</label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500"
              rows={2}
            />
          </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>
  );
}
