'use client';

import { TrendingUp, Coins, BarChart3, Star } from 'lucide-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import DataFetchError from '@/components/DataFetchError';

const FETCH_TIMEOUT_MS = 15000;

interface IndexItem {
  symbol: string;
  name: string;
  price: number;
  change: number;
}

interface SummaryData {
  indices?: IndexItem[];
  updated_at?: number;
}

interface Collection {
  id: string;
  title: string;
  category?: string;
  description?: string;
}

interface HeatmapSector {
  name?: string;
  symbol?: string;
  change?: number;
  [key: string]: unknown;
}

interface HeatmapData {
  sectors?: HeatmapSector[];
  updated_at?: number;
}

type FinanceTab = 'overview' | 'crypto' | 'movers' | 'watchlist';

interface MoverItem {
  symbol?: string;
  name?: string;
  price?: number;
  changesPercentage?: number;
  change?: number;
}

const WATCHLIST_KEY = 'gooseek_finance_watchlist';

const Page = () => {
  const [tab, setTab] = useState<FinanceTab>('overview');
  const [summary, setSummary] = useState<SummaryData | null>(null);
  const [heatmap, setHeatmap] = useState<HeatmapData | null>(null);
  const [collections, setCollections] = useState<Collection[]>([]);
  const [gainers, setGainers] = useState<MoverItem[]>([]);
  const [losers, setLosers] = useState<MoverItem[]>([]);
  const [crypto, setCrypto] = useState<MoverItem[]>([]);
  const [watchlist, setWatchlist] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchSummary = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/v1/finance/summary', {
        signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
      });
      if (!res.ok) throw new Error('Failed to fetch');
      const data = await res.json();
      setSummary(data);
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Error';
      const isTimeout = msg.includes('timeout') || (err as Error)?.name === 'AbortError';
      setError(isTimeout ? 'Request timed out. Try again.' : msg);
      toast.error(msg);
      setSummary({ indices: [] });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSummary();
  }, []);

  useEffect(() => {
    fetch('/api/v1/finance/heatmap', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
      .then((r) => r.json())
      .then((d: HeatmapData) => setHeatmap(d))
      .catch(() => setHeatmap({ sectors: [] }));
  }, []);

  useEffect(() => {
    fetch('/api/v1/collections?category=finance')
      .then((r) => r.json())
      .then((d) => setCollections(d.items ?? []))
      .catch(() => {});
  }, []);

  useEffect(() => {
    fetch('/api/v1/finance/gainers', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
      .then((r) => r.json())
      .then((d) => setGainers(d.items ?? []))
      .catch(() => setGainers([]));
  }, []);
  useEffect(() => {
    fetch('/api/v1/finance/losers', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
      .then((r) => r.json())
      .then((d) => setLosers(d.items ?? []))
      .catch(() => setLosers([]));
  }, []);
  useEffect(() => {
    fetch('/api/v1/finance/crypto', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
      .then((r) => r.json())
      .then((d) => setCrypto(d.items ?? []))
      .catch(() => setCrypto([]));
  }, []);
  useEffect(() => {
    try {
      const raw = localStorage.getItem(WATCHLIST_KEY);
      setWatchlist(raw ? JSON.parse(raw) : []);
    } catch {
      setWatchlist([]);
    }
  }, []);

  return (
    <div className="flex flex-col pt-10 pb-28 lg:pb-8 px-4 max-w-4xl mx-auto w-full">
      <div className="flex items-center gap-3 border-b border-light-200/20 dark:border-dark-200/20 pb-6">
        <TrendingUp size={40} className="text-[#EA580C]" />
        <h1 className="text-4xl font-normal">Finance</h1>
      </div>

      <div className="mt-4 flex flex-wrap gap-2">
        {(['overview', 'crypto', 'movers', 'watchlist'] as const).map((t) => (
          <button
            key={t}
            type="button"
            onClick={() => setTab(t)}
            className={cn(
              'flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-medium transition-colors',
              tab === t
                ? 'bg-[#EA580C] text-white'
                : 'bg-light-secondary dark:bg-dark-secondary text-black/70 dark:text-white/70 hover:bg-light-200 dark:hover:bg-dark-200'
            )}
          >
            {t === 'overview' && <TrendingUp size={16} />}
            {t === 'crypto' && <Coins size={16} />}
            {t === 'movers' && <BarChart3 size={16} />}
            {t === 'watchlist' && <Star size={16} />}
            {t === 'overview' && 'Overview'}
            {t === 'crypto' && 'Crypto'}
            {t === 'movers' && 'Gainers & Losers'}
            {t === 'watchlist' && `Watchlist (${watchlist.length})`}
          </button>
        ))}
        <Link
          href="/finance/predictions/polymarket"
          className="text-sm text-[#EA580C] hover:underline self-center ml-2"
        >
          Predictions →
        </Link>
      </div>

      {error ? (
        <DataFetchError message={error} onRetry={fetchSummary} />
      ) : loading ? (
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-6">
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="rounded-2xl bg-light-secondary dark:bg-dark-secondary p-4 animate-pulse"
            >
              <div className="h-4 w-20 bg-light-200 dark:bg-dark-200 rounded mb-3" />
              <div className="h-6 w-24 bg-light-200 dark:bg-dark-200 rounded mb-2" />
              <div className="h-4 w-16 bg-light-200 dark:bg-dark-200 rounded" />
            </div>
          ))}
        </div>
      ) : (
        <>
        {tab === 'overview' && summary?.indices && summary.indices.length > 0 && (
        <>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-6">
          {summary.indices.map((idx) => (
            <Link
              key={idx.symbol}
              href={`/finance/${encodeURIComponent(idx.symbol)}`}
              className="rounded-2xl bg-light-secondary dark:bg-dark-secondary p-4 shadow-sm border border-light-200/20 dark:border-dark-200/20 block hover:border-[#EA580C]/30 transition-colors"
            >
              <p className="text-sm text-black/60 dark:text-white/60">{idx.name}</p>
              <p className="text-xl font-medium mt-1">
                {idx.price > 0 ? idx.price.toLocaleString() : '—'}
              </p>
              <p
                className={cn(
                  'text-sm mt-1',
                  idx.change > 0 ? 'text-green-600' : idx.change < 0 ? 'text-red-600' : 'text-black/60 dark:text-white/60'
                )}
              >
                {idx.change !== 0 ? `${idx.change > 0 ? '+' : ''}${idx.change.toFixed(2)}%` : '—'}
              </p>
            </Link>
          ))}
        </div>

        <section className="mt-10">
          <h2 className="text-xl font-medium mb-4">S&P 500 Sector Heatmap</h2>
          {heatmap?.sectors && heatmap.sectors.length > 0 ? (
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              {heatmap.sectors.map((s, i) => {
                const ch = typeof s.change === 'number' ? s.change : 0;
                const label = (s.name ?? s.symbol ?? `Sector ${i + 1}`).toString();
                return (
                  <div
                    key={i}
                    className={cn(
                      'rounded-xl p-3 text-center text-sm font-medium',
                      ch > 0 && 'bg-green-500/20 text-green-700 dark:text-green-400',
                      ch < 0 && 'bg-red-500/20 text-red-700 dark:text-red-400',
                      ch === 0 && 'bg-light-secondary dark:bg-dark-secondary text-black/70 dark:text-white/70'
                    )}
                  >
                    <span className="truncate block">{label}</span>
                    <span className="text-xs mt-0.5">
                      {ch > 0 ? '+' : ''}{ch.toFixed(2)}%
                    </span>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="rounded-2xl bg-light-secondary dark:bg-dark-secondary p-6 text-black/60 dark:text-white/60 text-sm">
              <p>Sector heatmap will appear when finance-svc has market data (FMP_API_KEY + cache-worker).</p>
            </div>
          )}
        </section>

        <section className="mt-10">
          <h2 className="text-xl font-medium mb-4">Popular Spaces for Finance Research</h2>
          {collections.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {collections.map((c) => (
                <Link
                  key={c.id}
                  href={`/collections/${c.id}`}
                  className="rounded-2xl bg-light-secondary dark:bg-dark-secondary p-4 border border-light-200/20 dark:border-dark-200/20 hover:border-[#EA580C]/30 transition-colors block"
                >
                  <h3 className="font-medium">{c.title}</h3>
                  {c.description && (
                    <p className="text-sm text-black/60 dark:text-white/60 mt-1 line-clamp-2">{c.description}</p>
                  )}
                </Link>
              ))}
            </div>
          ) : (
            <div className="rounded-2xl bg-light-secondary dark:bg-dark-secondary p-4 text-black/60 dark:text-white/60 text-sm">
              <p>Collections will appear when projects-svc is running.</p>
            </div>
          )}
        </section>
        </>
        )}

        {tab === 'crypto' && (
          <div className="mt-6">
            <h2 className="text-xl font-medium mb-4">Popular Cryptocurrencies</h2>
            {crypto.length > 0 ? (
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {crypto.map((c, i) => (
                  <Link
                    key={c.symbol ?? i}
                    href={`/finance/${encodeURIComponent(c.symbol ?? '')}`}
                    className="rounded-xl p-3 bg-light-secondary dark:bg-dark-secondary border border-light-200/20 dark:border-dark-200/20 hover:border-[#EA580C]/30 transition-colors"
                  >
                    <p className="text-sm font-medium truncate">{c.symbol ?? '—'}</p>
                    <p className="text-lg mt-0.5">
                      {c.price != null ? `$${Number(c.price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 4 })}` : '—'}
                    </p>
                    <p className={cn(
                      'text-xs mt-0.5',
                      (c.changesPercentage ?? c.change ?? 0) > 0 ? 'text-green-600' : 'text-red-600'
                    )}>
                      {(c.changesPercentage ?? c.change ?? 0) !== 0
                        ? `${(c.changesPercentage ?? c.change ?? 0) > 0 ? '+' : ''}${(c.changesPercentage ?? c.change ?? 0).toFixed(2)}%`
                        : '—'}
                    </p>
                  </Link>
                ))}
              </div>
            ) : (
              <p className="text-black/60 dark:text-white/60 text-sm">Set FMP_API_KEY for crypto data.</p>
            )}
          </div>
        )}

        {tab === 'movers' && (
          <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="text-lg font-medium mb-3 text-green-600">Top Gainers</h3>
              {gainers.length > 0 ? (
                <div className="space-y-2">
                  {gainers.slice(0, 8).map((g, i) => (
                    <Link
                      key={g.symbol ?? i}
                      href={`/finance/${encodeURIComponent(g.symbol ?? '')}`}
                      className="flex justify-between items-center rounded-lg p-2 hover:bg-light-secondary dark:hover:bg-dark-secondary"
                    >
                      <span className="font-medium truncate max-w-[120px]">{g.symbol ?? '—'}</span>
                      <span className="text-green-600 text-sm">
                        +{((g.changesPercentage ?? g.change) ?? 0).toFixed(2)}%
                      </span>
                    </Link>
                  ))}
                </div>
              ) : (
                <p className="text-black/60 dark:text-white/60 text-sm">FMP_API_KEY required.</p>
              )}
            </div>
            <div>
              <h3 className="text-lg font-medium mb-3 text-red-600">Top Losers</h3>
              {losers.length > 0 ? (
                <div className="space-y-2">
                  {losers.slice(0, 8).map((l, i) => (
                    <Link
                      key={l.symbol ?? i}
                      href={`/finance/${encodeURIComponent(l.symbol ?? '')}`}
                      className="flex justify-between items-center rounded-lg p-2 hover:bg-light-secondary dark:hover:bg-dark-secondary"
                    >
                      <span className="font-medium truncate max-w-[120px]">{l.symbol ?? '—'}</span>
                      <span className="text-red-600 text-sm">
                        {((l.changesPercentage ?? l.change) ?? 0).toFixed(2)}%
                      </span>
                    </Link>
                  ))}
                </div>
              ) : (
                <p className="text-black/60 dark:text-white/60 text-sm">FMP_API_KEY required.</p>
              )}
            </div>
          </div>
        )}

        {tab === 'watchlist' && (
          <div className="mt-6">
            <h2 className="text-xl font-medium mb-4">My Watchlist</h2>
            <p className="text-sm text-black/60 dark:text-white/60 mb-4">
              Add tickers from search or ticker pages. Stored locally.
            </p>
            {watchlist.length > 0 ? (
              <div className="flex flex-wrap gap-2">
                {watchlist.map((ticker) => (
                  <Link
                    key={ticker}
                    href={`/finance/${ticker}`}
                    className="px-4 py-2 rounded-xl bg-light-secondary dark:bg-dark-secondary border border-light-200/20 dark:border-dark-200/20 hover:border-[#EA580C]/30"
                  >
                    {ticker}
                  </Link>
                ))}
              </div>
            ) : (
              <p className="text-black/60 dark:text-white/60">No tickers in watchlist yet.</p>
            )}
          </div>
        )}
        </>
      )}

      {!summary?.indices?.length && tab === 'overview' && (
        <div className="mt-6 p-6 rounded-2xl bg-light-secondary dark:bg-dark-secondary text-center text-black/60 dark:text-white/60">
          <p>Market data will appear here when finance-svc is running with FMP_API_KEY.</p>
          <p className="text-sm mt-2">Enable finance-svc in deploy.config.yaml</p>
        </div>
      )}
    </div>
  );
};

export default Page;
