"use client";

import React from "react";
import {
  LuBuilding2,
  LuClipboardList,
  LuUser,
  LuCalendar,
  LuBellRing,
  LuMegaphone,
  LuX,
  LuRefreshCw,
  LuCircleCheck,
} from "react-icons/lu";
import { formatDate } from "@/lib/api/mappers/audit-schedule.mappers";
import type { AuditRow, MiniUser } from "@/lib/api/types/audit-schedule.types";

type Variant = "cancel" | "reschedule" | "neutral";

interface ThemeConfig {
  bg: string;
  border: string;
  accent: string;
  softText: string;
  pillBg: string;
  pillIconBg: string;
  pillBorder: string;
  pillText: string;
  innerBg: string;
  innerBorder: string;
  label: string;
  Icon: React.ComponentType<{ size?: number }>;
}

interface Props {
  auditRow: AuditRow;
  scheduleDate?: string;
  variant?: Variant;
  statusLabel?: string;
  footerNote?: string;
  /** Coordinator from AuditSchedule — pass from parent */
  coordinator?: MiniUser | null;
  /** Override the stakeholder section label (defaults to "Coordinator") */
  stakeholderLabel?: string;
}

const THEMES: Record<Variant, ThemeConfig> = {
  cancel: {
    bg: "#fef5f5",
    border: "#fecaca",
    accent: "#b91c1c",
    softText: "#7f1d1d",
    pillBg: "#ffffff",
    pillIconBg: "#dc2626",
    pillBorder: "#fecaca",
    pillText: "#dc2626",
    innerBg: "#ffffff",
    innerBorder: "#fee2e2",
    label: "WILL CANCEL",
    Icon: LuX,
  },
  reschedule: {
    bg: "#fffbeb",
    border: "#fde68a",
    accent: "#b45309",
    softText: "#854d0e",
    pillBg: "#ffffff",
    pillIconBg: "#f59e0b",
    pillBorder: "#fde68a",
    pillText: "#b45309",
    innerBg: "#ffffff",
    innerBorder: "#fef3c7",
    label: "RESCHEDULING",
    Icon: LuRefreshCw,
  },
  neutral: {
    bg: "#f0fdf4",
    border: "#bbf7d0",
    accent: "#15803d",
    softText: "#14532d",
    pillBg: "#ffffff",
    pillIconBg: "#16a34a",
    pillBorder: "#bbf7d0",
    pillText: "#16a34a",
    innerBg: "#ffffff",
    innerBorder: "#dcfce7",
    label: "ACTIVE",
    Icon: LuCircleCheck,
  },
};

// Map enum values to human-readable labels
const AUDIT_TYPE_LABEL: Record<string, string> = {
  INITIAL: "Initial",
  SURVEILLANCE: "Surveillance",
  RECERTIFICATION: "Recertification",
  TRANSFER: "Transfer",
  FOLLOW_UP: "Follow-up",
};

function fullName(u?: MiniUser | null): string | null {
  if (!u) return null;
  const name = `${u.firstName ?? ""} ${u.lastName ?? ""}`.trim();
  return name || null;
}

export default function AuditDetailsCard({
  auditRow,
  scheduleDate,
  variant = "neutral",
  statusLabel,
  footerNote,
  coordinator,
  stakeholderLabel = "Coordinator",
}: Props) {
  const t = THEMES[variant];
  const StatusIcon = t.Icon;

  // Real field reads from AuditRow
  const company = auditRow.company?.name ?? null;
  const auditType = AUDIT_TYPE_LABEL[auditRow.audit_type] ?? auditRow.audit_type;
  const auditorName = fullName(auditRow.lead_auditor);
  const coordinatorName = fullName(coordinator);
  const timeLabel = auditRow.audit_time_label;

  return (
    <div
      style={{
        background: t.bg,
        border: `1px solid ${t.border}`,
        borderRadius: 14,
        padding: 20,
        marginBottom: 20,
      }}
    >
      {/* Top: status pill + audit code */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: 22,
          gap: 12,
        }}
      >
        <div
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 10,
            background: t.pillBg,
            color: t.pillText,
            fontWeight: 700,
            fontSize: 11,
            letterSpacing: 0.8,
            padding: "6px 14px 6px 6px",
            borderRadius: 999,
            border: `1px solid ${t.pillBorder}`,
            textTransform: "uppercase",
          }}
        >
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              width: 22,
              height: 22,
              borderRadius: 6,
              background: t.pillIconBg,
              color: "#fff",
            }}
          >
            <StatusIcon size={13} />
          </span>
          <span>{statusLabel ?? t.label}</span>
        </div>
        <div
          style={{
            fontFamily:
              "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
            fontWeight: 700,
            fontSize: 16,
            color: t.accent,
            letterSpacing: 0.6,
            whiteSpace: "nowrap",
          }}
        >
          {auditRow.audit_code}
        </div>
      </div>

      {/* 2x2 fields grid */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          rowGap: 18,
          columnGap: 28,
          marginBottom: 18,
        }}
      >
        <Field
          icon={<LuBuilding2 size={14} />}
          label="CLIENT"
          value={company}
        />
        <Field
          icon={<LuClipboardList size={14} />}
          label="AUDIT TYPE"
          value={auditType}
        />
        <Field
          icon={<LuUser size={14} />}
          label="LEAD AUDITOR"
          value={auditorName}
          fallback="Not assigned"
        />
        <Field
          icon={<LuCalendar size={14} />}
          label="AUDIT DATE"
          value={
            scheduleDate
              ? `${formatDate(scheduleDate)}${timeLabel ? ` · ${timeLabel}` : ""}`
              : null
          }
          fallback="Not scheduled"
        />
      </div>

      {/* Inner sub-card — mirrors the "Services (1)" block in the proposal */}
      <div
        style={{
          background: t.innerBg,
          border: `1px solid ${t.innerBorder}`,
          borderRadius: 10,
          overflow: "hidden",
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            padding: "10px 14px",
            background: t.bg,
            borderBottom: `1px solid ${t.innerBorder}`,
            fontSize: 12,
            fontWeight: 700,
            color: t.softText,
            letterSpacing: 0.4,
          }}
        >
          <LuMegaphone size={14} />
          <span>Notifications & Stakeholders</span>
        </div>

        <div style={{ padding: "12px 14px" }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              gap: 12,
              fontSize: 13,
            }}
          >
            <span style={{ color: "#64748b", fontWeight: 600 }}>
              {stakeholderLabel}
            </span>
            <span
              style={{
                fontWeight: 700,
                color: coordinatorName ? "#0f172a" : "#94a3b8",
                fontStyle: coordinatorName ? "normal" : "italic",
              }}
            >
              {coordinatorName ?? "Not assigned"}
            </span>
          </div>

          {footerNote && (
            <div
              style={{
                marginTop: 10,
                paddingTop: 10,
                borderTop: `1px dashed ${t.innerBorder}`,
                display: "flex",
                alignItems: "flex-start",
                gap: 8,
                fontSize: 12,
                color: t.softText,
                lineHeight: 1.55,
              }}
            >
              <LuBellRing
                size={14}
                style={{ flexShrink: 0, marginTop: 1, color: t.accent }}
              />
              <span>{footerNote}</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({
  icon,
  label,
  value,
  fallback = "—",
}: {
  icon: React.ReactNode;
  label: string;
  value: React.ReactNode;
  fallback?: string;
}) {
  const isEmpty = value === null || value === undefined || value === "";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6, minWidth: 0 }}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 6,
          fontSize: 11,
          fontWeight: 700,
          letterSpacing: 0.8,
          color: "#64748b",
          textTransform: "uppercase",
        }}
      >
        <span style={{ display: "inline-flex", color: "#94a3b8" }}>{icon}</span>
        <span>{label}</span>
      </div>
      <div
        style={{
          fontSize: 14.5,
          fontWeight: isEmpty ? 500 : 700,
          color: isEmpty ? "#94a3b8" : "#0f172a",
          fontStyle: isEmpty ? "italic" : "normal",
          lineHeight: 1.4,
          wordBreak: "break-word",
        }}
      >
        {isEmpty ? fallback : value}
      </div>
    </div>
  );
}