"use client";
import React from "react";
import {
  AlertTriangle,
  Calendar,
  FileText,
  MessageSquare,
  User as UserIcon,
} from "lucide-react";

import { fetchEntryFileBlob } from "@/lib/api/previous-nc.api";
import type {
  NcSource,
  PreviousNcDetailNc,
  PreviousNcEntry,
  PreviousNcRemark,
} from "@/lib/api/types/previous-nc.types";
import { formatDate, ncStatusColor, ncTypeColor } from "../../design-tokens";
import {
  Card,
  Callout,
  EmptyText,
  EvidenceButton,
  Fact,
  FileTypeGlyph,
  Pill,
  TabStyles,
  extractFilename,
  fileExt,
  formatMultiline,
} from "./shared";

interface Props {
  nc: PreviousNcDetailNc;
  entries: PreviousNcEntry[];
  remarks: PreviousNcRemark[];
  source: NcSource;
}

export default function NcDetailsTab({ nc, entries, remarks, source }: Props) {
  const withEvidence = entries.filter((e) => !!e.document_path).length;

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

      {/* Ownership / follow-up facts */}
      <div className="nt-facts">
        <Fact label="NC Type" value={nc.nc_type || "—"} icon={<AlertTriangle size={12} />} />
        <Fact label="Followed up by" value={nc.created_by_name || "—"} icon={<UserIcon size={12} />} />
        <Fact label="Closed by" value={nc.assigned_to_name || "—"} icon={<UserIcon size={12} />} />
        <Fact label="Follow-up date" value={formatDate(nc.follow_up_date)} icon={<Calendar size={12} />} />
      </div>

      {nc.follow_up_notes && (
        <Callout label="Follow-up notes" color="#0891b2" text={nc.follow_up_notes} />
      )}
      {nc.remark && <Callout label="Remark" color="#0f766e" text={nc.remark} />}

      {/* Findings */}
      <Card
        title="Findings"
        accent="#0f766e"
        full
        count={entries.length}
        action={
          withEvidence > 0 ? (
            <span
              style={{
                fontSize: 11,
                fontWeight: 700,
                color: "#0f766e",
                background: "#f0fdfa",
                border: "1px solid #cdeceb",
                padding: "3px 9px",
                borderRadius: 999,
              }}
            >
              {withEvidence} with evidence
            </span>
          ) : undefined
        }
      >
        {entries.length === 0 ? (
          <EmptyText text="No findings recorded for this NC." />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 12, paddingTop: 8 }}>
            {entries.map((e, i) => {
              const filename = e.document_path ? extractFilename(e.document_path) : "";
              const ext = filename ? fileExt(filename) : "";
              return (
                <div key={e.id} className="nt-finding">
                  <div className="nt-finding-head">
                    <span className="nt-finding-num">{i + 1}</span>
                    <Pill color={ncTypeColor(e.nc_type)} label={e.nc_type || "—"} />
                    <Pill color={ncStatusColor(e.status)} label={(e.status || "").toUpperCase()} />
                  </div>

                  <div className="nt-field">
                    <div className="nt-field-label">NCR / OBS Statement</div>
                    <div className="nt-field-body">{formatMultiline(e.ncr_statement)}</div>
                  </div>
                  <div className="nt-field">
                    <div className="nt-field-label">Criteria&apos;s Clause</div>
                    <div className="nt-field-body">{formatMultiline(e.criteria_clause)}</div>
                  </div>
                  <div className="nt-field">
                    <div className="nt-field-label">Proposed Corrective Action</div>
                    <div className="nt-field-body">
                      {e.corrective_action ? (
                        formatMultiline(e.corrective_action)
                      ) : (
                        <span className="nt-muted-italic">Not provided</span>
                      )}
                    </div>
                  </div>

                  {/* Evidence attachment */}
                  {e.document_path && (
                    <div className="nt-ev">
                      <span className="nt-ev-file">
                        <FileTypeGlyph ext={ext} />
                        <span className="nt-ev-name" title={filename}>
                          {filename}
                        </span>
                        {ext && <span className="nt-ev-ext">{ext.toUpperCase()}</span>}
                      </span>
                      <EvidenceButton
                        label="View / Download"
                        onLoad={() => fetchEntryFileBlob(source, nc.id, e.id)}
                      />
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </Card>

      {/* Remarks */}
      <Card title="Internal Remarks" accent="#7c3aed" full count={remarks.length}>
        {remarks.length === 0 ? (
          <EmptyText text="No remarks logged for this NC." />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 10, paddingTop: 8 }}>
            {remarks.map((r) => (
              <div
                key={r.id}
                style={{
                  background: "#faf9ff",
                  border: "1px solid #ece9fb",
                  borderLeft: "3px solid #7c3aed",
                  borderRadius: 10,
                  padding: "11px 14px",
                }}
              >
                <div style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
                  <MessageSquare size={13} style={{ color: "#7c3aed", marginTop: 2, flexShrink: 0 }} />
                  <div style={{ fontSize: 12.5, color: "#1f2937", lineHeight: 1.5 }}>
                    {r.remark}
                  </div>
                </div>
                <div
                  style={{
                    fontSize: 10,
                    color: "#94a3b8",
                    marginTop: 6,
                    fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  }}
                >
                  User #{r.user_id} · {formatDate(r.created_at)}
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}
