// ===== Spread Trends Tab =====
// Shows historical spread data and statistics
// Helps traders identify best entry times and strike liquidity patterns

function SpreadTrendsTab({ symbol = 'NIFTY' }) {
  const toast = useToast();
  const [activeStrike, setActiveStrike] = React.useState(null);
  const [activeOptionType, setActiveOptionType] = React.useState('CE');
  const [spreadData, setSpreadData] = React.useState([]);
  const [spreadStats, setSpreadStats] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [timeWindow, setTimeWindow] = React.useState(24);

  // Fetch and display initial ATM data
  React.useEffect(() => {
    loadSpreadData();
    const interval = setInterval(loadSpreadData, 10000); // Refresh every 10 seconds
    return () => clearInterval(interval);
  }, [symbol]);

  // Fetch spread history and stats when strike changes
  React.useEffect(() => {
    if (activeStrike) {
      loadSpreadStats();
      loadSpreadHistory();
    }
  }, [activeStrike, activeOptionType, timeWindow]);

  const loadSpreadData = async () => {
    setLoading(true);
    try {
      const response = await API.get(`/api/atm-strikes/${symbol}`);
      if (response.success && response.symbols?.length > 0) {
        const symbolData = response.symbols[0];
        if (symbolData.strikes?.length > 0 && !activeStrike) {
          // Default to ATM strike
          const atmStrike = symbolData.strikes.find(s => s.isAtm);
          if (atmStrike) {
            setActiveStrike(atmStrike.strike);
          }
        }
      }
    } catch (error) {
      toast('Failed to load spread data', 'error');
    } finally {
      setLoading(false);
    }
  };

  const loadSpreadStats = async () => {
    if (!activeStrike) return;

    try {
      const response = await API.get(
        `/api/atm-strikes/${symbol}/spread-stats/${activeStrike}/${activeOptionType}?hoursBack=${timeWindow}`
      );
      setSpreadStats(response);
    } catch (error) {
      toast('Failed to load spread statistics', 'error');
    }
  };

  const loadSpreadHistory = async () => {
    if (!activeStrike) return;

    try {
      const response = await API.get(
        `/api/atm-strikes/${symbol}/spread-history?strike=${activeStrike}&optionType=${activeOptionType}`
      );
      if (response.history) {
        setSpreadData(response.history.slice(-50)); // Last 50 data points
      }
    } catch (error) {
      toast('Failed to load spread history', 'error');
    }
  };

  const getLiquidityColor = (liquidityStatus) => {
    switch (liquidityStatus) {
      case 'VeryLiquid':
        return 'bg-green-100 text-green-800';
      case 'Acceptable':
        return 'bg-blue-100 text-blue-800';
      case 'Thin':
        return 'bg-yellow-100 text-yellow-800';
      case 'Dangerous':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  return (
    <div className="p-4 space-y-4">
      {/* Header and Controls */}
      <div className="bg-white rounded-lg shadow p-4">
        <h2 className="text-xl font-bold mb-4">📈 Spread Trends - {symbol}</h2>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
          <div>
            <label className="block text-sm font-medium mb-1">Strike</label>
            <input
              type="number"
              value={activeStrike || ''}
              onChange={(e) => setActiveStrike(parseInt(e.target.value) || null)}
              className="w-full px-2 py-1 border rounded"
              placeholder="Enter strike"
            />
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Option Type</label>
            <select
              value={activeOptionType}
              onChange={(e) => setActiveOptionType(e.target.value)}
              className="w-full px-2 py-1 border rounded"
            >
              <option value="CE">Call (CE)</option>
              <option value="PE">Put (PE)</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Time Window</label>
            <select
              value={timeWindow}
              onChange={(e) => setTimeWindow(parseInt(e.target.value))}
              className="w-full px-2 py-1 border rounded"
            >
              <option value={1}>Last Hour</option>
              <option value={4}>4 Hours</option>
              <option value={24}>24 Hours</option>
              <option value={72}>3 Days</option>
              <option value={168}>1 Week</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">&nbsp;</label>
            <button
              onClick={loadSpreadStats}
              disabled={loading}
              className="w-full px-4 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
            >
              {loading ? 'Loading...' : 'Refresh'}
            </button>
          </div>
        </div>
      </div>

      {/* Statistics Cards */}
      {spreadStats && (
        <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
          <SpreadStatCard
            label="Min Spread"
            value={`₹${spreadStats.minSpread?.toFixed(2) || 'N/A'}`}
            color="bg-green-50 border-green-200"
          />
          <SpreadStatCard
            label="Max Spread"
            value={`₹${spreadStats.maxSpread?.toFixed(2) || 'N/A'}`}
            color="bg-red-50 border-red-200"
          />
          <SpreadStatCard
            label="Avg Spread"
            value={`₹${spreadStats.avgSpread?.toFixed(2) || 'N/A'}`}
            color="bg-blue-50 border-blue-200"
          />
          <SpreadStatCard
            label="Median"
            value={`₹${spreadStats.medianSpread?.toFixed(2) || 'N/A'}`}
            color="bg-purple-50 border-purple-200"
          />
          <SpreadStatCard
            label="Data Points"
            value={spreadStats.dataPoints || 0}
            color="bg-gray-50 border-gray-200"
          />
        </div>
      )}

      {/* Spread Chart (Simple line graph) */}
      <div className="bg-white rounded-lg shadow p-4">
        <h3 className="text-lg font-semibold mb-4">Spread History</h3>
        {spreadData.length > 0 ? (
          <div className="relative h-64 bg-gray-50 rounded p-4">
            <SpreadChart data={spreadData} />
          </div>
        ) : (
          <p className="text-gray-500 text-center py-8">No spread history data available</p>
        )}
      </div>

      {/* Liquidity Status Indicator */}
      <div className="bg-white rounded-lg shadow p-4">
        <h3 className="text-lg font-semibold mb-4">Liquidity Guide</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <LiquidityCard
            status="VeryLiquid"
            spread="< ₹0.05"
            color="bg-green-100 text-green-800"
            description="Best for large orders"
          />
          <LiquidityCard
            status="Acceptable"
            spread="₹0.05-₹0.50"
            color="bg-blue-100 text-blue-800"
            description="Good for intraday"
          />
          <LiquidityCard
            status="Thin"
            spread="₹0.50-₹2.00"
            color="bg-yellow-100 text-yellow-800"
            description="Watch slippage"
          />
          <LiquidityCard
            status="Dangerous"
            spread=">= ₹2.00"
            color="bg-red-100 text-red-800"
            description="Avoid trading"
          />
        </div>
      </div>

      {/* Tips */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-900">
        <strong>💡 Pro Tips:</strong>
        <ul className="list-disc ml-6 mt-2">
          <li>Enter trades when spread is at "Min Spread" levels for better execution</li>
          <li>Avoid entries when spread is trending towards "Max Spread"</li>
          <li>ATM strikes typically have better liquidity than OTM strikes</li>
          <li>Watch median spread as your trading reference point</li>
        </ul>
      </div>
    </div>
  );
}

/**
 * Simple Stat Card Component
 */
function SpreadStatCard({ label, value, color }) {
  return (
    <div className={`${color} border rounded p-3 text-center`}>
      <p className="text-xs text-gray-600">{label}</p>
      <p className="text-lg font-bold">{value}</p>
    </div>
  );
}

/**
 * Liquidity Status Card
 */
function LiquidityCard({ status, spread, color, description }) {
  return (
    <div className={`${color} rounded p-3 text-center`}>
      <p className="font-semibold text-sm">{status}</p>
      <p className="text-xs mt-1">{spread}</p>
      <p className="text-xs mt-1 opacity-75">{description}</p>
    </div>
  );
}

/**
 * Simple Spread Chart Component (ASCII-style mini chart)
 * For a production app, use a charting library like recharts or chart.js
 */
function SpreadChart({ data }) {
  if (!data || data.length === 0) return null;

  const spreads = data.map(d => d.bidAskSpread || 0).filter(s => s > 0);
  if (spreads.length === 0) return <p className="text-gray-500">No spread data</p>;

  const maxSpread = Math.max(...spreads);
  const minSpread = Math.min(...spreads);
  const range = maxSpread - minSpread || 1;

  return (
    <div className="space-y-2">
      {/* Simple line plot using SVG */}
      <svg width="100%" height="100%" viewBox="0 0 500 200" className="border border-gray-200 rounded">
        {/* Grid lines */}
        <line x1="40" y1="170" x2="500" y2="170" stroke="#e0e0e0" />
        <line x1="40" y1="85" x2="500" y2="85" stroke="#e0e0e0" />

        {/* Y-axis */}
        <line x1="40" y1="20" x2="40" y2="170" stroke="#333" strokeWidth="2" />
        {/* X-axis */}
        <line x1="40" y1="170" x2="500" y2="170" stroke="#333" strokeWidth="2" />

        {/* Plot line */}
        <polyline
          fill="none"
          stroke="#3b82f6"
          strokeWidth="2"
          points={spreads
            .map((s, i) => {
              const x = 40 + (i / (spreads.length - 1)) * 460;
              const y = 170 - ((s - minSpread) / range) * 150;
              return `${x},${y}`;
            })
            .join(' ')}
        />

        {/* Y-axis labels */}
        <text x="10" y="25" fontSize="10" fill="#666">{maxSpread.toFixed(2)}</text>
        <text x="10" y="175" fontSize="10" fill="#666">{minSpread.toFixed(2)}</text>
      </svg>
      <p className="text-xs text-gray-600 text-center">Time →</p>
    </div>
  );
}


