import { useState, useEffect } from 'react';
import { DataTable } from '@/components/ui/data-table';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Star, TrendingUp, TrendingDown, Calendar, Clock } from 'lucide-react';
import { getApiUrl } from '@/config/api';

export default function ScannerPanel() {
  const [scanResults, setScanResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [watchlist, setWatchlist] = useState([]);
  const [useHistorical, setUseHistorical] = useState(false);
  const [historicalDate, setHistoricalDate] = useState(new Date().toISOString().split('T')[0]);
  const [historicalTime, setHistoricalTime] = useState('16:00:00');

  useEffect(() => {
    // Load watchlist from localStorage
    const saved = localStorage.getItem('watchlist');
    if (saved) {
      try {
        setWatchlist(JSON.parse(saved));
      } catch (e) {
        console.error('Error loading watchlist:', e);
      }
    }

    if (!useHistorical) {
      runScan();
      const interval = setInterval(runScan, 60000); // Scan every minute
      return () => clearInterval(interval);
    }
  }, [useHistorical]);

  const runScan = async () => {
    setLoading(true);
    try {
      let url = getApiUrl('/api/scanner/multi-signal');
      if (useHistorical && historicalDate) {
        const params = new URLSearchParams({ date: historicalDate });
        if (historicalTime) {
          params.append('time', historicalTime);
        }
        url += `?${params.toString()}`;
      }
      
      const response = await fetch(url);
      const data = await response.json();
      if (data.success) {
        setScanResults(data.data || []);
      }
    } catch (error) {
      console.error('Scanner error:', error);
    } finally {
      setLoading(false);
    }
  };

  const addToWatchlist = (symbol) => {
    if (!watchlist.includes(symbol)) {
      const updated = [...watchlist, symbol];
      setWatchlist(updated);
      localStorage.setItem('watchlist', JSON.stringify(updated));
      // Dispatch custom event for same-tab updates
      window.dispatchEvent(new Event('watchlistUpdated'));
    }
  };

  const columns = [
    {
      accessorKey: 'ticker',
      header: 'Symbol',
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          <button
            onClick={() => addToWatchlist(row.original.ticker)}
            className="text-yellow-400 hover:text-yellow-300 transition-colors"
            title="Add to watchlist"
          >
            <Star className="w-4 h-4" />
          </button>
          <span className="font-semibold text-slate-100">
            {row.original.ticker}
          </span>
        </div>
      ),
    },
    {
      accessorKey: 'score',
      header: 'Score',
      cell: ({ row }) => (
        <Badge
          variant={row.original.score >= 6 ? 'destructive' : 'secondary'}
          className="font-mono"
        >
          {row.original.score}
        </Badge>
      ),
    },
    {
      accessorKey: 'reasons',
      header: 'Signals',
      cell: ({ row }) => (
        <div className="flex flex-wrap gap-1 max-w-md">
          {row.original.reasons?.split(' | ').map((reason, idx) => (
            <Badge key={idx} variant="outline" className="text-xs">
              {reason}
            </Badge>
          ))}
        </div>
      ),
    },
    {
      accessorKey: 'notional_20m',
      header: 'Notional (20m)',
      cell: ({ row }) => (
        <span className="font-mono text-sm text-blue-400">
          {row.original.notional_20m}
        </span>
      ),
    },
    {
      accessorKey: 'rvol_peak',
      header: 'rVol Peak',
      cell: ({ row }) => {
        const rvol = parseFloat(row.original.rvol_peak) || 0;
        return (
          <span className={rvol > 200 ? 'text-red-400 font-semibold' : 'text-slate-300'}>
            {rvol}%
          </span>
        );
      },
    },
    {
      accessorKey: 'last_seen_ct',
      header: 'Last Seen',
      cell: ({ row }) => (
        <span className="text-xs text-slate-400">
          {row.original.last_seen_ct || 'N/A'}
        </span>
      ),
    },
    {
      id: 'action',
      header: 'Quick View',
      cell: ({ row }) => (
        <Button
          size="sm"
          variant="outline"
          onClick={() => window.open(`/chart/${row.original.ticker}`, '_blank')}
        >
          Chart
        </Button>
      ),
    },
  ];

  return (
    <div className="space-y-4">
      {/* Scanner Header */}
      <div className="p-4 bg-slate-900 rounded-lg border border-slate-800 space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-slate-100">
              Multi-Signal Scanner
            </h3>
            <p className="text-sm text-slate-400 mt-1">
              {useHistorical ? 'Historical data view' : 'Real-time institutional footprint detection'}
            </p>
          </div>
          <Button onClick={runScan} disabled={loading} variant="outline">
            {loading ? 'Scanning...' : '🔄 Refresh'}
          </Button>
        </div>
        
        {/* Historical Data Toggle */}
        <div className="flex items-center gap-4 pt-2 border-t border-slate-800">
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={useHistorical}
              onChange={(e) => {
                setUseHistorical(e.target.checked);
                if (e.target.checked) {
                  // Stop auto-refresh when using historical
                }
              }}
              className="w-4 h-4"
            />
            <span className="text-sm text-slate-300">View Historical Data</span>
          </label>
          
          {useHistorical && (
            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4 text-slate-400" />
              <Input
                type="date"
                value={historicalDate}
                onChange={(e) => setHistoricalDate(e.target.value)}
                className="w-40"
                max={new Date().toISOString().split('T')[0]}
              />
              <Clock className="w-4 h-4 text-slate-400 ml-2" />
              <Input
                type="time"
                value={historicalTime}
                onChange={(e) => setHistoricalTime(e.target.value)}
                className="w-32"
                step="1"
              />
            </div>
          )}
        </div>
      </div>

      {/* Results Table */}
      {scanResults.length > 0 ? (
        <DataTable
          columns={columns}
          data={scanResults}
          className="bg-slate-900 border border-slate-800 rounded-lg"
        />
      ) : (
        <div className="p-12 text-center text-slate-400 bg-slate-900 rounded-lg border border-slate-800">
          {loading ? 'Scanning for signals...' : 'No signals found. Waiting for activity...'}
        </div>
      )}
    </div>
  );
}
