import type {
  AuditRequest,
  AuditRequestTableRow,
  AuditRequestStatus,
  AuditMode,
  CertificationType,
  MiniUser,
} from "@/lib/api/types/audit-request.types";

// ─────────────────────────────────────────────────────────────────────────────
// Safe full-name join — firstName + lastName, tolerant of null/missing parts.
// Avoids the "DEVELOPER null" bug when a user record has a null lastName.
// Returns "" when neither part is present (caller decides the fallback).
// ─────────────────────────────────────────────────────────────────────────────
function safeFullName(u?: MiniUser | null): string {
  if (!u) return "";
  const first = (u.firstName ?? "").trim();
  const last = (u.lastName ?? "").trim();
  return `${first} ${last}`.trim();
}

// ─────────────────────────────────────────────────────────────────────────────
// mapRequestToRow — Raw AuditRequest → AuditRequestTableRow (flat table shape)
// ─────────────────────────────────────────────────────────────────────────────
export function mapRequestToRow(
  request: AuditRequest,
  index: number,
): AuditRequestTableRow {
  // ✅ NEW — lead auditor comes from the linked audit_schedule_row (created
  // when the coordinator schedules the request). Until then there is no
  // linked row, so the column shows "N/A".
  const leadAuditor = request.audit_schedule_row?.lead_auditor;
  const leadAuditorName = safeFullName(leadAuditor) || "N/A";

  return {
    sno: index + 1,
    id: request.id,
    status: request.status,
    company_id: request.company_id,
    company_name: request.company?.name ?? request.company_name ?? "—",
    auditee_name: request.auditee_name,
    auditee_email: request.auditee_email,
    certification_type: request.certification_type,
    proposed_date: request.proposed_date,
    proposed_time: request.proposed_time,
    location: request.location,
    mode: request.mode,
    requested_by_name: request.requested_by
      ? `${request.requested_by.firstName} ${request.requested_by.lastName}`
      : "—",
    requested_by_email: request.requested_by?.email ?? "—",
    reviewed_by_name: request.reviewed_by
      ? `${request.reviewed_by.firstName} ${request.reviewed_by.lastName}`
      : "—",
    audit_code: request.audit_schedule_row?.audit_code ?? "—",
    audit_schedule_row_id: request.audit_schedule_row_id ?? null,
    // ✅ NEW
    lead_auditor_name: leadAuditorName,
    // 🆕 Proceed to Inquiry — link + carried fields
    inquiry_id: (request as any).inquiry_id ?? null,
    scope_of_work: (request as any).scope_of_work ?? "",
    previous_cert_no: (request as any).previous_cert_no ?? "",
    created_at: request.created_at,
    raw: request,
  };
}

export function mapAuditRequestsApiResponse(
  requests: AuditRequest[],
): AuditRequestTableRow[] {
  return requests.map((r, i) => mapRequestToRow(r, i));
}

// ─────────────────────────────────────────────────────────────────────────────
// Status + mode + certification visual badge meta
// ─────────────────────────────────────────────────────────────────────────────
export const REQUEST_STATUS_META: Record<
  AuditRequestStatus,
  { label: string; color: string; bg: string; icon: string }
> = {
  DRAFT: { label: "Draft", color: "#475569", bg: "#f1f5f9", icon: "📝" },
  SUBMITTED: {
    label: "Submitted",
    color: "#1e40af",
    bg: "#dbeafe",
    icon: "📤",
  },
  UNDER_REVIEW: {
    label: "Under Review",
    color: "#92400e",
    bg: "#fef3c7",
    icon: "👀",
  },
  SCHEDULED: {
    label: "Scheduled",
    color: "#166534",
    bg: "#dcfce7",
    icon: "✅",
  },
  REJECTED: {
    label: "Rejected",
    color: "#991b1b",
    bg: "#fef2f2",
    icon: "❌",
  },
  CANCELLED: {
    label: "Cancelled",
    color: "#475569",
    bg: "#f1f5f9",
    icon: "🚫",
  },
  COMPLETED: {
    label: "Completed",
    color: "#0e7490",
    bg: "#cffafe",
    icon: "🏁",
  },
};

export const REQUEST_MODE_META: Record<
  AuditMode,
  { label: string; color: string; bg: string; icon: string }
> = {
  ONLINE: { label: "Online", color: "#1e40af", bg: "#dbeafe", icon: "💻" },
  ONSITE: { label: "On-site", color: "#15803d", bg: "#dcfce7", icon: "🏢" },
  HYBRID: { label: "Hybrid", color: "#6d28d9", bg: "#ede9fe", icon: "🔀" },
};

export const CERTIFICATION_TYPE_META: Record<
  CertificationType,
  { label: string; color: string; bg: string }
> = {
  INITIAL: {
    label: "Initial Certification",
    color: "#15803d",
    bg: "#dcfce7",
  },
  SURVEILLANCE: { label: "Surveillance", color: "...", bg: "..." },
  SURVEILLANCE_1: {
    label: "1st Surveillance",
    color: "#b45309",
    bg: "#fef3c7",
  },
  SURVEILLANCE_2: {
    label: "2nd Surveillance",
    color: "#b45309",
    bg: "#fef3c7",
  },
  RECERTIFICATION: {
    label: "Re-Certification",
    color: "#6d28d9",
    bg: "#ede9fe",
  },
  SURVEILLANCE_RECERT: {
    label: "Surveillance & Recert",
    color: "#7c2d12",
    bg: "#fed7aa",
  },
   "Recertification or renewal": {           // 🆕
    label: "Recertification or Renewal",
    color: "#7c3aed",
    bg: "#ede9fe",
  },
};

// ─────────────────────────────────────────────────────────────────────────────
// Date / time formatters
// (Reuses the same patterns as audit-schedule.mappers.ts — kept inline to avoid
//  cross-module import. If you have a shared formatters file, import from there.)
// ─────────────────────────────────────────────────────────────────────────────
export function formatDate(s?: string | null): string {
  if (!s) return "—";
  try {
    return new Date(s)
      .toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      })
      .replace(/ /g, "-");
  } catch {
    return "—";
  }
}

export function formatDateTime(s?: string | null): string {
  if (!s) return "—";
  try {
    const d = new Date(s);
    const date = d
      .toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      })
      .replace(/ /g, "-");
    const time = d.toLocaleTimeString("en-GB", {
      hour: "2-digit",
      minute: "2-digit",
    });
    return `${date} ${time}`;
  } catch {
    return "—";
  }
}

// Format HH:mm:ss → e.g. "11:00 AM"
export function formatTime(s?: string | null): string {
  if (!s) return "—";
  try {
    const [hh, mm] = s.split(":").map((v) => parseInt(v, 10) || 0);
    const period = hh >= 12 ? "PM" : "AM";
    const hour12 = hh % 12 === 0 ? 12 : hh % 12;
    return `${hour12}:${mm.toString().padStart(2, "0")} ${period}`;
  } catch {
    return "—";
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Status helpers — which actions are available for a given status?
// ─────────────────────────────────────────────────────────────────────────────
export function canEditRequest(status: AuditRequestStatus): boolean {
  return ["DRAFT", "SUBMITTED", "UNDER_REVIEW"].includes(status);
}

export function canScheduleRequest(status: AuditRequestStatus): boolean {
  return ["SUBMITTED", "UNDER_REVIEW"].includes(status);
}

export function canRejectRequest(status: AuditRequestStatus): boolean {
  return ["SUBMITTED", "UNDER_REVIEW"].includes(status);
}

export function canCancelRequest(status: AuditRequestStatus): boolean {
  return ["DRAFT", "SUBMITTED", "UNDER_REVIEW"].includes(status);
}

// ─────────────────────────────────────────────────────────────────────────────
// Export formatter for Excel/CSV
// ─────────────────────────────────────────────────────────────────────────────
export function formatRequestForExport(
  row: AuditRequestTableRow,
): Record<string, string | number> {
  return {
    "No.": row.sno,
    "Company": row.company_name,
    "Auditee": row.auditee_name,
    "Auditee Email": row.auditee_email,
    "Certification": CERTIFICATION_TYPE_META[row.certification_type]?.label ?? row.certification_type,
    "Proposed Date": formatDate(row.proposed_date),
    "Proposed Time": formatTime(row.proposed_time),
    "Mode": REQUEST_MODE_META[row.mode]?.label ?? row.mode,
    "Location": row.location,
    "Status": REQUEST_STATUS_META[row.status]?.label ?? row.status,
    "Requested By": row.requested_by_name,
    "Reviewed By": row.reviewed_by_name,
    "Lead Auditor": row.lead_auditor_name,
    "Audit Code": row.audit_code,
    "Submitted": formatDateTime(row.created_at),
  };
}
// 🆕 Proceed to Inquiry is allowed while the request is not rejected/cancelled
// and has not already been linked to an inquiry. Mirrors the backend guards.
export function canProceedRequest(
  status: AuditRequestStatus,
  inquiryId: number | null,
): boolean {
  if (inquiryId) return false;
  return !["REJECTED", "CANCELLED"].includes(status);
}
