"use client";

/**
 * Analysis Artifact Renderer
 * ────────────────────────────
 * Renders a structured Analysis object as a live interactive panel.
 * Uses the reusable section renderer for all content sections.
 */

import { useState } from "react";
import type { Analysis } from "@/lib/services/analysis-schema";
import type { ExtractedAction } from "@/lib/services/analysis-actions";
import { renderSections } from "@/components/analysis/section-renderer";
import { ActionsPanel } from "@/components/analysis/sections/actions-panel";
import { SaveClientPanel } from "@/components/analysis/save-client-panel";
import { X, RefreshCw, Eye, Database, Share2, Check, Link2, CalendarDays, Clock } from "lucide-react";

export function AnalysisArtifact({ analysis, onClose, onRefresh, extractedActions }: {
  analysis: Analysis & { extractedActions?: ExtractedAction[] };
  onClose?: () => void;
  onRefresh?: () => void;
  extractedActions?: ExtractedAction[];
}) {
  const actions = extractedActions ?? (analysis as unknown as { extractedActions?: ExtractedAction[] }).extractedActions ?? [];
  const [showSources, setShowSources] = useState(false);
  const [shareUrl, setShareUrl] = useState<string | null>(null);
  const [shareCopied, setShareCopied] = useState(false);

  async function enableShare() {
    // The analysis id is stored in the analysis object
    const res = await fetch("/api/analysis/share", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ analysisJobId: analysis.id }),
    });
    if (res.ok) {
      const data = await res.json();
      setShareUrl(data.shareUrl);
      navigator.clipboard.writeText(data.shareUrl);
      setShareCopied(true);
      setTimeout(() => setShareCopied(false), 3000);
    }
  }
  return (
    <div className="h-full overflow-y-auto bg-slate-50">
      {/* Header with branding */}
      <div className="sticky top-0 z-10 bg-white border-b border-slate-200 px-5 py-4">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-3">
            {analysis.branding?.clientLogoUrl ? (
              <img src={analysis.branding.clientLogoUrl} alt={analysis.branding.clientName} className="w-8 h-8 rounded-lg object-contain bg-white border border-slate-100 shrink-0 mt-0.5" />
            ) : (
              <div className="w-8 h-8 rounded-lg bg-brand-500 flex items-center justify-center shrink-0 mt-0.5">
                <span className="text-[10px] font-bold text-white">{(analysis.branding?.clientName ?? "?").slice(0, 2).toUpperCase()}</span>
              </div>
            )}
            <div>
              <div className="flex items-center gap-2">
                <p className="text-[10px] font-bold uppercase tracking-widest text-brand-600">{analysis.branding?.appBrand ?? "meSEO"}</p>
                <span className="text-[9px] text-slate-300">·</span>
                <p className="text-[10px] text-slate-400">{analysis.branding?.reportDate}</p>
              </div>
              <h2 className="text-lg font-bold text-slate-900 mt-0.5">{analysis.title}</h2>
              <div className="flex items-center gap-3 mt-1">
                <span className="flex items-center gap-1 text-[11px] text-slate-500">
                  <CalendarDays className="w-3 h-3 text-slate-400" />
                  {analysis.period.start} → {analysis.period.end}
                  <span className="text-slate-300 ml-0.5">({analysis.period.label})</span>
                </span>
                {analysis.comparisonPeriod && (
                  <span className="flex items-center gap-1 text-[10px] text-slate-400">
                    vs {analysis.comparisonPeriod.label}
                  </span>
                )}
                {analysis.completedAt && (
                  <span className="flex items-center gap-1 text-[10px] text-slate-300">
                    <Clock className="w-2.5 h-2.5" />
                    {new Date(analysis.completedAt).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}
                  </span>
                )}
              </div>
            </div>
          </div>
          {onClose && (
            <button onClick={onClose} className="text-slate-400 hover:text-slate-600 p-1">
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
        {/* Sources + actions */}
        <div className="flex items-center justify-between mt-2">
          <div className="flex items-center gap-2 flex-wrap">
            {analysis.sources.map(s => (
              <span key={s.id} className={`text-[10px] font-semibold px-2 py-0.5 rounded-full border ${
                s.status === "available" ? "bg-green-50 text-green-700 border-green-200"
                : s.status === "partial" ? "bg-amber-50 text-amber-700 border-amber-200"
                : "bg-slate-100 text-slate-400 border-slate-200"
              }`}>
                {s.status === "available" ? "●" : s.status === "partial" ? "◐" : "○"} {s.label}
              </span>
            ))}
          </div>
          <div className="flex items-center gap-1">
            {onRefresh && (
              <button onClick={onRefresh} className="flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-semibold text-slate-500 hover:bg-slate-100 transition-colors" title="Refresh analysis">
                <RefreshCw className="w-3 h-3" /> Refresh
              </button>
            )}
            <button onClick={() => setShowSources(!showSources)} className="flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-semibold text-slate-500 hover:bg-slate-100 transition-colors" title="View source data">
              <Database className="w-3 h-3" /> Sources
            </button>
            <button onClick={enableShare} className="flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-semibold text-slate-500 hover:bg-slate-100 transition-colors" title="Share analysis">
              {shareCopied ? <Check className="w-3 h-3 text-green-600" /> : <Share2 className="w-3 h-3" />}
              {shareCopied ? "Copied!" : "Share"}
            </button>
          </div>
        </div>

        {/* Expanded source details */}
        {showSources && (
          <div className="mt-2 bg-slate-50 rounded-lg border border-slate-100 p-3 space-y-1.5">
            {analysis.sources.map(s => (
              <div key={s.id} className="flex items-center justify-between text-[11px]">
                <span className="text-slate-600">{s.label}</span>
                <span className="text-slate-400">
                  {s.status === "available" ? `${s.recordCount ?? 0} records` : s.status === "partial" && (s.recordCount ?? 0) === 0 ? "Connected — awaiting data" : s.status === "partial" ? `${s.recordCount} records (partial)` : s.status === "missing" ? "Not connected" : s.status}
                  {s.dateRange ? ` · ${s.dateRange.start} → ${s.dateRange.end}` : ""}
                </span>
              </div>
            ))}
            {analysis.narrative?.methodology && (
              <p className="text-[10px] text-slate-400 pt-1 border-t border-slate-100 mt-1">{analysis.narrative.methodology}</p>
            )}
          </div>
        )}
      </div>

      {/* Sections */}
      <div className="p-5 space-y-5">
        {/* Executive Summary — premium lead paragraph */}
        <div className="relative bg-gradient-to-br from-brand-50/60 via-white to-white rounded-2xl border border-brand-100 overflow-hidden shadow-sm">
          <div className="absolute top-0 left-0 h-full w-1 bg-gradient-to-b from-brand-500 to-brand-600" />
          <div className="px-6 py-4 pl-7">
            <div className="flex items-center gap-2 mb-2">
              <span className="text-[9px] font-bold uppercase tracking-widest text-brand-600">Executive Summary</span>
              <span className="text-[9px] text-slate-300">·</span>
              <span className="text-[9px] text-slate-400">
                {analysis.sources.filter(s => s.status === "available").length} source{analysis.sources.filter(s => s.status === "available").length !== 1 ? "s" : ""} · {analysis.findings.length} finding{analysis.findings.length !== 1 ? "s" : ""} · {analysis.recommendations.length} rec{analysis.recommendations.length !== 1 ? "s" : ""}
              </span>
            </div>
            <p className="text-[15px] text-slate-800 leading-relaxed font-medium">
              {analysis.narrative?.executiveSummary || analysis.summary}
            </p>
            {analysis.narrative?.executiveSummary && analysis.summary && analysis.narrative.executiveSummary !== analysis.summary && (
              <p className="text-xs text-slate-500 leading-relaxed mt-2 pt-2 border-t border-brand-100/60">
                {analysis.summary}
              </p>
            )}
          </div>
        </div>

        {/* Rendered sections from the section renderer */}
        {renderSections(analysis)}

        {/* Actionable items → Execution Hub */}
        {actions.length > 0 && <ActionsPanel actions={actions} brandId={analysis.brandId} />}

        {/* Save for Client */}
        {onRefresh && <SaveClientPanel analysisJobId={analysis.id} />}
      </div>
    </div>
  );
}
