"use client";

import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import type { Analysis } from "@/lib/services/analysis-schema";
import { AnalysisArtifact } from "@/components/analysis-artifact";
import { NarrativeReport } from "@/components/analysis/narrative-report";
import { AlertCircle, Loader2 } from "lucide-react";

export default function SharedAnalysisPage() {
  const params = useParams();
  const token = params.token as string;

  const [analysis, setAnalysis] = useState<Analysis | null>(null);
  const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
  const [error, setError] = useState<string | null>(null);
  const [view, setView] = useState<"artifact" | "report">("artifact");

  useEffect(() => {
    if (!token) return;
    // Try client version first, fall back to full analysis
    fetch(`/api/analysis/client-version?token=${encodeURIComponent(token)}`)
      .then(res => res.ok ? res.json() : null)
      .then(clientData => {
        if (clientData?.analysis) {
          setAnalysis(clientData.analysis as Analysis);
          setStatus("loaded");
          return;
        }
        // Fall back to full analysis
        return fetch(`/api/analysis/share?token=${encodeURIComponent(token)}`)
          .then(res => {
            if (!res.ok) throw new Error("This analysis is no longer available or sharing has been disabled.");
            return res.json();
          })
          .then(data => {
            setAnalysis(data.analysis as Analysis);
            setStatus("loaded");
          });
      })
      .catch(err => {
        setError(err.message);
        setStatus("error");
      });
  }, [token]);

  if (status === "loading") {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-8 h-8 text-brand-500 animate-spin mx-auto mb-3" />
          <p className="text-sm text-slate-500">Loading analysis...</p>
        </div>
      </div>
    );
  }

  if (status === "error" || !analysis) {
    return (
      <div className="min-h-screen bg-slate-50 flex items-center justify-center">
        <div className="bg-white rounded-2xl border border-slate-200 p-8 max-w-md text-center shadow-sm">
          <AlertCircle className="w-10 h-10 text-slate-300 mx-auto mb-3" />
          <h1 className="text-lg font-bold text-slate-900 mb-1">Analysis Not Available</h1>
          <p className="text-sm text-slate-500">{error ?? "This shared analysis could not be found."}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50">
      {/* View toggle */}
      <div className="sticky top-0 z-20 bg-white border-b border-slate-200">
        <div className="max-w-5xl mx-auto px-4 py-2 flex items-center gap-2">
          <div className="flex items-center gap-1 bg-slate-100 rounded-lg p-1">
            <button onClick={() => setView("artifact")} className={`px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${view === "artifact" ? "bg-white text-slate-900 shadow-sm" : "text-slate-500"}`}>
              Live Artifact
            </button>
            <button onClick={() => setView("report")} className={`px-3 py-1.5 rounded-md text-xs font-semibold transition-colors ${view === "report" ? "bg-white text-slate-900 shadow-sm" : "text-slate-500"}`}>
              Written Report
            </button>
          </div>
          <span className="ml-auto text-[10px] text-slate-400">Shared analysis · Read only</span>
        </div>
      </div>

      {/* Content */}
      <div className="max-w-5xl mx-auto">
        {view === "artifact" ? (
          <div className="bg-white border-x border-slate-200 min-h-screen">
            <AnalysisArtifact analysis={analysis} />
          </div>
        ) : (
          <div className="bg-white border-x border-slate-200 min-h-screen">
            <NarrativeReport analysis={analysis} />
          </div>
        )}
      </div>
    </div>
  );
}
