'use client';

import { useEffect, useState, use } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
import { AnalysisView } from '@/components/analyzer/analysis-view';
import { ItglueSuggestionsPanel } from '@/components/analyzer/itglue-suggestions-panel';
import type { PersistedAnalysis } from '@/lib/types/analyzer';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { PageHeader } from '@/components/navigation/page-header';

export default function AnalysisDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const [analysis, setAnalysis] = useState<PersistedAnalysis | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch(`/api/analyzer/analyses/${id}`);
        if (!res.ok) {
          const data = (await res.json().catch(() => ({}))) as { error?: string };
          throw new Error(data.error ?? `Request failed: ${res.status}`);
        }
        const { analysis } = (await res.json()) as { analysis: PersistedAnalysis };
        if (!cancelled) setAnalysis(analysis);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : 'Unknown error');
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [id]);

  const ticketNumber = analysis?.ticketNumber;
  return (
    <>
      <PageHeader
        title={analysis?.ticketNumber ? `Analysis · ${analysis.ticketNumber}` : 'Analysis'}
        description={analysis?.id && `id ${analysis.id.slice(0, 8)}`}
        breadcrumbs={[
          { label: 'Analyzer', href: '/analyzer/tickets' },
          ...(ticketNumber
            ? [{ label: ticketNumber, href: `/analyzer/ticket/${encodeURIComponent(ticketNumber)}` }]
            : []),
          { label: 'Analysis' },
        ]}
        accent
      />
      <div className="container mx-auto px-6 py-6 max-w-5xl">
        {error && (
          <Alert variant="destructive">
            <AlertTitle>Couldn&rsquo;t load this analysis</AlertTitle>
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}
        {!error && !analysis && (
          <div className="space-y-4">
            <Skeleton className="h-32 w-full" />
            <Skeleton className="h-24 w-full" />
            <Skeleton className="h-24 w-full" />
          </div>
        )}
        {analysis && (
          <div className="space-y-6">
            <AnalysisView analysis={analysis} />
            <ItglueSuggestionsPanel analysisId={analysis.id} />
          </div>
        )}
      </div>
    </>
  );
}
