'use client';

import { ChevronLeft, TrendingUp, FileText, BarChart3, Sparkles, Star } from 'lucide-react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';

interface QuoteData {
  symbol: string;
  name: string;
  price: number;
  change: number;
  high?: number;
  low?: number;
}

interface NewsItem {
  title?: string;
  url?: string;
  publishedDate?: string;
}

interface SecFiling {
  type?: string;
  fillingDate?: string;
  finalLink?: string;
  description?: string;
}

const WATCHLIST_KEY = 'gooseek_finance_watchlist';

const Page = () => {
  const params = useParams();
  const ticker = (params?.ticker as string)?.toUpperCase() ?? '';
  const [quote, setQuote] = useState<QuoteData | null>(null);
  const [inWatchlist, setInWatchlist] = useState(false);
  const [news, setNews] = useState<NewsItem[]>([]);
  const [filings, setFilings] = useState<SecFiling[]>([]);
  const [priceContext, setPriceContext] = useState<{
    summary?: string | null;
    news?: string[];
  } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!ticker) return;
    try {
      const raw = localStorage.getItem(WATCHLIST_KEY);
      const list = raw ? JSON.parse(raw) : [];
      setInWatchlist(Array.isArray(list) && list.includes(ticker));
    } catch {
      setInWatchlist(false);
    }
  }, [ticker]);

  const toggleWatchlist = () => {
    try {
      const raw = localStorage.getItem(WATCHLIST_KEY);
      const list: string[] = raw ? JSON.parse(raw) : [];
      const idx = list.indexOf(ticker);
      if (idx >= 0) {
        list.splice(idx, 1);
        setInWatchlist(false);
      } else {
        list.push(ticker);
        setInWatchlist(true);
      }
      localStorage.setItem(WATCHLIST_KEY, JSON.stringify(list));
    } catch {
      toast.error('Failed to update watchlist');
    }
  };

  useEffect(() => {
    if (!ticker) return;
    const fetchData = async () => {
      setLoading(true);
      try {
        const [quoteRes, newsRes, filingsRes, contextRes] = await Promise.all([
          fetch(`/api/v1/finance/quote/${ticker}`),
          fetch(`/api/v1/finance/news/${ticker}`),
          fetch(`/api/v1/finance/sec-filings/${ticker}`),
          fetch(`/api/v1/finance/price-context/${ticker}`),
        ]);
        if (quoteRes.ok) setQuote(await quoteRes.json());
        if (newsRes.ok) {
          const d = await newsRes.json();
          setNews(Array.isArray(d?.items) ? d.items : []);
        }
        if (filingsRes.ok) {
          const d = await filingsRes.json();
          setFilings(Array.isArray(d?.filings) ? d.filings : []);
        }
        if (contextRes.ok) {
          const d = await contextRes.json();
          if (d.summary || (d.news && d.news.length > 0)) {
            setPriceContext({ summary: d.summary ?? null, news: d.news ?? [] });
          }
        }
      } catch {
        toast.error('Failed to load ticker data');
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [ticker]);

  return (
    <div className="flex flex-col pt-10 pb-28 lg:pb-8 px-4 max-w-4xl mx-auto w-full">
      <Link
        href="/finance"
        className="inline-flex items-center gap-1 text-sm text-black/60 dark:text-white/60 hover:text-black dark:hover:text-white mb-4"
      >
        <ChevronLeft size={16} />
        Back to Finance
      </Link>

      <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-3xl font-normal">{ticker}</h1>
        <button
          type="button"
          onClick={toggleWatchlist}
          className={cn(
            'p-2 rounded-lg transition-colors',
            inWatchlist ? 'text-yellow-500 hover:text-yellow-600' : 'text-black/40 dark:text-white/40 hover:text-[#EA580C]'
          )}
          title={inWatchlist ? 'Remove from watchlist' : 'Add to watchlist'}
        >
          <Star size={24} fill={inWatchlist ? 'currentColor' : 'none'} />
        </button>
      </div>

      {loading ? (
        <div className="mt-6 space-y-4">
          <div className="h-24 rounded-2xl bg-light-secondary dark:bg-dark-secondary animate-pulse" />
          <div className="h-32 rounded-2xl bg-light-secondary dark:bg-dark-secondary animate-pulse" />
        </div>
      ) : quote ? (
        <>
          <div className="mt-6 rounded-2xl bg-light-secondary dark:bg-dark-secondary p-6 shadow-sm border border-light-200/20 dark:border-dark-200/20">
            <p className="text-sm text-black/60 dark:text-white/60">{quote.name || ticker}</p>
            <p className="text-3xl font-medium mt-1">
              {quote.price > 0 ? `$${quote.price.toLocaleString(undefined, { minimumFractionDigits: 2 })}` : '—'}
            </p>
            <p
              className={cn(
                'text-lg mt-1',
                quote.change > 0 ? 'text-green-600' : quote.change < 0 ? 'text-red-600' : 'text-black/60 dark:text-white/60'
              )}
            >
              {quote.change !== 0 ? `${quote.change > 0 ? '+' : ''}${quote.change.toFixed(2)}%` : '—'}
            </p>
            {quote.high != null && quote.low != null && quote.high > 0 && quote.low > 0 && (
              <p className="text-sm text-black/60 dark:text-white/60 mt-2">
                Day range: ${quote.low.toFixed(2)} – ${quote.high.toFixed(2)}
              </p>
            )}
          </div>

          {priceContext && (priceContext.summary || (priceContext.news && priceContext.news.length > 0)) && (
            <div className="mt-4 rounded-2xl bg-light-secondary/80 dark:bg-dark-secondary/80 p-4 border border-light-200/30 dark:border-dark-200/30">
              <h3 className="text-sm font-medium flex items-center gap-2 mb-2">
                <Sparkles size={16} className="text-[#EA580C]" />
                Price movement context
              </h3>
              {priceContext.summary ? (
                <p className="text-sm text-black/80 dark:text-white/80">{priceContext.summary}</p>
              ) : priceContext.news && priceContext.news.length > 0 ? (
                <ul className="text-sm text-black/70 dark:text-white/70 space-y-1">
                  {priceContext.news.slice(0, 3).map((h, i) => (
                    <li key={i}>• {h}</li>
                  ))}
                </ul>
              ) : null}
            </div>
          )}

          {news.length > 0 && (
            <div className="mt-6">
              <h2 className="text-lg font-medium mb-3 flex items-center gap-2">
                <BarChart3 size={20} /> News
              </h2>
              <ul className="space-y-2">
                {news.slice(0, 5).map((item, i) => (
                  <li key={i}>
                    <a
                      href={item.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-600 dark:text-blue-400 hover:underline block truncate"
                    >
                      {item.title ?? 'News'}
                    </a>
                    {item.publishedDate && (
                      <span className="text-xs text-black/50 dark:text-white/50">{item.publishedDate}</span>
                    )}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {filings.length > 0 && (
            <div className="mt-6">
              <h2 className="text-lg font-medium mb-3 flex items-center gap-2">
                <FileText size={20} /> SEC Filings
              </h2>
              <ul className="space-y-2">
                {filings.slice(0, 10).map((f, i) => (
                  <li key={i} className="flex items-center justify-between gap-2">
                    <span className="text-sm">{f.type ?? 'Filing'}</span>
                    <a
                      href={f.finalLink}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-600 dark:text-blue-400 hover:underline text-sm truncate max-w-[200px]"
                    >
                      {f.fillingDate ?? 'View'}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {news.length === 0 && filings.length === 0 && quote.price === 0 && (
            <p className="mt-6 text-black/60 dark:text-white/60 text-sm">
              Set FMP_API_KEY in finance-svc for full data.
            </p>
          )}
        </>
      ) : (
        <p className="mt-6 text-black/60 dark:text-white/60">Ticker not found.</p>
      )}
    </div>
  );
};

export default Page;
