"use client";
import React from "react";
import {
  Building2,
  Calendar,
  Hash,
  Layers,
  Mail,
  MapPin,
  Phone,
  Tag,
  User as UserIcon,
} from "lucide-react";

import type {
  NcSource,
  PreviousNcDetailNc,
} from "@/lib/api/types/previous-nc.types";
import { formatDate } from "../../design-tokens";
import {
  Card,
  Fact,
  Row,
  TabStyles,
  initials,
} from "./shared";

interface Props {
  nc: PreviousNcDetailNc;
  source: NcSource;
}

// The detail endpoint returns extra client contact columns on the `nc`
// object that aren't in the TS type yet (contact_person, mobile,
// client_email, location, company_code, etc). We read them defensively
// with a set of fallback keys so whichever your backend sends shows up.
function pick(obj: any, keys: string[]): string {
  for (const k of keys) {
    const v = obj?.[k];
    if (v !== undefined && v !== null && String(v).trim() !== "") {
      return String(v).trim();
    }
  }
  return "";
}

// Parse "Name - Designation, Name2 - Designation" (the auditee_name format
// the NC uses) plus any structured auditees array, into a clean list.
function resolveAuditees(nc: any): Array<{ name: string; designation: string }> {
  const raw = nc?.auditees_json ?? nc?.auditees;
  let list: any[] = [];
  if (Array.isArray(raw)) list = raw;
  else if (typeof raw === "string" && raw.trim()) {
    try {
      const parsed = JSON.parse(raw);
      if (Array.isArray(parsed)) list = parsed;
    } catch {
      /* fall through */
    }
  }

  const structured = list
    .map((a) => ({
      name: String(a?.name ?? "").trim(),
      designation: String(a?.designation ?? a?.position ?? "").trim(),
    }))
    .filter((a) => a.name);
  if (structured.length) return structured;

  // Legacy "Name - Desig, Name2 - Desig" string.
  const single = String(nc?.auditee_name ?? "").trim();
  if (!single) return [];
  return single
    .split(",")
    .map((chunk) => {
      const [name, ...rest] = chunk.split(" - ");
      return {
        name: (name || "").trim(),
        designation: rest.join(" - ").trim(),
      };
    })
    .filter((a) => a.name);
}

export default function ClientDetailsTab({ nc }: Props) {
  const contact = pick(nc, ["contact_person", "contact_primary", "contact"]);
  const mobile = pick(nc, ["mobile", "phone", "contact_number", "telephone"]);
  const email = pick(nc, ["client_email", "email", "auditee_email"]);
  const location = pick(nc, ["location", "city", "company_city", "address"]);
  const companyCode = pick(nc, ["company_code", "client_code", "company_id"]);
  const standards =
    nc.standard_names && nc.standard_names.length > 0
      ? nc.standard_names.join(", ")
      : "—";
  const auditees = resolveAuditees(nc);
  const dateTime = [
    formatDate(nc.audit_date),
    pick(nc, ["audit_time_label", "audit_time"]),
  ]
    .filter((s) => s && s !== "—")
    .join(" · ");

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

      {/* Key facts */}
      <div className="nt-facts">
        <Fact label="Company" value={nc.company_name || "—"} icon={<Building2 size={12} />} />
        <Fact label="Audit Type" value={nc.audit_type || "—"} icon={<Tag size={12} />} />
        <Fact label="Audit Date" value={formatDate(nc.audit_date)} icon={<Calendar size={12} />} />
        <Fact label="Source DB" value={nc.source} icon={<Layers size={12} />} />
      </div>

      {/* Two-column: Client + Audit scope */}
      <div className="nt-grid-2">
        <Card title="Client" accent="#0f766e">
          <Row label="Company" value={nc.company_name || "—"} strong icon={<Building2 size={13} />} />
          <Row label="Company code" value={companyCode || "—"} mono icon={<Hash size={13} />} />
          <Row label="Contact person" value={contact || "—"} icon={<UserIcon size={13} />} />
          <Row label="Phone" value={mobile || "—"} icon={<Phone size={13} />} />
          <Row label="Email" value={email || "—"} icon={<Mail size={13} />} />
          <Row label="Location" value={location || "—"} icon={<MapPin size={13} />} />
        </Card>

        <Card title="Audit Scope" accent="#0891b2">
          <Row label="Standards" value={standards} icon={<Tag size={13} />} />
          <Row label="Audit type" value={nc.audit_type || "—"} />
          <Row label="Date & time" value={dateTime || formatDate(nc.audit_date)} icon={<Calendar size={13} />} />
          <Row label="Auditee" value={nc.auditee_name || "—"} icon={<UserIcon size={13} />} />
          <Row label="Designation" value={nc.designation || "—"} />
        </Card>
      </div>

      {/* Client record — full meta */}
      <Card title="Client Record" accent="#4338ca" full>
        <div className="nt-grid-2">
          <Row label="Client ID" value={nc.client_id != null ? `#${nc.client_id}` : "—"} mono />
          <Row label="Service ID" value={nc.serve_id != null ? `#${nc.serve_id}` : "—"} mono />
          <Row label="Record created" value={formatDate(nc.created_at)} />
          <Row label="Last updated" value={formatDate(nc.updated_at)} />
        </div>
      </Card>

      {/* Auditees / attendees */}
      <Card
        title="Auditees / Attendees"
        accent="#b45309"
        full
        count={auditees.length || undefined}
      >
        {auditees.length === 0 ? (
          <div className="nt-empty" style={{ border: "none", padding: "10px 0" }}>
            No auditees recorded on this NC.
          </div>
        ) : (
          <div className="nt-people">
            {auditees.map((a, i) => (
              <div className="nt-person" key={i}>
                <span className="nt-person-idx">{String(i + 1).padStart(2, "0")}</span>
                <span className="nt-person-avatar">{initials(a.name)}</span>
                <span className="nt-person-main">
                  <span className="nt-person-name">{a.name}</span>
                  <span className="nt-person-sub">
                    {a.designation || "Designation not specified"}
                  </span>
                </span>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}
