import { useState, useEffect, useCallback } from 'react';
import { SlidersHorizontal, Search, RefreshCw } from 'lucide-react';
import { useAppContext } from '../context/AppContext';
import { useNavigate } from 'react-router-dom';
import { getPlatformAccessToken } from '../lib/authSession';
import { tradingRuntime } from '../lib/runtime';
import { createRequestId } from '../../../shared/request-id.js';
import { SkeletonBlock } from '../components/Skeleton';
import { PageHeader } from '../components/ui/page-header';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Select } from '../components/ui/select';
import { Card, CardContent } from '../components/ui/card';

// ─── Types ────────────────────────────────────────────────────────────────────
interface ScreenerRow {
  symbol:        string;
  companyName:   string;
  price:         number;
  changesPercentage: number;
  marketCap:     number;
  pe:            number | null;
  sector:        string;
  volume:        number;
}

const SECTORS = [
  'All', 'Technology', 'Financial Services', 'Healthcare', 'Consumer Cyclical',
  'Consumer Defensive', 'Industrials', 'Energy', 'Utilities', 'Real Estate',
  'Communication Services', 'Basic Materials',
];

const CAP_OPTIONS: { label: string; min: number; max?: number }[] = [
  { label: 'Any Cap', min: 0 },
  { label: 'Mega (>$200B)', min: 200_000_000_000 },
  { label: 'Large ($10B–$200B)', min: 10_000_000_000, max: 200_000_000_000 },
  { label: 'Mid ($2B–$10B)', min: 2_000_000_000, max: 10_000_000_000 },
  { label: 'Small (<$2B)', min: 0, max: 2_000_000_000 },
];

const fmtCap = (n: number) => {
  if (n >= 1e12) return `$${(n / 1e12).toFixed(1)}T`;
  if (n >= 1e9)  return `$${(n / 1e9).toFixed(1)}B`;
  if (n >= 1e6)  return `$${(n / 1e6).toFixed(1)}M`;
  return `$${n.toLocaleString()}`;
};

// ─── Screener fetch ───────────────────────────────────────────────────────────
async function runScreener(params: {
  sector: string;
  marketCapMore?: number;
  marketCapLess?: number;
  limit: number;
}): Promise<ScreenerRow[]> {
  const token = await getPlatformAccessToken();
  const qs = new URLSearchParams({ limit: String(params.limit) });
  if (params.sector && params.sector !== 'All') qs.set('sector', params.sector);
  if (params.marketCapMore) qs.set('marketCapMoreThan', String(params.marketCapMore));
  if (params.marketCapLess) qs.set('marketCapLessThan', String(params.marketCapLess));

  const res = await fetch(`${tradingRuntime.tradingApiUrl}/api/screener?${qs}`, {
    headers: {
      Authorization:  `Bearer ${token}`,
      'x-request-id': createRequestId('web-screener'),
    },
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({})) as any;
    throw new Error(body?.error ?? `Screener failed (${res.status})`);
  }
  const data = await res.json() as any;
  return Array.isArray(data) ? data : (data.results ?? []);
}

// ─── ScreenerView ─────────────────────────────────────────────────────────────
export function ScreenerView() {
  const { setActiveSymbol } = useAppContext();
  const navigate = useNavigate();

  const [results,  setResults]  = useState<ScreenerRow[]>([]);
  const [loading,  setLoading]  = useState(false);
  const [error,    setError]    = useState<string | null>(null);
  const [query,    setQuery]    = useState('');
  const [sector,   setSector]   = useState('All');
  const [capIdx,   setCapIdx]   = useState(0);
  const [sortKey,  setSortKey]  = useState<keyof ScreenerRow>('marketCap');
  const [sortAsc,  setSortAsc]  = useState(false);

  const fetchResults = useCallback(async () => {
    setLoading(true);
    setError(null);
    const cap = CAP_OPTIONS[capIdx];
    try {
      const rows = await runScreener({
        sector,
        marketCapMore: cap.min > 0 ? cap.min : undefined,
        marketCapLess: cap.max,
        limit: 50,
      });
      setResults(rows);
    } catch (e: any) {
      setError(e?.message ?? 'Screener request failed');
    } finally {
      setLoading(false);
    }
  }, [sector, capIdx]);

  // Fetch on mount and when filters change
  useEffect(() => { fetchResults(); }, [fetchResults]);

  // Client-side search filter + sort
  const filtered = results
    .filter(r => {
      if (!query) return true;
      const q = query.toUpperCase();
      return r.symbol?.includes(q) || r.companyName?.toLowerCase().includes(query.toLowerCase());
    })
    .sort((a, b) => {
      const av = a[sortKey] as any ?? 0;
      const bv = b[sortKey] as any ?? 0;
      return sortAsc ? (av > bv ? 1 : -1) : (av < bv ? 1 : -1);
    });

  const handleSort = (key: keyof ScreenerRow) => {
    if (sortKey === key) setSortAsc(p => !p);
    else { setSortKey(key); setSortAsc(false); }
  };

  const SortIcon = ({ k }: { k: keyof ScreenerRow }) => (
    <span style={{ color: sortKey === k ? 'var(--primary)' : 'var(--muted-foreground)', marginLeft: 3, fontSize: 10 }}>
      {sortKey === k ? (sortAsc ? '▲' : '▼') : '⇅'}
    </span>
  );
  const moreSectorSelected = SECTORS.indexOf(sector) >= 6;

  const ScreenerSkeletonRows = () => (
    <div role="status" aria-label="Loading screener results">
      {Array.from({ length: 6 }).map((_, i) => (
        <div
          key={i}
          style={{
            display: 'grid',
            gridTemplateColumns: '100px 1fr 90px 90px 110px 80px 110px',
            padding: '12px 16px',
            borderBottom: i < 5 ? '1px solid var(--border)' : 'none',
            alignItems: 'center',
            columnGap: 0,
          }}
        >
          <SkeletonBlock width={54} height={13} />
          <SkeletonBlock width={`${72 - (i % 3) * 8}%`} height={12} />
          <SkeletonBlock width={58} height={12} />
          <SkeletonBlock width={50} height={12} />
          <SkeletonBlock width={74} height={12} />
          <SkeletonBlock width={38} height={12} />
          <SkeletonBlock width={68} height={12} />
        </div>
      ))}
    </div>
  );

  const handleRowClick = (symbol: string) => {
    setActiveSymbol(symbol);
    navigate('/');
  };

  return (
    <div>
      <PageHeader
        title="Stock Screener"
        description="Filter liquid names by sector and market cap, then jump directly into charting and research."
        action={
          <Button onClick={fetchResults} disabled={loading} variant="outline" size="sm">
            <RefreshCw size={13} style={{ animation: loading ? 'spin 1s linear infinite' : 'none' }} />
            Refresh
          </Button>
        }
      />

      <Card style={{ marginBottom: 16 }}>
        <CardContent style={{ padding: 16 }}>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
            <div style={{ position: 'relative', minWidth: 200, maxWidth: 280 }}>
              <Search size={14} style={{
                position: 'absolute', left: 10, top: '50%',
                transform: 'translateY(-50%)', color: 'var(--muted-foreground)',
              }} />
              <Input
                type="text"
                placeholder="Filter by name or ticker…"
                value={query}
                onChange={e => setQuery(e.target.value)}
                style={{ paddingLeft: 32 }}
              />
            </div>

            <Select
              value={String(capIdx)}
              onChange={e => setCapIdx(Number(e.target.value))}
              style={{ width: 180 }}
            >
              {CAP_OPTIONS.map((c, i) => (
                <option key={c.label} value={i}>{c.label}</option>
              ))}
            </Select>

            <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', alignItems: 'center' }}>
              <SlidersHorizontal size={13} color="var(--muted-foreground)" />
          {SECTORS.slice(0, 6).map(s => (
            <button
              key={s}
              onClick={() => setSector(s)}
              style={{
                padding: '5px 10px', borderRadius: 20,
                border: '1px solid', fontSize: 11, fontWeight: 600,
                cursor: 'pointer',
                borderColor: sector === s ? 'var(--primary)' : 'var(--border)',
                background: sector === s ? 'var(--accent-soft)' : 'var(--card)',
                color: sector === s ? 'var(--primary)' : 'var(--muted-foreground)',
                fontFamily: 'inherit',
              }}
            >
              {s}
            </button>
          ))}
              <Select
                aria-label="More sectors"
                value={SECTORS.indexOf(sector) >= 6 ? sector : ''}
                onChange={e => e.target.value && setSector(e.target.value)}
                style={{
                  width: 140,
                  borderRadius: 999,
                  borderColor: moreSectorSelected ? 'var(--primary)' : 'var(--border)',
                  background: moreSectorSelected ? 'var(--accent-soft)' : 'var(--card)',
                  color: moreSectorSelected ? 'var(--primary)' : 'var(--muted-foreground)',
                  fontWeight: moreSectorSelected ? 700 : 500,
                }}
              >
                <option value="">More sectors…</option>
                {SECTORS.slice(6).map(s => (
                  <option key={s} value={s}>{s}</option>
                ))}
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {error && !loading && (
        <div style={{
          padding: 12,
          background: 'color-mix(in oklab, var(--destructive) 10%, var(--card) 90%)',
          border: '1px solid color-mix(in oklab, var(--destructive) 45%, var(--border) 55%)',
          borderRadius: 8,
          fontSize: 13,
          color: 'var(--destructive)',
          marginBottom: 12,
        }}>
          {error}
        </div>
      )}

      <div style={{ background: 'var(--card)', borderRadius: 12, border: '1px solid var(--border)', overflowX: 'auto', overflowY: 'hidden' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '100px 1fr 90px 90px 110px 80px 110px',
          padding: '10px 16px',
          borderBottom: '1px solid var(--border)',
          background: 'var(--muted)',
        }}>
          {([
            ['symbol', 'Symbol'],
            ['companyName', 'Company'],
            ['price', 'Price'],
            ['changesPercentage', 'Change %'],
            ['marketCap', 'Market Cap'],
            ['pe', 'P/E'],
            ['volume', 'Volume'],
          ] as [keyof ScreenerRow, string][]).map(([key, label]) => (
            <span
              key={key}
              onClick={() => handleSort(key)}
              style={{
                fontSize: 11, color: 'var(--muted-foreground)', fontWeight: 700,
                textTransform: 'uppercase', letterSpacing: '0.05em',
                cursor: 'pointer', userSelect: 'none',
              }}
            >
              {label}<SortIcon k={key} />
            </span>
          ))}
        </div>

        {loading && <ScreenerSkeletonRows />}

        {!loading && filtered.map((row, i) => (
          <div
            key={row.symbol}
            onClick={() => handleRowClick(row.symbol)}
            style={{
              display: 'grid',
              gridTemplateColumns: '100px 1fr 90px 90px 110px 80px 110px',
              padding: '11px 16px',
              borderBottom: i < filtered.length - 1 ? '1px solid var(--border)' : 'none',
              cursor: 'pointer',
              alignItems: 'center',
              transition: 'background 0.15s ease',
            }}
            onMouseEnter={e => (e.currentTarget.style.background = 'var(--muted)')}
            onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
          >
            <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--primary)' }}>{row.symbol}</span>
            <span style={{ fontSize: 12, color: 'var(--foreground)' }}>{row.companyName}</span>
            <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--foreground)' }}>
              {row.price != null ? `$${row.price.toFixed(2)}` : '—'}
            </span>
            <span style={{
              fontSize: 12, fontWeight: 600,
              color: row.changesPercentage >= 0 ? '#16A34A' : '#DC2626',
            }}>
              {row.changesPercentage >= 0 ? '+' : ''}{row.changesPercentage?.toFixed(2)}%
            </span>
            <span style={{ fontSize: 12, color: 'var(--foreground)' }}>
              {row.marketCap ? fmtCap(row.marketCap) : '—'}
            </span>
            <span style={{ fontSize: 12, color: 'var(--foreground)' }}>
              {row.pe != null && row.pe > 0 ? row.pe.toFixed(1) : '—'}
            </span>
            <span style={{ fontSize: 12, color: 'var(--foreground)' }}>
              {row.volume ? fmtCap(row.volume).replace('$', '') : '—'}
            </span>
          </div>
        ))}

        {!loading && filtered.length === 0 && !error && (
          <div style={{ padding: 32, textAlign: 'center', color: 'var(--muted-foreground)', fontSize: 13 }}>
            No results match your filters
          </div>
        )}
      </div>

      {!loading && filtered.length > 0 && (
        <div style={{ marginTop: 8, fontSize: 11, color: 'var(--muted-foreground)' }}>
          {filtered.length} companies · Click any row to view chart & research
        </div>
      )}
    </div>
  );
}
