import { useMemo, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useTickerDetail } from '../hooks/useTickerDetail';
import { CandlestickChart } from '../components/charts/CandlestickChart';
import { ScoreCard } from '../components/ui/ScoreCard';
import { SkeletonCard } from '../components/ui/Skeleton';
import { SentimentPanel } from '../components/ticker/SentimentPanel';
import { FundamentalsPanel } from '../components/ticker/FundamentalsPanel';
import { IndicatorSelector } from '../components/ticker/IndicatorSelector';
import { useToast } from '../components/ui/Toast';
import { fetchData } from '../api/ingestion';
import { formatPrice } from '../lib/format';
import type { TradeSetup } from '../lib/types';

function SectionError({ message, onRetry }: { message: string; onRetry?: () => void }) {
  return (
    <div className="glass-sm bg-red-500/10 border-red-500/20 p-4 text-sm text-red-400">
      <p>{message}</p>
      {onRetry && (
        <button onClick={onRetry} className="mt-2 text-xs font-medium text-red-300 underline hover:text-red-200">
          Retry
        </button>
      )}
    </div>
  );
}

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60_000);
  if (mins < 1) return 'just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  return `${days}d ago`;
}

interface DataStatusItem {
  label: string;
  available: boolean;
  timestamp?: string | null;
}

function DataFreshnessBar({ items }: { items: DataStatusItem[] }) {
  return (
    <div className="glass-sm p-3 flex flex-wrap gap-4">
      {items.map((item) => (
        <div key={item.label} className="flex items-center gap-2">
          <span className={`inline-block h-2 w-2 rounded-full shrink-0 ${
            item.available ? 'bg-emerald-400 shadow-lg shadow-emerald-400/40' : 'bg-gray-600'
          }`} />
          <span className="text-xs text-gray-400">{item.label}</span>
          {item.available && item.timestamp && (
            <span className="text-[10px] text-gray-500">{timeAgo(item.timestamp)}</span>
          )}
          {!item.available && (
            <span className="text-[10px] text-gray-600">no data</span>
          )}
        </div>
      ))}
    </div>
  );
}

export default function TickerDetailPage() {
  const { symbol = '' } = useParams<{ symbol: string }>();
  const { ohlcv, scores, srLevels, sentiment, fundamentals, trades } = useTickerDetail(symbol);
  const queryClient = useQueryClient();
  const { addToast } = useToast();

  const ingestion = useMutation({
    mutationFn: () => fetchData(symbol),
    onSuccess: (result: any) => {
      // Show per-source status breakdown
      const sources = result?.sources;
      if (sources) {
        const parts: string[] = [];
        for (const [name, info] of Object.entries(sources) as [string, any][]) {
          const label = name.charAt(0).toUpperCase() + name.slice(1);
          if (info.status === 'ok') {
            parts.push(`${label} ✓`);
          } else if (info.status === 'skipped') {
            parts.push(`${label}: skipped (${info.message})`);
          } else {
            parts.push(`${label} ✗: ${info.message}`);
          }
        }
        const hasError = Object.values(sources).some((s: any) => s.status === 'error');
        const hasSkip = Object.values(sources).some((s: any) => s.status === 'skipped');
        const toastType = hasError ? 'error' : hasSkip ? 'info' : 'success';
        addToast(toastType, parts.join(' · '));
      } else {
        addToast('success', `Data fetched for ${symbol.toUpperCase()}`);
      }
      queryClient.invalidateQueries({ queryKey: ['ohlcv', symbol] });
      queryClient.invalidateQueries({ queryKey: ['sentiment', symbol] });
      queryClient.invalidateQueries({ queryKey: ['fundamentals', symbol] });
      queryClient.invalidateQueries({ queryKey: ['sr-levels', symbol] });
      queryClient.invalidateQueries({ queryKey: ['scores', symbol] });
    },
    onError: (err: Error) => {
      addToast('error', err.message || 'Failed to fetch data');
    },
  });

  const dataStatus: DataStatusItem[] = useMemo(() => [
    {
      label: 'OHLCV',
      available: !!ohlcv.data && ohlcv.data.length > 0,
      timestamp: ohlcv.data?.[ohlcv.data.length - 1]?.created_at,
    },
    {
      label: 'Sentiment',
      available: !!sentiment.data && sentiment.data.count > 0,
      timestamp: sentiment.data?.scores?.[0]?.timestamp,
    },
    {
      label: 'Fundamentals',
      available: !!fundamentals.data && fundamentals.data.fetched_at !== null,
      timestamp: fundamentals.data?.fetched_at,
    },
    {
      label: 'S/R Levels',
      available: !!srLevels.data && srLevels.data.count > 0,
      timestamp: srLevels.data?.levels?.[0]?.created_at,
    },
    {
      label: 'Scores',
      available: !!scores.data && scores.data.composite_score !== null,
      timestamp: scores.data?.computed_at,
    },
  ], [ohlcv.data, sentiment.data, fundamentals.data, srLevels.data, scores.data]);

  // Log trades API errors but don't disrupt the page
  useEffect(() => {
    if (trades.error) {
      console.error('Failed to fetch trade setups:', trades.error);
    }
  }, [trades.error]);

  // Pick the latest trade setup for the current symbol
  const tradeSetup: TradeSetup | undefined = useMemo(() => {
    if (trades.error || !trades.data) return undefined;
    const matching = trades.data.filter(
      (t) => t.symbol.toUpperCase() === symbol.toUpperCase(),
    );
    if (matching.length === 0) return undefined;
    return matching.reduce((latest, t) =>
      new Date(t.detected_at) > new Date(latest.detected_at) ? t : latest,
    );
  }, [trades.data, trades.error, symbol]);

  // Sort visible S/R levels by strength for the table (only levels within chart zones)
  const sortedLevels = useMemo(() => {
    if (!srLevels.data?.visible_levels) return [];
    return [...srLevels.data.visible_levels].sort((a, b) => b.strength - a.strength);
  }, [srLevels.data]);

  return (
    <div className="space-y-6 animate-slide-up">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gradient">{symbol.toUpperCase()}</h1>
          <p className="text-sm text-gray-500 mt-0.5">Ticker Detail</p>
        </div>
        <button
          onClick={() => ingestion.mutate()}
          disabled={ingestion.isPending}
          className="btn-gradient inline-flex items-center gap-2 px-5 py-2.5 text-sm disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {ingestion.isPending && (
            <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          )}
          <span>{ingestion.isPending ? 'Fetching…' : 'Fetch Data'}</span>
        </button>
      </div>

      {/* Data freshness bar */}
      <DataFreshnessBar items={dataStatus} />

      {/* Chart Section */}
      <section>
        <h2 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">Price Chart</h2>
        {ohlcv.isLoading && <SkeletonCard className="h-[400px]" />}
        {ohlcv.isError && (
          <SectionError
            message={ohlcv.error instanceof Error ? ohlcv.error.message : 'Failed to load OHLCV data'}
            onRetry={() => ohlcv.refetch()}
          />
        )}
        {ohlcv.data && (
          <div className="glass p-5">
            <CandlestickChart data={ohlcv.data} srLevels={srLevels.data?.levels} zones={srLevels.data?.zones} tradeSetup={tradeSetup} />
            {srLevels.isError && (
              <p className="mt-2 text-xs text-yellow-500/80">S/R levels unavailable — chart shown without overlays</p>
            )}
          </div>
        )}
      </section>

      {/* Trade Setup Summary Card */}
      {tradeSetup && (
        <section>
          <h2 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">Trade Setup</h2>
          <div className="glass p-5">
            <div className="flex flex-wrap items-center gap-6">
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-500">Direction</span>
                <span className={`text-sm font-semibold ${tradeSetup.direction === 'long' ? 'text-emerald-400' : 'text-red-400'}`}>
                  {tradeSetup.direction.toUpperCase()}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-500">Entry</span>
                <span className="text-sm font-mono text-blue-300">{formatPrice(tradeSetup.entry_price)}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-500">Stop</span>
                <span className="text-sm font-mono text-red-400">{formatPrice(tradeSetup.stop_loss)}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-500">Target</span>
                <span className="text-sm font-mono text-emerald-400">{formatPrice(tradeSetup.target)}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-500">R:R</span>
                <span className="text-sm font-semibold text-gray-200">{tradeSetup.rr_ratio.toFixed(2)}</span>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Scores + Side Panels */}
      <div className="grid gap-6 lg:grid-cols-3">
        <section>
          <h2 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">Scores</h2>
          {scores.isLoading && <SkeletonCard />}
          {scores.isError && (
            <SectionError message={scores.error instanceof Error ? scores.error.message : 'Failed to load scores'} onRetry={() => scores.refetch()} />
          )}
          {scores.data && (
            <ScoreCard compositeScore={scores.data.composite_score} dimensions={scores.data.dimensions} compositeBreakdown={scores.data.composite_breakdown} />
          )}
        </section>

        <section>
          <h2 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">Sentiment</h2>
          {sentiment.isLoading && <SkeletonCard />}
          {sentiment.isError && (
            <SectionError message={sentiment.error instanceof Error ? sentiment.error.message : 'Failed to load sentiment'} onRetry={() => sentiment.refetch()} />
          )}
          {sentiment.data && <SentimentPanel data={sentiment.data} />}
        </section>

        <section>
          <h2 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">Fundamentals</h2>
          {fundamentals.isLoading && <SkeletonCard />}
          {fundamentals.isError && (
            <SectionError message={fundamentals.error instanceof Error ? fundamentals.error.message : 'Failed to load fundamentals'} onRetry={() => fundamentals.refetch()} />
          )}
          {fundamentals.data && <FundamentalsPanel data={fundamentals.data} />}
        </section>
      </div>

      {/* Indicators */}
      <section>
        <h2 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">Technical Indicators</h2>
        <IndicatorSelector symbol={symbol} />
      </section>

      {/* S/R Levels Table — sorted by strength */}
      {sortedLevels.length > 0 && (
        <section>
          <h2 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">
            Support &amp; Resistance Levels
            <span className="ml-2 text-gray-600 normal-case tracking-normal">sorted by strength</span>
          </h2>
          <div className="glass overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/[0.06] text-left text-xs uppercase tracking-wider text-gray-500">
                  <th className="px-4 py-3">Type</th>
                  <th className="px-4 py-3">Price Level</th>
                  <th className="px-4 py-3">Strength</th>
                  <th className="px-4 py-3">Method</th>
                </tr>
              </thead>
              <tbody>
                {sortedLevels.map((level) => (
                  <tr key={level.id} className="border-b border-white/[0.04] transition-colors duration-150 hover:bg-white/[0.03]">
                    <td className="px-4 py-3">
                      <span className={level.type === 'support' ? 'text-emerald-400' : 'text-red-400'}>{level.type}</span>
                    </td>
                    <td className="px-4 py-3 text-gray-200 font-mono">{formatPrice(level.price_level)}</td>
                    <td className="px-4 py-3 text-gray-200">{level.strength}</td>
                    <td className="px-4 py-3 text-gray-400">{level.detection_method}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      )}
    </div>
  );
}
