"use client";
import React, { useCallback, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import toast from "react-hot-toast";

import {
  ArrowLeft,
  CheckCircle2,
  ClipboardList,
  FileText,
  Lock,
  RotateCw,
  UserSquare2,
  Users,
} from "lucide-react";

import {
  fetchPreviousNcAttendanceBlob,
  fetchPreviousNcPdfBlob,
  getPreviousNc,
} from "@/lib/api/previous-nc.api";
import type {
  NcSource,
  PreviousNcDetailResponse,
} from "@/lib/api/types/previous-nc.types";

import {
  TOKENS,
  formatDate,
  ncStatusColor,
  ncTypeColor,
  sourceColor,
} from "../design-tokens";
import ClientDetailsTab from "./tabs/ClientDetailsTab";
import NcDetailsTab from "./tabs/NcDetailsTab";
import FinalClosureTab from "./tabs/FinalClosureTab";

// ─── Tab config ─────────────────────────────────────────────────────────
type TabKey = "client" | "nc" | "final";

const TABS: { key: TabKey; label: string; icon: React.ReactNode }[] = [
  { key: "client", label: "Client Details", icon: <UserSquare2 size={15} strokeWidth={2.2} /> },
  { key: "nc", label: "NC Details", icon: <ClipboardList size={15} strokeWidth={2.2} /> },
  { key: "final", label: "Final Closure", icon: <CheckCircle2 size={15} strokeWidth={2.2} /> },
];

// ═══════════════════════════════════════════════════════════════════════
// Detail page
// ═══════════════════════════════════════════════════════════════════════

export default function NcDetailPage() {
  const router = useRouter();
  const params = useSearchParams();

  // Sources: "QRS"/"TQS" are legacy-imported NCs, "NEW" is an NC raised
  // natively in this app (see RaiseNcPage.tsx / NcEditPage.tsx). Mirrors the
  // same three-way source handling NcEditPage.tsx already uses.
  const source = (params.get("source") || "QRS").toUpperCase() as NcSource;
  const idStr = params.get("id") || "";
  const id = Number(idStr);

  const [data, setData] = useState<PreviousNcDetailResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [pdfBusy, setPdfBusy] = useState<"report" | "attendance" | null>(null);
  const [activeTab, setActiveTab] = useState<TabKey>("client");

  const fetchData = useCallback(async () => {
    if (
      !id ||
      (source !== "QRS" && source !== "TQS" && (source as string) !== "NEW")
    ) {
      setError("Invalid source or id in URL.");
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const res = await getPreviousNc(source, id);
      setData(res);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load NC details");
    } finally {
      setLoading(false);
    }
  }, [source, id]);

  useEffect(() => {
    fetchData();
    setActiveTab("client");
  }, [fetchData]);

  const openPdf = async (kind: "report" | "attendance") => {
    setPdfBusy(kind);
    try {
      const blobUrl =
        kind === "report"
          ? await fetchPreviousNcPdfBlob(source, id)
          : await fetchPreviousNcAttendanceBlob(source, id);
      const win = window.open(blobUrl, "_blank");
      if (!win) toast.error("Popup blocked — allow popups for this site");
      setTimeout(() => URL.revokeObjectURL(blobUrl), 60_000);
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to open PDF");
    } finally {
      setPdfBusy(null);
    }
  };

  if (loading) return <LoadingShell />;
  if (error)
    return <ErrorShell message={error} onBack={() => router.back()} />;
  if (!data) return null;

  const { nc, entries, remarks, final_closures } = data;
  const isNcClosed = (nc.status || "").toLowerCase() === "closed";

  return (
    <div
      style={{
        background: TOKENS.bg,
        minHeight: "100vh",
        padding: "28px 24px 60px",
        fontFamily:
          "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
        color: TOKENS.ink,
      }}
    >
      {/* Top bar */}
      <div
        style={{
          maxWidth: 1200,
          margin: "0 auto 16px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 12,
          flexWrap: "wrap",
        }}
      >
        <button
          onClick={() => router.back()}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            padding: "9px 16px",
            background: TOKENS.surface,
            border: `1px solid ${TOKENS.line}`,
            borderRadius: TOKENS.rMd,
            cursor: "pointer",
            fontSize: 13,
            fontWeight: 600,
            color: TOKENS.ink3,
            boxShadow: TOKENS.shadow,
            transition: "all 0.15s",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = TOKENS.ink5;
            e.currentTarget.style.color = TOKENS.ink;
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = TOKENS.line;
            e.currentTarget.style.color = TOKENS.ink3;
          }}
        >
          <ArrowLeft size={14} strokeWidth={2.2} />
          Back to list
        </button>

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <PdfButton
            label="View NC PDF"
            color={TOKENS.brand}
            icon={<FileText size={14} strokeWidth={2.2} />}
            busy={pdfBusy === "report"}
            onClick={() => openPdf("report")}
          />
          <PdfButton
            label="View Attendance PDF"
            color={TOKENS.success}
            icon={<Users size={14} strokeWidth={2.2} />}
            busy={pdfBusy === "attendance"}
            onClick={() => openPdf("attendance")}
          />
        </div>
      </div>

      {/* Hero header */}
      <div
        style={{
          maxWidth: 1200,
          margin: "0 auto 18px",
          background:
            "linear-gradient(135deg, #0b1220 0%, #0f172a 50%, #0d544c 100%)",
          padding: "28px 32px",
          borderRadius: TOKENS.rLg,
          color: "#fff",
          position: "relative",
          overflow: "hidden",
          boxShadow: TOKENS.shadow,
        }}
      >
        <div
          style={{
            position: "absolute",
            inset: 0,
            backgroundImage:
              "radial-gradient(circle at 1px 1px, rgba(255,255,255,0.07) 1px, transparent 0)",
            backgroundSize: "24px 24px",
            opacity: 0.6,
          }}
        />
        <div
          style={{
            position: "relative",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
            gap: 24,
            flexWrap: "wrap",
          }}
        >
          <div style={{ flex: "1 1 400px", minWidth: 280 }}>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                marginBottom: 14,
              }}
            >
              <HeroChip
                color={sourceColor(nc.source)}
                label={nc.source}
                bold
              />
              <HeroChip
                color={ncTypeColor(nc.nc_type)}
                label={nc.nc_type || "—"}
              />
              <HeroChip
                color={ncStatusColor(nc.status)}
                label={(nc.status || "").toUpperCase()}
                bold
              />
            </div>

            <h1
              style={{
                margin: 0,
                fontSize: 26,
                fontWeight: 800,
                letterSpacing: "-0.025em",
                lineHeight: 1.2,
              }}
            >
              NC #{nc.id}
              <br />
              <span style={{ color: "#5eead4", fontSize: 18 }}>
                {nc.company_name || "Unknown company"}
              </span>
            </h1>

            <p
              style={{
                margin: "10px 0 0",
                fontSize: 13,
                color: "rgba(255,255,255,0.72)",
                lineHeight: 1.5,
              }}
            >
              {nc.audit_type}
              {nc.audit_date ? ` · ${formatDate(nc.audit_date)}` : ""}
            </p>
          </div>

          <div
            style={{
              display: "grid",
              gap: 8,
              fontSize: 12,
              background: "rgba(255,255,255,0.06)",
              border: "1px solid rgba(255,255,255,0.1)",
              borderRadius: TOKENS.rMd,
              padding: "14px 18px",
              minWidth: 240,
            }}
          >
            <MetaRow label="Source DB" value={nc.source} />
            <MetaRow label="NC ID" value={`#${nc.id}`} />
            <MetaRow label="Audit Date" value={formatDate(nc.audit_date)} />
            <MetaRow label="Created" value={formatDate(nc.created_at)} />
            <MetaRow
              label="Findings"
              value={`${entries.length} entr${entries.length === 1 ? "y" : "ies"}`}
            />
          </div>
        </div>
      </div>

      {/* ── Tabs ── */}
      <div style={{ maxWidth: 1200, margin: "0 auto" }}>
        <div
          role="tablist"
          style={{
            display: "flex",
            gap: 4,
            borderBottom: `1px solid ${TOKENS.line}`,
            marginBottom: 20,
            overflowX: "auto",
          }}
        >
          {TABS.map((t) => {
            const isActive = activeTab === t.key;
            const locked = t.key === "final" && !isNcClosed;
            return (
              <button
                key={t.key}
                role="tab"
                aria-selected={isActive}
                onClick={() => setActiveTab(t.key)}
                style={{
                  position: "relative",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 8,
                  padding: "12px 18px",
                  background: "transparent",
                  border: "none",
                  cursor: "pointer",
                  fontSize: 13.5,
                  fontWeight: 700,
                  whiteSpace: "nowrap",
                  marginBottom: -1,
                  borderBottom: `2.5px solid ${isActive ? TOKENS.brand : "transparent"}`,
                  color: isActive ? TOKENS.brand : TOKENS.ink4,
                  transition: "color 0.15s ease, border-color 0.15s ease",
                }}
                onMouseEnter={(e) => {
                  if (!isActive) e.currentTarget.style.color = TOKENS.ink2;
                }}
                onMouseLeave={(e) => {
                  if (!isActive) e.currentTarget.style.color = TOKENS.ink4;
                }}
              >
                <span style={{ display: "inline-flex", opacity: isActive ? 1 : 0.75 }}>
                  {t.icon}
                </span>
                {t.label}
                {locked && (
                  <Lock size={12} strokeWidth={2.4} style={{ opacity: 0.55 }} />
                )}
              </button>
            );
          })}
        </div>

        <div style={{ animation: "pn-fade 0.22s ease" }}>
          {activeTab === "client" && (
            <ClientDetailsTab nc={nc} source={source} />
          )}
          {activeTab === "nc" && (
            <NcDetailsTab
              nc={nc}
              entries={entries}
              remarks={remarks}
              source={source}
            />
          )}
          {activeTab === "final" && (
            <FinalClosureTab
              nc={nc}
              finalClosures={final_closures}
              source={source}
            />
          )}
        </div>
        <style>{`@keyframes pn-fade{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}`}</style>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Sub-components
// ═══════════════════════════════════════════════════════════════════════

function PdfButton({
  label,
  color,
  icon,
  busy,
  onClick,
}: {
  label: string;
  color: string;
  icon: React.ReactNode;
  busy?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      disabled={busy}
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        padding: "9px 16px",
        background: color,
        color: "#fff",
        border: "none",
        borderRadius: TOKENS.rMd,
        fontSize: 13,
        fontWeight: 700,
        cursor: busy ? "wait" : "pointer",
        boxShadow: `0 4px 12px ${color}40`,
        opacity: busy ? 0.7 : 1,
        transition: "all 0.15s",
      }}
      onMouseEnter={(e) => {
        if (busy) return;
        e.currentTarget.style.transform = "translateY(-1px)";
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.transform = "translateY(0)";
      }}
    >
      {busy ? (
        <RotateCw
          size={14}
          strokeWidth={2.2}
          style={{ animation: "pn-spin 0.8s linear infinite" }}
        />
      ) : (
        icon
      )}
      {busy ? "Loading…" : label}
      <style>{`@keyframes pn-spin{to{transform:rotate(360deg)}}`}</style>
    </button>
  );
}

function HeroChip({
  color,
  label,
  bold,
}: {
  color: string;
  label: string;
  bold?: boolean;
}) {
  return (
    <span
      style={{
        display: "inline-block",
        padding: "3px 10px",
        background: `${color}30`,
        color: "#fff",
        border: `1px solid ${color}80`,
        borderRadius: 999,
        fontSize: 10,
        fontWeight: bold ? 800 : 700,
        textTransform: "uppercase",
        letterSpacing: 0.4,
      }}
    >
      {label}
    </span>
  );
}

function MetaRow({ label, value }: { label: string; value: string }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 16 }}>
      <span style={{ color: "rgba(255,255,255,0.5)", fontWeight: 500 }}>
        {label}
      </span>
      <span
        style={{
          color: "#fff",
          fontWeight: 600,
          fontFamily: "'IBM Plex Mono', monospace",
          fontSize: 11,
        }}
      >
        {value}
      </span>
    </div>
  );
}


function LoadingShell() {
  return (
    <div
      style={{
        minHeight: "60vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: TOKENS.bg,
      }}
    >
      <div style={{ textAlign: "center" }}>
        <div
          style={{
            width: 44,
            height: 44,
            border: `3px solid ${TOKENS.line}`,
            borderTopColor: TOKENS.brand,
            borderRadius: "50%",
            animation: "pn-spin 0.7s linear infinite",
            margin: "0 auto 14px",
          }}
        />
        <div style={{ fontSize: 13, fontWeight: 600, color: TOKENS.ink3 }}>
          Loading NC details
        </div>
        <style>{`@keyframes pn-spin{to{transform:rotate(360deg)}}`}</style>
      </div>
    </div>
  );
}

function ErrorShell({
  message,
  onBack,
}: {
  message: string;
  onBack: () => void;
}) {
  return (
    <div
      style={{
        minHeight: "60vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 40,
      }}
    >
      <div
        style={{
          maxWidth: 400,
          textAlign: "center",
          background: TOKENS.surface,
          padding: 32,
          borderRadius: TOKENS.rLg,
          boxShadow: TOKENS.shadow,
        }}
      >
        <h3 style={{ margin: "0 0 6px", color: TOKENS.danger, fontSize: 16 }}>
          Failed to load NC
        </h3>
        <p style={{ color: TOKENS.ink4, fontSize: 13, margin: "0 0 16px" }}>
          {message}
        </p>
        <button
          onClick={onBack}
          style={{
            padding: "8px 16px",
            background: TOKENS.brand,
            color: "#fff",
            border: "none",
            borderRadius: TOKENS.rMd,
            fontSize: 13,
            fontWeight: 700,
            cursor: "pointer",
          }}
        >
          Go back
        </button>
      </div>
    </div>
  );
}
