'use client';

import { useQueryClient } from '@tanstack/react-query';
import Link from 'next/link';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { format } from 'date-fns';
import { ArrowLeft, BrainCircuit, RefreshCcw } from 'lucide-react';
import { useParams } from 'next/navigation';
import { AppShell } from '@/components/shell/app-shell';
import { useAuthGuard } from '@/hooks/use-auth-guard';
import { useLinkPrefetch } from '@/hooks/use-link-prefetch';
import { queryKeys } from '@/lib/query/keys';
import { aiReportQueryOptions } from '@/lib/query/options';
import type { CompanyAiReportDetail } from '@/lib/types';
import { Button } from '@/components/ui/button';
import { Panel } from '@/components/ui/panel';

function formatFilingDate(value: string) {
  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return 'Unknown';
  }

  return format(date, 'MMM dd, yyyy');
}

export default function AnalysisReportPage() {
  const { isPending, isAuthenticated } = useAuthGuard();
  const params = useParams<{ ticker: string; accessionNumber: string }>();
  const queryClient = useQueryClient();
  const { prefetchResearchTicker } = useLinkPrefetch();

  const tickerFromRoute = useMemo(() => {
    const value = typeof params.ticker === 'string' ? params.ticker : '';
    return value.toUpperCase();
  }, [params.ticker]);

  const accessionNumber = useMemo(() => {
    const value = typeof params.accessionNumber === 'string' ? params.accessionNumber : '';
    return decodeURIComponent(value);
  }, [params.accessionNumber]);

  const [report, setReport] = useState<CompanyAiReportDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadReport = useCallback(async () => {
    if (!accessionNumber) {
      setError('Invalid accession number.');
      setReport(null);
      setLoading(false);
      return;
    }

    const options = aiReportQueryOptions(accessionNumber);

    if (!queryClient.getQueryData(options.queryKey)) {
      setLoading(true);
    }

    setError(null);

    try {
      const response = await queryClient.ensureQueryData(options);
      setReport(response.report);
    } catch (err) {
      setReport(null);
      setError(err instanceof Error ? err.message : 'Unable to load AI summary');
    } finally {
      setLoading(false);
    }
  }, [accessionNumber, queryClient]);

  useEffect(() => {
    if (!isPending && isAuthenticated) {
      void loadReport();
    }
  }, [isPending, isAuthenticated, loadReport]);

  if (isPending || !isAuthenticated) {
    return <div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading summary detail...</div>;
  }

  const resolvedTicker = report?.ticker ?? tickerFromRoute;
  const analysisHref = resolvedTicker ? `/analysis?ticker=${encodeURIComponent(resolvedTicker)}` : '/analysis';
  const filingsHref = resolvedTicker ? `/filings?ticker=${encodeURIComponent(resolvedTicker)}` : '/filings';

  return (
    <AppShell
      title="AI Summary"
      subtitle={`Detailed filing analysis${resolvedTicker ? ` for ${resolvedTicker}` : ''}.`}
      activeTicker={resolvedTicker}
      breadcrumbs={[
        { label: 'Analysis', href: analysisHref },
        { label: 'Reports', href: analysisHref },
        { label: resolvedTicker || 'Summary' }
      ]}
      actions={(
        <Button
          variant="secondary"
          onClick={() => {
            if (accessionNumber) {
              void queryClient.invalidateQueries({ queryKey: queryKeys.report(accessionNumber) });
            }
            void loadReport();
          }}
          disabled={loading}
        >
          <RefreshCcw className="size-4" />
          Refresh
        </Button>
      )}
    >
      <Panel>
        <div className="flex flex-wrap items-center gap-3">
          <Link
            href={analysisHref}
            onMouseEnter={() => prefetchResearchTicker(resolvedTicker)}
            onFocus={() => prefetchResearchTicker(resolvedTicker)}
            className="inline-flex items-center gap-1 text-xs uppercase tracking-[0.12em] text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
          >
            <ArrowLeft className="size-3" />
            Back to analysis
          </Link>
          <Link
            href={filingsHref}
            onMouseEnter={() => prefetchResearchTicker(resolvedTicker)}
            onFocus={() => prefetchResearchTicker(resolvedTicker)}
            className="inline-flex items-center gap-1 text-xs uppercase tracking-[0.12em] text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"
          >
            <ArrowLeft className="size-3" />
            Back to filings
          </Link>
        </div>
      </Panel>

      {loading ? (
        <Panel>
          <p className="text-sm text-[color:var(--terminal-muted)]">Loading AI summary...</p>
        </Panel>
      ) : null}

      {!loading && error ? (
        <Panel>
          <p className="text-sm text-[#ffb5b5]">{error}</p>
        </Panel>
      ) : null}

      {!loading && !error && report ? (
        <>
          <Panel
            title={`${report.companyName} (${report.ticker})`}
            subtitle={`${report.filingType} filed ${formatFilingDate(report.filingDate)} · ${report.provider} / ${report.model}`}
          >
            <div className="grid grid-cols-1 gap-3 text-sm md:grid-cols-2 xl:grid-cols-3">
              <div className="rounded-md border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-3 py-2">
                <p className="text-xs uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]">Accession</p>
                <p className="mt-1 break-all text-[color:var(--terminal-bright)]">{report.accessionNumber}</p>
              </div>
              <div className="rounded-md border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-3 py-2">
                <p className="text-xs uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]">Provider</p>
                <p className="mt-1 text-[color:var(--terminal-bright)]">{report.provider}</p>
              </div>
              <div className="rounded-md border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-3 py-2">
                <p className="text-xs uppercase tracking-[0.12em] text-[color:var(--terminal-muted)]">Model</p>
                <p className="mt-1 text-[color:var(--terminal-bright)]">{report.model}</p>
              </div>
            </div>
          </Panel>

          <Panel title="Summary" subtitle="Full AI-generated filing analysis.">
            <div className="mb-3 inline-flex items-center gap-2 rounded-md border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] px-2 py-1 text-xs text-[color:var(--terminal-muted)]">
              <BrainCircuit className="size-3.5" />
              Full text view
            </div>
            <p className="whitespace-pre-wrap text-sm leading-7 text-[color:var(--terminal-bright)]">
              {report.summary}
            </p>
          </Panel>
        </>
      ) : null}
    </AppShell>
  );
}
