import type {
  AuditSchedule,
  AuditScheduleRow,
  ScheduleStatus,
  RowStatus,
  AuditType,
  AuditMode,
} from "@/lib/api/types/audit-schedule.types";

// ─────────────────────────────────────────────────────────────────────────────
// mapScheduleToRow — Raw AuditSchedule → AuditScheduleRow (flat table shape)
// ─────────────────────────────────────────────────────────────────────────────
export function mapScheduleToRow(
  schedule: AuditSchedule,
  index: number,
): AuditScheduleRow {
  return {
    sno: index + 1,
    id: schedule.id,
    schedule_date: schedule.schedule_date,
    title: schedule.title,
    client_group: schedule.client_group,
    status: schedule.status,
    coordinator_name: schedule.coordinator
      ? `${schedule.coordinator.firstName} ${schedule.coordinator.lastName}`
      : "—",
    coordinator_email: schedule.coordinator?.email ?? "—",
    row_count: schedule.row_count ?? schedule.rows?.length ?? 0,
    source_email: schedule.source_email ?? "—",
    notes: schedule.notes ?? "—",
    created_at: schedule.created_at,
    rows: schedule.rows ?? [],
  };
}

export function mapAuditSchedulesApiResponse(
  schedules: AuditSchedule[],
): AuditScheduleRow[] {
  return schedules.map((s, i) => mapScheduleToRow(s, i));
}

// ─────────────────────────────────────────────────────────────────────────────
// Status + type visual badge meta
// ─────────────────────────────────────────────────────────────────────────────
export const SCHEDULE_STATUS_META: Record<
  ScheduleStatus,
  { label: string; color: string; bg: string }
> = {
  DRAFT: { label: "Draft", color: "#475569", bg: "#f1f5f9" },
  PUBLISHED: { label: "Published", color: "#1e40af", bg: "#dbeafe" },
  IN_PROGRESS: { label: "In Progress", color: "#b45309", bg: "#fef3c7" },
  COMPLETED: { label: "Completed", color: "#166534", bg: "#dcfce7" },
  CANCELLED: { label: "Cancelled", color: "#991b1b", bg: "#fef2f2" },
};

export const ROW_STATUS_META: Record<
  RowStatus,
  { label: string; color: string; bg: string }
> = {
  PENDING: { label: "Pending", color: "#92400e", bg: "#fef3c7" },
  CONFIRMED: { label: "Scheduled", color: "#166534", bg: "#dcfce7" },
  IN_PROGRESS: { label: "In Progress", color: "#6d28d9", bg: "#ede9fe" },
  COMPLETED: { label: "Completed", color: "#166534", bg: "#dcfce7" },
  CANCELLED: { label: "Cancelled", color: "#991b1b", bg: "#fef2f2" },
  RESCHEDULED: { label: "Rescheduled", color: "#0e7490", bg: "#cffafe" },
};

export const AUDIT_TYPE_META: Record<
  AuditType,
  { label: string; color: string; bg: string }
> = {
  INITIAL: { label: "Initial", color: "#15803d", bg: "#dcfce7" },
  SURVEILLANCE: { label: "Surveillance", color: "#b45309", bg: "#fef3c7" },
  RECERTIFICATION: { label: "Recertification", color: "#6d28d9", bg: "#ede9fe" },
  TRANSFER: { label: "Transfer", color: "#0e7490", bg: "#cffafe" },
  FOLLOW_UP: { label: "Follow-up", color: "#7c2d12", bg: "#fed7aa" },
};

export const AUDIT_MODE_META: Record<
  AuditMode,
  { label: string; color: string; bg: string; icon: string }
> = {
  ONSITE: { label: "On-site", color: "#15803d", bg: "#dcfce7", icon: "🏢" },
  OFFICE: { label: "Office", color: "#0e7490", bg: "#cffafe", icon: "🏛️" },
  ONLINE: { label: "Online", color: "#6d28d9", bg: "#ede9fe", icon: "💻" },
  REMOTE: { label: "Remote", color: "#1e40af", bg: "#dbeafe", icon: "💻" },
  HYBRID: { label: "Hybrid", color: "#6d28d9", bg: "#ede9fe", icon: "🔀" },
};

// ─────────────────────────────────────────────────────────────────────────────
// Date formatter (matches your existing pattern)
// ─────────────────────────────────────────────────────────────────────────────
// 🛠 FIX: date-only fields like schedule_date / original_audit_date are DB
// "date" columns — plain calendar days with no time component. Passing them
// straight to `new Date(s)` parses them as UTC midnight (ISO-8601 spec),
// which then gets rendered in whatever timezone the browser is in — for
// anyone west of UTC that silently rolls the day back by one. This detects
// a bare "YYYY-MM-DD" string and builds the Date from local components
// instead, so the calendar day never shifts regardless of viewer timezone.
function parseDateOnlyLocal(s: string): Date {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
  if (m) {
    return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
  }
  return new Date(s);
}

export function formatDate(s?: string | null): string {
  if (!s) return "—";
  try {
    return parseDateOnlyLocal(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 "—";
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Export formatter for Excel/CSV
// ─────────────────────────────────────────────────────────────────────────────
export function formatScheduleForExport(
  row: AuditScheduleRow,
): Record<string, string | number> {
  return {
    "No.": row.sno,
    "Schedule Date": formatDate(row.schedule_date),
    Title: row.title,
    "Client Group": row.client_group,
    Status: SCHEDULE_STATUS_META[row.status]?.label ?? row.status,
    Coordinator: row.coordinator_name,
    "Coordinator Email": row.coordinator_email,
    "Row Count": row.row_count,
    Notes: row.notes,
  };
}
