import { useState, useEffect } from 'react';
import { PageContainer } from '../../components/shared/PageContainer';
import { DataTable } from '../../components/shared/DataTable';
import { MetricCard } from '../../components/shared/MetricCard';
import { Button } from '../../components/shared/Button';
import { Modal } from '../../components/shared/Modal';
import { FormInput } from '../../components/shared/FormInput';
import { FormSelect } from '../../components/shared/FormSelect';
import { dbisAdminApi } from '../../services/api/dbisAdminApi';

interface DecisionMap {
  sizeThresholds: {
    small: { max: number; providers: string[] };
    medium: { max: number; providers: string[] };
    large: { providers: string[] };
  };
  slippageRules: {
    lowSlippage: { max: number; prefer: string };
    mediumSlippage: { max: number; prefer: string };
    highSlippage: { prefer: string };
  };
  liquidityRules: {
    highLiquidity: { min: number; prefer: string };
    mediumLiquidity: { prefer: string };
    lowLiquidity: { prefer: string };
  };
}

interface Quote {
  provider: string;
  amountOut: string;
  priceImpact: number;
  gasEstimate: string;
  effectiveOutput: string;
}

export default function LiquidityEnginePage() {
  const [decisionMap, setDecisionMap] = useState<DecisionMap | null>(null);
  const [quotes, setQuotes] = useState<Quote[]>([]);
  const [showConfigModal, setShowConfigModal] = useState(false);
  const [loading, setLoading] = useState(true);
  const [simulationResult, setSimulationResult] = useState<any>(null);

  useEffect(() => {
    loadDecisionMap();
    loadQuotes();
  }, []);

  const loadDecisionMap = async () => {
    try {
      const data = await dbisAdminApi.getLiquidityDecisionMap();
      setDecisionMap(data);
    } catch (error) {
      console.error('Failed to load decision map:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadQuotes = async () => {
    try {
      const data = await dbisAdminApi.getLiquidityQuotes({
        inputToken: 'WETH',
        outputToken: 'USDT',
        amount: '1000000000000000000', // 1 ETH
      });
      setQuotes(data);
    } catch (error) {
      console.error('Failed to load quotes:', error);
    }
  };

  const handleSaveConfig = async () => {
    try {
      await dbisAdminApi.updateLiquidityDecisionMap(decisionMap!);
      setShowConfigModal(false);
      alert('Configuration saved successfully');
    } catch (error) {
      console.error('Failed to save config:', error);
      alert('Failed to save configuration');
    }
  };

  const handleSimulate = async () => {
    try {
      const result = await dbisAdminApi.simulateRoute({
        inputToken: 'WETH',
        outputToken: 'USDT',
        amount: '1000000000000000000',
      });
      setSimulationResult(result);
    } catch (error) {
      console.error('Failed to simulate:', error);
    }
  };

  if (loading) {
    return <PageContainer>Loading...</PageContainer>;
  }

  return (
    <PageContainer>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">Liquidity Engine</h1>
        <div className="flex gap-2">
          <Button onClick={() => setShowConfigModal(true)}>Configure Routing</Button>
          <Button onClick={handleSimulate}>Simulate Route</Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <MetricCard
          title="Total Swaps"
          value="1,234"
          subtitle="Last 24h"
        />
        <MetricCard
          title="Avg Slippage"
          value="0.15%"
          subtitle="Across all providers"
        />
        <MetricCard
          title="Best Provider"
          value="Dodoex"
          subtitle="Most used"
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">Provider Quotes</h2>
          <DataTable
            data={quotes}
            columns={[
              { key: 'provider', header: 'Provider' },
              { key: 'amountOut', header: 'Output' },
              { key: 'priceImpact', header: 'Price Impact', render: (val) => `${val}%` },
              { key: 'effectiveOutput', header: 'Effective Output' },
            ]}
          />
        </div>

        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">Decision Logic Map</h2>
          {decisionMap && (
            <div className="space-y-4">
              <div>
                <h3 className="font-medium mb-2">Size Thresholds</h3>
                <div className="text-sm space-y-1">
                  <div>Small (&lt; ${decisionMap.sizeThresholds.small.max.toLocaleString()}): {decisionMap.sizeThresholds.small.providers.join(', ')}</div>
                  <div>Medium (&lt; ${decisionMap.sizeThresholds.medium.max.toLocaleString()}): {decisionMap.sizeThresholds.medium.providers.join(', ')}</div>
                  <div>Large: {decisionMap.sizeThresholds.large.providers.join(', ')}</div>
                </div>
              </div>
              <div>
                <h3 className="font-medium mb-2">Slippage Rules</h3>
                <div className="text-sm space-y-1">
                  <div>Low (&lt; {decisionMap.slippageRules.lowSlippage.max}%): Prefer {decisionMap.slippageRules.lowSlippage.prefer}</div>
                  <div>Medium (&lt; {decisionMap.slippageRules.mediumSlippage.max}%): Prefer {decisionMap.slippageRules.mediumSlippage.prefer}</div>
                  <div>High: Prefer {decisionMap.slippageRules.highSlippage.prefer}</div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {simulationResult && (
        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">Simulation Result</h2>
          <div className="space-y-2">
            <div><strong>Provider:</strong> {simulationResult.provider}</div>
            <div><strong>Expected Output:</strong> {simulationResult.expectedOutput}</div>
            <div><strong>Slippage:</strong> {simulationResult.slippage}%</div>
            <div><strong>Confidence:</strong> {simulationResult.confidence}%</div>
            <div><strong>Reasoning:</strong> {simulationResult.reasoning}</div>
          </div>
        </div>
      )}

      {showConfigModal && decisionMap && (
        <Modal
          title="Configure Routing Logic"
          onClose={() => setShowConfigModal(false)}
          size="large"
        >
          <div className="space-y-6">
            <div>
              <h3 className="font-semibold mb-3">Size Thresholds</h3>
              <div className="space-y-3">
                <div>
                  <label className="block text-sm font-medium mb-1">Small Swap Max (USD)</label>
                  <FormInput
                    type="number"
                    value={decisionMap.sizeThresholds.small.max}
                    onChange={(e) => setDecisionMap({
                      ...decisionMap,
                      sizeThresholds: {
                        ...decisionMap.sizeThresholds,
                        small: { ...decisionMap.sizeThresholds.small, max: Number(e.target.value) },
                      },
                    })}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">Medium Swap Max (USD)</label>
                  <FormInput
                    type="number"
                    value={decisionMap.sizeThresholds.medium.max}
                    onChange={(e) => setDecisionMap({
                      ...decisionMap,
                      sizeThresholds: {
                        ...decisionMap.sizeThresholds,
                        medium: { ...decisionMap.sizeThresholds.medium, max: Number(e.target.value) },
                      },
                    })}
                  />
                </div>
              </div>
            </div>

            <div>
              <h3 className="font-semibold mb-3">Slippage Rules</h3>
              <div className="space-y-3">
                <div>
                  <label className="block text-sm font-medium mb-1">Low Slippage Threshold (%)</label>
                  <FormInput
                    type="number"
                    step="0.1"
                    value={decisionMap.slippageRules.lowSlippage.max}
                    onChange={(e) => setDecisionMap({
                      ...decisionMap,
                      slippageRules: {
                        ...decisionMap.slippageRules,
                        lowSlippage: { ...decisionMap.slippageRules.lowSlippage, max: Number(e.target.value) },
                      },
                    })}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">Preferred Provider (Low Slippage)</label>
                  <FormSelect
                    value={decisionMap.slippageRules.lowSlippage.prefer}
                    onChange={(e) => setDecisionMap({
                      ...decisionMap,
                      slippageRules: {
                        ...decisionMap.slippageRules,
                        lowSlippage: { ...decisionMap.slippageRules.lowSlippage, prefer: e.target.value },
                      },
                    })}
                    options={[
                      { value: 'UniswapV3', label: 'Uniswap V3' },
                      { value: 'Dodoex', label: 'Dodoex' },
                      { value: 'Balancer', label: 'Balancer' },
                      { value: 'Curve', label: 'Curve' },
                    ]}
                  />
                </div>
              </div>
            </div>

            <div className="flex justify-end gap-2">
              <Button variant="secondary" onClick={() => setShowConfigModal(false)}>Cancel</Button>
              <Button onClick={handleSaveConfig}>Save Configuration</Button>
            </div>
          </div>
        </Modal>
      )}
    </PageContainer>
  );
}

