"use client";

import React, { useEffect, useState, useCallback } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { fetchApi } from "@/lib/api/http";
import {
  scheduleAuditRequest,
  AUDIT_REQUESTS_API_BASE_URL,
} from "@/lib/api/audit-request.api";
import {
  formatDate,
  formatTime,
  REQUEST_MODE_META,
  CERTIFICATION_TYPE_META,
} from "@/lib/api/mappers/audit-request.mappers";
import type {
  AuditRequest,
  ScheduleAuditRequestDto,
  ScheduleAuditType,
  ScheduleAuditMode,
} from "@/lib/api/types/audit-request.types";

// "HH:MM". These convert between the two formats.
const toTimeInput = (t: string): string => (t ? t.slice(0, 5) : ""); // "11:00:00" → "11:00"
const toDbTime = (t: string): string =>
  t ? (t.length === 5 ? `${t}:00` : t) : "11:00:00"; // "11:00" → "11:00:00"
type UserOpt = {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
};

interface SelectOption {
  value: number | string;
  label: string;
}

interface Props {
  isOpen: boolean;
  onClose: () => void;
  request: AuditRequest | null;
  onSuccess?: () => void;
}

const TIME_OPTIONS: { label: string; time: string }[] = [
  { label: "09.00AM", time: "09:00:00" },
  { label: "10.00AM", time: "10:00:00" },
  { label: "11.00AM", time: "11:00:00" },
  { label: "12.00PM", time: "12:00:00" },
  { label: "01.00PM", time: "13:00:00" },
  { label: "02.00PM", time: "14:00:00" },
  { label: "03.00PM", time: "15:00:00" },
  { label: "04.00PM", time: "16:00:00" },
];

const AUDIT_TYPE_OPTIONS: { value: ScheduleAuditType; label: string }[] = [
  { value: "INITIAL", label: "Initial Audit" },
  { value: "SURVEILLANCE", label: "Surveillance Audit" },
  { value: "RECERTIFICATION", label: "Recertification" },
];

const AUDIT_MODE_OPTIONS: { value: ScheduleAuditMode; label: string }[] = [
  { value: "ONSITE", label: "🏢 On-site" },
  { value: "OFFICE", label: "🏛️ Office" },
];

const AUDIT_STAGES = [
  "Stage 1",
  "Stage 2",
  "Stage 1 & 2 Combined",
  "Surveillance",
  "Recertification",
];

const CLIENT_GROUP_OPTIONS: SelectOption[] = [
  { value: "QRS", label: "QRS" },
  { value: "IICC", label: "IICC" },
];

// Map marketing's certification_type → coordinator's audit_type (best guess)
function mapCertToAuditType(
  certType: AuditRequest["certification_type"],
): ScheduleAuditType {
  if (certType === "INITIAL") return "INITIAL";
  if (certType === "RECERTIFICATION") return "RECERTIFICATION";
  if (certType === "SURVEILLANCE_RECERT") return "RECERTIFICATION";
  return "SURVEILLANCE";
}

// Map marketing's mode → coordinator's audit_mode
function mapModeToAuditMode(mode: AuditRequest["mode"]): ScheduleAuditMode {
  if (mode === "ONLINE") return "OFFICE"; // online maps to office (remote)
  return "ONSITE";
}

export default function ScheduleRequestModal({
  isOpen,
  onClose,
  request,
  onSuccess,
}: Props) {
  // ── Form state ──────────────────────────────────────────────────────────
  const [leadAuditorId, setLeadAuditorId] = useState<number | null>(null);
  const [coAuditorIds, setCoAuditorIds] = useState<number[]>([]);   // 🆕
  const [auditDate, setAuditDate] = useState("");
  const [timeLabel, setTimeLabel] = useState("11.00AM");
  const [auditTime, setAuditTime] = useState("11:00:00");
  const [auditType, setAuditType] = useState<ScheduleAuditType>("SURVEILLANCE");
  const [auditStage, setAuditStage] = useState("Stage 2");
  const [auditMode, setAuditMode] = useState<ScheduleAuditMode>("ONSITE");
  const [clientGroup, setClientGroup] = useState<"QRS" | "IICC">("QRS");
  const [coordinatorRemarks, setCoordinatorRemarks] = useState("");
  const [notes, setNotes] = useState("");
  const [summaryOpen, setSummaryOpen] = useState(true);
  // ── Lookups ─────────────────────────────────────────────────────────────
  const [users, setUsers] = useState<UserOpt[]>([]);

  // ── UI state ────────────────────────────────────────────────────────────
  const [submitting, setSubmitting] = useState(false);

  // ── Load auditors when modal opens ──────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    fetchApi<{ data: UserOpt[] } | UserOpt[]>(
      `${AUDIT_REQUESTS_API_BASE_URL}/users?limit=200`,
    )
      .then((res: any) => {
        const list = Array.isArray(res) ? res : (res?.data ?? []);
        setUsers(list);
      })
      .catch(() => setUsers([]));
  }, [isOpen]);

  // ── Pre-fill form from the marketing request when it opens ──────────────
  useEffect(() => {
    if (!isOpen || !request) return;
    setAuditDate(request.proposed_date);
    setAuditType(mapCertToAuditType(request.certification_type));
    setAuditMode(mapModeToAuditMode(request.mode));
    // Time pre-fill
    const proposedTime = request.proposed_time;
    setAuditTime(proposedTime || "11:00:00");
    const matched = TIME_OPTIONS.find((t) => t.time === proposedTime);
    if (matched) {
      setTimeLabel(matched.label);
    }
  }, [isOpen, request]);

  // ── Reset on close ──────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) {
      setLeadAuditorId(null);
      setCoAuditorIds([]);   // 🆕
      setAuditDate("");
      setTimeLabel("11.00AM");
      setAuditTime("11:00:00");
      setAuditType("SURVEILLANCE");
      setAuditStage("Stage 2");
      setAuditMode("ONSITE");
      setClientGroup("QRS");
      setCoordinatorRemarks("");
      setNotes("");
    }
  }, [isOpen]);

  if (!isOpen || !request) return null;

  const selectedTime = auditTime || "11:00:00";

  // ── Submit ──────────────────────────────────────────────────────────────
  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!leadAuditorId) return toast.error("Select a lead auditor");
    if (!auditDate) return toast.error("Pick an audit date");

    const confirmed = window.confirm(
      `Schedule this audit?\n\n` +
        `Company: ${request.company?.name ?? request.company_name ?? "—"}\n` +
        `Date: ${auditDate} at ${timeLabel}\n` +
        `Type: ${auditType} (${auditStage})\n` +
        `Mode: ${auditMode}\n\n` +
        `This will:\n` +
        `• Create an audit row in audit-schedules\n` +
        `• Generate a unique audit code\n` +
        `• Notify the marketing submitter\n\n` +
        `Proceed?`,
    );
    if (!confirmed) return;

    setSubmitting(true);
    try {
      const dto: ScheduleAuditRequestDto = {
        lead_auditor_id: leadAuditorId,
        co_auditor_ids: coAuditorIds.length ? coAuditorIds : undefined,   // 🆕
        audit_date: auditDate,
        audit_time: selectedTime,
        audit_time_label: timeLabel,
        audit_type: auditType,
        audit_stage: auditStage || undefined,
        audit_mode: auditMode,
        client_group: clientGroup,
        coordinator_remarks: coordinatorRemarks.trim() || undefined,
        notes: notes.trim() || undefined,
      };
      const result = await scheduleAuditRequest(request.id, dto);
      const auditCode = result.audit_schedule_row?.audit_code ?? "—";
      toast.success(
        `✅ Scheduled. Audit code: ${auditCode}. Notification sent.`,
        { duration: 5000 },
      );
      onSuccess?.();
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Failed to schedule audit");
    } finally {
      setSubmitting(false);
    }
  };

  const certLabel =
    CERTIFICATION_TYPE_META[request.certification_type]?.label ??
    request.certification_type;
  const modeLabel = REQUEST_MODE_META[request.mode]?.label ?? request.mode;
  const companyName = request.company?.name ?? request.company_name ?? "—";

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 900, width: "95%" }}
      >
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>📅 Schedule Audit Request</h2>
            <p className={styles.modalSubtitle}>
              Confirm details from request #{request.id} and create the audit
              row
            </p>
          </div>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            type="button"
            aria-label="Close"
          >
            ✕
          </button>
        </div>

        {/* ── Marketing's original request (collapsible summary) ── */}
        <div style={{ borderBottom: "1px solid #eef0f2" }}>
          {/* Toggle header — always visible, click to collapse/expand */}
          <button
            type="button"
            onClick={() => setSummaryOpen((o) => !o)}
            style={{
              width: "100%",
              display: "flex",
              alignItems: "center",
              gap: 12,
              padding: "12px 24px",
              background: "#fafbfc",
              border: "none",
              borderBottom: summaryOpen ? "1px solid #eef0f2" : "none",
              cursor: "pointer",
              textAlign: "left",
            }}
          >
            <div
              style={{
                width: 30,
                height: 30,
                borderRadius: 8,
                background: "#0f172a",
                color: "#fff",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontSize: 13,
                fontWeight: 700,
                flexShrink: 0,
              }}
            >
              {companyName.trim().charAt(0).toUpperCase() || "?"}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div
                style={{
                  fontSize: 10,
                  fontWeight: 700,
                  letterSpacing: "0.07em",
                  textTransform: "uppercase",
                  color: "#94a3b8",
                }}
              >
                Marketing's submission · #{request.id}
              </div>
              <div
                style={{
                  fontSize: 13,
                  fontWeight: 700,
                  color: "#0f172a",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {companyName}
              </div>
              {request.company_source && (
                <span
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 4,
                    marginTop: 3,
                    fontSize: 10,
                    fontWeight: 600,
                    color: "#475569",
                  }}
                >
                  <span
                    style={{
                      width: 5,
                      height: 5,
                      borderRadius: "50%",
                      background: "#22c55e",
                    }}
                  />
                  {request.company_source} · clients database
                </span>
              )}
            </div>
            <span
              style={{
                fontSize: 12,
                fontWeight: 600,
                color: "#64748b",
                display: "flex",
                alignItems: "center",
                gap: 4,
                flexShrink: 0,
              }}
            >
              {summaryOpen ? "Hide details" : "Show details"}
              <span
                style={{
                  display: "inline-block",
                  transition: "transform 0.2s",
                  transform: summaryOpen ? "rotate(180deg)" : "rotate(0deg)",
                }}
              >
                ▾
              </span>
            </span>
          </button>

          {/* Collapsible body */}
          {summaryOpen && (
            <div style={{ padding: "18px 24px", background: "#ffffff" }}>
              {/* Detail grid */}
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
                  gap: 1,
                  background: "#eef0f2",
                  border: "1px solid #eef0f2",
                  borderRadius: 10,
                  overflow: "hidden",
                }}
              >
                {[
                  { label: "Auditee", value: request.auditee_name },
                  {
                    label: "Proposed date",
                    value: `${formatDate(request.proposed_date)} · ${formatTime(request.proposed_time)}`,
                  },
                  { label: "Mode", value: modeLabel },
                  { label: "Certification", value: certLabel },
                  { label: "Accreditation", value: request.accreditation },
                  { label: "Location", value: request.location },
                ].map((item) => (
                  <div
                    key={item.label}
                    style={{ background: "#fafbfc", padding: "10px 12px" }}
                  >
                    <div
                      style={{
                        fontSize: 10,
                        fontWeight: 600,
                        color: "#94a3b8",
                        textTransform: "uppercase",
                        letterSpacing: "0.05em",
                        marginBottom: 3,
                      }}
                    >
                      {item.label}
                    </div>
                    <div
                      style={{
                        fontSize: 13,
                        color: "#0f172a",
                        fontWeight: 600,
                      }}
                    >
                      {item.value}
                    </div>
                  </div>
                ))}
              </div>

              {request.marketing_remarks && (
                <div
                  style={{
                    marginTop: 12,
                    display: "flex",
                    gap: 8,
                    padding: "10px 12px",
                    background: "#fffbeb",
                    border: "1px solid #fde68a",
                    borderRadius: 8,
                    fontSize: 12,
                    color: "#78350f",
                    lineHeight: 1.6,
                  }}
                >
                  <span style={{ flexShrink: 0 }}>📝</span>
                  <span>
                    <strong>Marketing remarks:</strong>{" "}
                    {request.marketing_remarks}
                  </span>
                </div>
              )}

              {/* What scheduling will do */}
              <div
                style={{
                  marginTop: 12,
                  padding: "12px 14px",
                  background: "#f8fafc",
                  border: "1px solid #e2e8f0",
                  borderRadius: 10,
                }}
              >
                <div
                  style={{
                    fontSize: 10,
                    fontWeight: 700,
                    letterSpacing: "0.06em",
                    textTransform: "uppercase",
                    color: "#64748b",
                    marginBottom: 8,
                  }}
                >
                  What happens on schedule
                </div>
                <div
                  style={{ display: "flex", flexDirection: "column", gap: 6 }}
                >
                  {[
                    "A company record is created in the Client/companies module",
                    "A unique audit code is generated",
                    "An audit row is added to the schedule",
                    "Marketing submitter & assigned auditor are notified",
                  ].map((step, i) => (
                    <div
                      key={i}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 8,
                        fontSize: 12,
                        color: "#334155",
                      }}
                    >
                      <span
                        style={{
                          width: 16,
                          height: 16,
                          borderRadius: "50%",
                          background: "#dcfce7",
                          color: "#16a34a",
                          fontSize: 10,
                          fontWeight: 700,
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          flexShrink: 0,
                        }}
                      >
                        {i + 1}
                      </span>
                      {step}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
        <form onSubmit={handleSubmit} className={styles.form}>
          <div className={styles.formBody}>
            {/* ══ Schedule Details (coordinator confirms/changes) ═════ */}
            <div className={styles.sectionHeader}>
              <span className={styles.sectionDot}></span>
              Confirm Schedule Details
            </div>

            <div className={styles.grid2}>
              <div className={`${styles.formGroup} ${styles.full}`}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Lead Auditor
                </label>
                <Select<SelectOption>
                  classNamePrefix="rselect"
                  options={users.map((u) => ({
                    value: u.id,
                    label: `${u.firstName} ${u.lastName} (${u.email})`,
                  }))}
                  value={
                    leadAuditorId
                      ? {
                          value: leadAuditorId,
                          label: (() => {
                            const u = users.find((x) => x.id === leadAuditorId);
                            return u
                              ? `${u.firstName} ${u.lastName} (${u.email})`
                              : `User #${leadAuditorId}`;
                          })(),
                        }
                      : null
                  }
                  onChange={(opt) => {
                    const leadId = opt ? Number(opt.value) : null;
                    setLeadAuditorId(leadId);
                    if (leadId)
                      setCoAuditorIds((prev) =>
                        prev.filter((id) => id !== leadId),
                      );
                  }}
                  placeholder="Assign auditor..."
                />
              </div>

              {/* 🆕 Additional Auditors (Auditor 2, 3, ...) */}
              <div className={`${styles.formGroup} ${styles.full}`}>
                <label className={styles.label}>Additional Auditors</label>
                <Select<SelectOption, true>
                  classNamePrefix="rselect"
                  isMulti
                  options={users
                    .filter((u) => u.id !== leadAuditorId)
                    .map((u) => ({
                      value: u.id,
                      label: `${u.firstName} ${u.lastName} (${u.email})`,
                    }))}
                  value={coAuditorIds.map((id) => {
                    const u = users.find((x) => x.id === id);
                    return {
                      value: id,
                      label: u
                        ? `${u.firstName} ${u.lastName} (${u.email})`
                        : `User #${id}`,
                    };
                  })}
                  onChange={(opts) =>
                    setCoAuditorIds(
                      opts ? opts.map((o) => Number(o.value)) : [],
                    )
                  }
                  placeholder="Optional — Auditor 2..."
                  closeMenuOnSelect={false}
                />
              </div>

              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Audit Date
                </label>
                <input
                  type="date"
                  className={styles.input}
                  value={auditDate}
                  onChange={(e) => setAuditDate(e.target.value)}
                />
                {auditDate &&
                  auditDate < new Date().toISOString().split("T")[0] && (
                    <div
                      style={{ marginTop: 4, fontSize: 11, color: "#b45309" }}
                    >
                      🕰️ Past date — audit will be recorded retroactively
                    </div>
                  )}
                {auditDate && auditDate !== request.proposed_date && (
                  <div
                    style={{
                      marginTop: 4,
                      fontSize: 11,
                      color: "#b45309",
                    }}
                  >
                    ⚠️ Differs from proposed date (
                    {formatDate(request.proposed_date)})
                  </div>
                )}
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label}>Audit Time</label>
                <input
                  type="time"
                  className={styles.input}
                  value={toTimeInput(auditTime)}
                  onChange={(e) => {
                    const dbTime = toDbTime(e.target.value);
                    setAuditTime(dbTime);
                    // Build a readable label, e.g. "11.30AM"
                    const [hh, mm] = dbTime
                      .split(":")
                      .map((v) => parseInt(v, 10) || 0);
                    const period = hh >= 12 ? "PM" : "AM";
                    const hour12 = hh % 12 === 0 ? 12 : hh % 12;
                    setTimeLabel(
                      `${String(hour12).padStart(2, "0")}.${String(mm).padStart(2, "0")}${period}`,
                    );
                  }}
                />
              </div>

              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Audit Type
                </label>
                <Select<SelectOption>
                  classNamePrefix="rselect"
                  options={AUDIT_TYPE_OPTIONS}
                  value={
                    AUDIT_TYPE_OPTIONS.find((o) => o.value === auditType) ??
                    null
                  }
                  onChange={(opt) =>
                    setAuditType(
                      (opt?.value as ScheduleAuditType) ?? "SURVEILLANCE",
                    )
                  }
                  isSearchable={false}
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label}>Audit Stage</label>
                <Select<SelectOption>
                  classNamePrefix="rselect"
                  options={AUDIT_STAGES.map((s) => ({ value: s, label: s }))}
                  value={{ value: auditStage, label: auditStage }}
                  onChange={(opt) =>
                    setAuditStage((opt?.value as string) ?? "Stage 2")
                  }
                />
              </div>

              <div className={styles.formGroup}>
                <label className={`${styles.label} ${styles.labelRequired}`}>
                  Audit Mode
                </label>
                <Select<SelectOption>
                  classNamePrefix="rselect"
                  options={AUDIT_MODE_OPTIONS}
                  value={
                    AUDIT_MODE_OPTIONS.find((o) => o.value === auditMode) ??
                    null
                  }
                  onChange={(opt) =>
                    setAuditMode((opt?.value as ScheduleAuditMode) ?? "ONSITE")
                  }
                  isSearchable={false}
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label}>Client Group</label>
                <Select<SelectOption>
                  classNamePrefix="rselect"
                  options={CLIENT_GROUP_OPTIONS}
                  value={
                    CLIENT_GROUP_OPTIONS.find((o) => o.value === clientGroup) ??
                    null
                  }
                  onChange={(opt) =>
                    setClientGroup((opt?.value as "QRS" | "IICC") ?? "QRS")
                  }
                  isSearchable={false}
                />
              </div>
            </div>

            {/* ══ Coordinator Remarks ═════════════════════════════════ */}
            <div className={styles.sectionHeader}>
              <span className={styles.sectionDot}></span>
              Coordinator Notes (Optional)
            </div>

            <div className={`${styles.formGroup} ${styles.full}`}>
              <label className={styles.label}>Coordinator Remarks</label>
              <textarea
                className={styles.textarea}
                rows={2}
                value={coordinatorRemarks}
                onChange={(e) => setCoordinatorRemarks(e.target.value)}
                placeholder="Any notes about scheduling decisions, auditor availability, etc."
                maxLength={500}
              />
            </div>

            <div className={`${styles.formGroup} ${styles.full}`}>
              <label className={styles.label}>
                Internal Notes (for audit row)
              </label>
              <textarea
                className={styles.textarea}
                rows={2}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Optional internal notes that will be saved on the audit_schedule_row"
                maxLength={500}
              />
            </div>
          </div>

          {/* ── Footer ──────────────────────────────────────────────── */}
          <div className={styles.modalFooter}>
            <button
              type="button"
              className={styles.cancelBtn}
              onClick={onClose}
              disabled={submitting}
            >
              Cancel
            </button>
            <button
              type="submit"
              className={styles.saveBtn}
              disabled={submitting}
              style={{
                background: "linear-gradient(135deg,#16a34a,#22c55e)",
              }}
            >
              {submitting ? "Scheduling..." : "📅 Schedule & Create Audit Row"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
