"use client";
import React from "react";
import { CheckCircle2, FileText, Lock } from "lucide-react";

import { fetchClosureFileBlob } from "@/lib/api/previous-nc.api";
import type {
  NcSource,
  PreviousNcDetailNc,
  PreviousNcFinalClosure,
} from "@/lib/api/types/previous-nc.types";
import { formatDate } from "../../design-tokens";
import {
  Card,
  EmptyText,
  EvidenceButton,
  Fact,
  FileTypeGlyph,
  TabStyles,
  extractFilename,
  fileExt,
} from "./shared";

interface Props {
  nc: PreviousNcDetailNc;
  finalClosures: PreviousNcFinalClosure[];
  source: NcSource;
}

export default function FinalClosureTab({ nc, finalClosures, source }: Props) {
  const isClosed = (nc.status || "").toLowerCase() === "closed";

  // ── NC still open — final closure not applicable yet ──
  if (!isClosed) {
    return (
      <div className="nt-scope">
        <TabStyles />
        <div className="nt-locked">
          <div className="nt-locked-badge">
            <Lock size={26} strokeWidth={2} />
          </div>
          <h3>NC is still open</h3>
          <p>
            Final closure details aren&apos;t available yet. Once this NC is
            marked <strong style={{ color: "#0f766e" }}>closed</strong>, the
            final closure record and its signed PDF will appear here
            automatically.
          </p>
        </div>
      </div>
    );
  }

  // ── NC closed ──
  return (
    <div className="nt-scope nt-stack">
      <TabStyles />

      <div className="nt-facts">
        <Fact
          label="Status"
          value="Closed"
          icon={<CheckCircle2 size={12} />}
        />
        <Fact label="Closed by" value={nc.assigned_to_name || "—"} />
        <Fact
          label="Closure records"
          value={String(finalClosures.length)}
        />
        <Fact label="Follow-up date" value={formatDate(nc.follow_up_date)} />
      </div>

      <Card
        title="Final Closures"
        accent="#16a34a"
        full
        count={finalClosures.length}
      >
        {finalClosures.length === 0 ? (
          <EmptyText text="This NC is marked closed, but no final closure record has been filed yet." />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 12, paddingTop: 8 }}>
            {finalClosures.map((c) => {
              const pdfName = c.final_closure_pdf
                ? extractFilename(c.final_closure_pdf)
                : "";
              const docName = c.submitted_documents
                ? extractFilename(c.submitted_documents)
                : "";
              return (
                <div key={c.id} className="nt-closure">
                  <div className="nt-closure-grid">
                    <SF label="Closure Date" value={formatDate(c.closure_date)} />
                    <SF label="Auditor" value={c.auditor_name || "—"} />
                    <SF label="NC Type" value={c.nc_type || "—"} />
                    <SF label="Critical Clause" value={c.critical_clause || "—"} />
                    <div>
                      <div className="nt-sf-label">Result</div>
                      <div className="nt-sf-value">
                        {c.result_accepted ? (
                          <span className="nt-result-yes">Accepted</span>
                        ) : c.result_not_accepted ? (
                          <span className="nt-result-no">Not Accepted</span>
                        ) : (
                          "—"
                        )}
                      </div>
                    </div>
                    <SF label="Verified By" value={c.verification_by || "—"} />
                  </div>

                  {c.remarks && (
                    <div
                      style={{
                        marginTop: 12,
                        paddingTop: 12,
                        borderTop: "1px dashed #e2e8f0",
                        fontSize: 12.5,
                        color: "#475569",
                        lineHeight: 1.5,
                      }}
                    >
                      <strong style={{ color: "#0b1220" }}>Remarks: </strong>
                      {c.remarks}
                    </div>
                  )}

                  {/* Attachments: signed closure PDF + submitted documents */}
                  {(c.final_closure_pdf || c.submitted_documents) && (
                    <div className="nt-ev" style={{ flexDirection: "column", alignItems: "stretch" }}>
                      {c.final_closure_pdf && (
                        <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
                          <span className="nt-ev-file">
                            <FileTypeGlyph ext={fileExt(pdfName) || "pdf"} />
                            <span className="nt-ev-name" title={pdfName}>
                              {pdfName || "Final closure PDF"}
                            </span>
                            <span className="nt-ev-ext">PDF</span>
                          </span>
                          <EvidenceButton
                            label="View Final Closure PDF"
                            onLoad={() => fetchClosureFileBlob(source, nc.id, "signed_copy")}
                          />
                        </div>
                      )}
                      {c.submitted_documents && (
                        <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
                          <span className="nt-ev-file">
                            <FileTypeGlyph ext={fileExt(docName)} />
                            <span className="nt-ev-name" title={docName}>
                              {docName || "Submitted documents"}
                            </span>
                            {fileExt(docName) && (
                              <span className="nt-ev-ext">{fileExt(docName).toUpperCase()}</span>
                            )}
                          </span>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </Card>
    </div>
  );
}

function SF({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <div className="nt-sf-label">{label}</div>
      <div className="nt-sf-value">{value}</div>
    </div>
  );
}
