import { useEffect, useState } from 'react';
import { DataTable } from '@/components/ui/data-table';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/button';
import { getApiUrl } from '@/config/api';

export default function PhaseClassifierPanel() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [phases, setPhases] = useState({});
  const [lastUpdate, setLastUpdate] = useState(null);
  const [autoRefresh, setAutoRefresh] = useState(true);

  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await fetch(getApiUrl('/api/options/phase-classifier'));
      const result = await response.json();
      
      if (result.success) {
        setData(result.data || []);
        setPhases(result.phases || {});
        setLastUpdate(new Date());
        setError(null);
      } else {
        setError(result.error || 'Failed to fetch phase classifier data');
      }
    } catch (err) {
      setError(err.message);
      console.error('Phase classifier error:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    
    if (autoRefresh) {
      const interval = setInterval(fetchData, 30000); // Refresh every 30 seconds
      return () => clearInterval(interval);
    }
  }, [autoRefresh]);

  const getPhaseColor = (phase) => {
    switch (phase) {
      case 'SQUEEZE':
        return 'bg-red-500/20 text-red-400 border-red-500/50';
      case 'UNWINDING':
        return 'bg-green-500/20 text-green-400 border-green-500/50';
      case 'HEDGED SHORTING':
        return 'bg-orange-500/20 text-orange-400 border-orange-500/50';
      case 'ACCUMULATION':
        return 'bg-blue-500/20 text-blue-400 border-blue-500/50';
      default:
        return 'bg-slate-500/20 text-slate-400 border-slate-500/50';
    }
  };

  const getPhaseIcon = (phase) => {
    switch (phase) {
      case 'SQUEEZE':
        return '🔥';
      case 'UNWINDING':
        return '📈';
      case 'HEDGED SHORTING':
        return '⚠️';
      case 'ACCUMULATION':
        return '💎';
      default:
        return '⚪';
    }
  };

  const columns = [
    {
      accessorKey: 'symbol',
      header: 'Symbol',
      cell: ({ row }) => (
        <div className="font-mono text-sm font-semibold text-slate-100">
          {row.original.symbol}
        </div>
      )
    },
    {
      accessorKey: 'phase',
      header: 'Phase',
      cell: ({ row }) => {
        const phase = row.original.phase;
        return (
          <Badge className={`${getPhaseColor(phase)} border font-semibold`}>
            {getPhaseIcon(phase)} {phase}
          </Badge>
        );
      }
    },
    {
      accessorKey: 'call_prem_formatted',
      header: 'Call Premium',
      cell: ({ row }) => (
        <div className="text-sm text-green-400 font-mono">
          {row.original.call_prem_formatted || '0'}
        </div>
      )
    },
    {
      accessorKey: 'put_prem_formatted',
      header: 'Put Premium',
      cell: ({ row }) => (
        <div className="text-sm text-red-400 font-mono">
          {row.original.put_prem_formatted || '0'}
        </div>
      )
    },
    {
      accessorKey: 'total_prem_formatted',
      header: 'Total Premium',
      cell: ({ row }) => (
        <div className="text-sm text-slate-300 font-mono font-semibold">
          {row.original.total_prem_formatted || '0'}
        </div>
      )
    },
    {
      accessorKey: 'ret_lb_pct',
      header: 'Return %',
      cell: ({ row }) => {
        const pct = row.original.ret_lb_pct || 0;
        const color = pct >= 0 ? 'text-green-400' : 'text-red-400';
        return (
          <div className={`text-sm font-mono font-semibold ${color}`}>
            {pct >= 0 ? '+' : ''}{pct.toFixed(2)}%
          </div>
        );
      }
    },
    {
      accessorKey: 'short_vol_pct',
      header: 'Short Vol %',
      cell: ({ row }) => (
        <div className="text-sm text-slate-400 font-mono">
          {row.original.short_vol_pct ? `${row.original.short_vol_pct.toFixed(1)}%` : 'N/A'}
        </div>
      )
    },
    {
      accessorKey: 'above_vwap',
      header: 'Above VWAP',
      cell: ({ row }) => (
        <div className="text-sm">
          {row.original.above_vwap ? (
            <Badge variant="success" className="bg-green-500/20 text-green-400">
              ✓
            </Badge>
          ) : (
            <Badge variant="secondary" className="bg-red-500/20 text-red-400">
              ✗
            </Badge>
          )}
        </div>
      )
    },
    {
      accessorKey: 'broke_or_high',
      header: 'Broke OR High',
      cell: ({ row }) => (
        <div className="text-sm">
          {row.original.broke_or_high ? (
            <Badge variant="success" className="bg-green-500/20 text-green-400">
              ✓
            </Badge>
          ) : (
            <Badge variant="secondary" className="bg-slate-500/20 text-slate-400">
              ✗
            </Badge>
          )}
        </div>
      )
    },
    {
      accessorKey: 'phase_interpretation',
      header: 'Interpretation',
      cell: ({ row }) => (
        <div className="text-xs text-slate-400 max-w-md">
          {row.original.phase_interpretation}
        </div>
      )
    },
    {
      accessorKey: 'trade_implication',
      header: 'Trade Action',
      cell: ({ row }) => {
        const impl = row.original.trade_implication;
        if (!impl || impl.action === 'WAIT') return <span className="text-slate-500">-</span>;
        
        const actionColor = {
          'BUY': 'text-green-400',
          'SHORT': 'text-red-400',
          'SHORT or AVOID': 'text-orange-400',
          'BUY (SWING)': 'text-blue-400'
        };
        
        return (
          <div className="text-xs">
            <div className={`font-semibold ${actionColor[impl.action] || 'text-slate-400'}`}>
              {impl.action}
            </div>
            <div className="text-slate-500 mt-1">
              Entry: {impl.entry}
            </div>
          </div>
        );
      }
    }
  ];

  // Group data by phase for summary
  const groupedByPhase = data.reduce((acc, row) => {
    const phase = row.phase || 'NEUTRAL';
    if (!acc[phase]) acc[phase] = [];
    acc[phase].push(row);
    return acc;
  }, {});

  if (loading && data.length === 0) {
    return (
      <div className="bg-slate-900/50 border border-slate-800 rounded-lg p-8">
        <div className="text-center text-slate-400">Loading phase classifier data...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-slate-900/50 border border-slate-800 rounded-lg p-8">
        <div className="text-center text-red-400">Error: {error}</div>
        <Button onClick={fetchData} className="mt-4">Retry</Button>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Summary Cards */}
      <div className="grid grid-cols-5 gap-4">
        <div className="bg-slate-900/50 border border-red-500/50 rounded-lg p-4">
          <div className="text-xs text-slate-400 mb-1">SQUEEZE</div>
          <div className="text-2xl font-bold text-red-400">{phases.SQUEEZE || 0}</div>
        </div>
        <div className="bg-slate-900/50 border border-green-500/50 rounded-lg p-4">
          <div className="text-xs text-slate-400 mb-1">UNWINDING</div>
          <div className="text-2xl font-bold text-green-400">{phases.UNWINDING || 0}</div>
        </div>
        <div className="bg-slate-900/50 border border-orange-500/50 rounded-lg p-4">
          <div className="text-xs text-slate-400 mb-1">HEDGED SHORTING</div>
          <div className="text-2xl font-bold text-orange-400">{phases.HEDGED_SHORTING || 0}</div>
        </div>
        <div className="bg-slate-900/50 border border-blue-500/50 rounded-lg p-4">
          <div className="text-xs text-slate-400 mb-1">ACCUMULATION</div>
          <div className="text-2xl font-bold text-blue-400">{phases.ACCUMULATION || 0}</div>
        </div>
        <div className="bg-slate-900/50 border border-slate-500/50 rounded-lg p-4">
          <div className="text-xs text-slate-400 mb-1">NEUTRAL</div>
          <div className="text-2xl font-bold text-slate-400">{phases.NEUTRAL || 0}</div>
        </div>
      </div>

      {/* Controls */}
      <div className="flex items-center justify-between bg-slate-900/50 border border-slate-800 rounded-lg p-4">
        <div className="flex items-center gap-4">
          <Button
            onClick={fetchData}
            variant="outline"
            size="sm"
            disabled={loading}
          >
            {loading ? 'Refreshing...' : 'Refresh'}
          </Button>
          <label className="flex items-center gap-2 text-sm text-slate-400">
            <input
              type="checkbox"
              checked={autoRefresh}
              onChange={(e) => setAutoRefresh(e.target.checked)}
              className="rounded"
            />
            Auto-refresh (30s)
          </label>
          {lastUpdate && (
            <div className="text-xs text-slate-500">
              Last update: {lastUpdate.toLocaleTimeString()}
            </div>
          )}
        </div>
        <div className="text-sm text-slate-400">
          Total: {data.length} symbols
        </div>
      </div>

      {/* Data Table */}
      <div className="bg-slate-900/50 border border-slate-800 rounded-lg">
        <DataTable
          data={data}
          columns={columns}
          defaultSort={{ id: 'phase_priority', desc: false }}
        />
      </div>

      {/* Phase Legend */}
      <div className="bg-slate-900/50 border border-slate-800 rounded-lg p-4">
        <div className="text-sm font-semibold text-slate-300 mb-3">Phase Interpretations</div>
        <div className="grid grid-cols-2 gap-4 text-xs text-slate-400">
          <div>
            <div className="font-semibold text-red-400 mb-1">🔥 SQUEEZE</div>
            <div>Gamma squeeze setup. Market makers short gamma, forced to buy as price rises. Opening range break = institutional momentum ignition.</div>
          </div>
          <div>
            <div className="font-semibold text-green-400 mb-1">📈 UNWINDING</div>
            <div>Short unwind in progress. Low short volume means sellers are NOT selling into the rally. Call dominance + lack of resistance = sustained bid.</div>
          </div>
          <div>
            <div className="font-semibold text-orange-400 mb-1">⚠️ HEDGED SHORTING</div>
            <div>Bearish trap disguised as bullish flow. Calls are being bought as downside protection. High short volume = aggressive selling into dark pools.</div>
          </div>
          <div>
            <div className="font-semibold text-blue-400 mb-1">💎 ACCUMULATION</div>
            <div>Quiet institutional accumulation. Heavy call buying without price movement = large players building positions without chasing.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

