"use client";

import React, { useEffect, useState } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import { FiSave, FiX } from "react-icons/fi";
import { fetchApi } from "@/lib/api/http";
import {
  updateAuditRow,
  AUDIT_SCHEDULES_API_BASE_URL,
} from "@/lib/api/audit-schedule.api";
import type {
  AuditRow,
  AuditMode,
  AuditType,
  RowStatus,
} from "@/lib/api/types/audit-schedule.types";

interface UserOpt {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
}
interface StandardOpt {
  id: number;
  name: string;
}
interface SelectOption {
  value: number | string;
  label: string;
}

interface Props {
  isOpen: boolean;
  onClose: () => void;
  scheduleId: number | null;
  auditRow: AuditRow | null;
  onSuccess?: () => void;
}

// DB ↔ native <input type="time"> conversion (same helpers as the form)
const toTimeInput = (t?: string | null): string =>
  t ? t.slice(0, 5) : "";
const toDbTime = (t: string): string =>
  t ? (t.length === 5 ? `${t}:00` : t) : "09:00:00";

// Build a friendly label like "09.30AM" from an HH:MM:SS DB time
const toTimeLabel = (dbTime: string): string => {
  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;
  return `${String(hour12).padStart(2, "0")}.${String(mm).padStart(
    2,
    "0",
  )}${period}`;
};

// Status options — labels match the new "Scheduled" vocabulary; values
const STATUS_OPTIONS: { value: RowStatus; label: string }[] = [
  { value: "PENDING",     label: "Pending" },
  { value: "CONFIRMED",   label: "Scheduled" },
  { value: "IN_PROGRESS", label: "In Progress" },
  { value: "COMPLETED",   label: "Completed" },
  { value: "CANCELLED",   label: "Cancelled" },
  { value: "RESCHEDULED", label: "Rescheduled" },
];

const AUDIT_TYPES: { value: AuditType; label: string }[] = [
  { value: "INITIAL", label: "Initial Audit" },
  { value: "SURVEILLANCE", label: "Surveillance Audit" },
  { value: "RECERTIFICATION", label: "Recertification" },
  { value: "TRANSFER", label: "Transfer Audit" },
  { value: "FOLLOW_UP", label: "Follow-up Audit" },
];

// ✅ Includes every mode a row could have been created with from an audit
// request (OFFICE / ONLINE) as well as the schedule-native ones, so the
// dropdown can always display the row's stored mode.
const AUDIT_MODES: { value: AuditMode; label: string }[] = [
  { value: "ONSITE", label: "🏢 On-site" },
  { value: "OFFICE", label: "🏛️ Office" },
  { value: "ONLINE", label: "💻 Online" },
  { value: "REMOTE", label: "💻 Remote" },
  { value: "HYBRID", label: "🔀 Hybrid" },
];

export default function AuditRowEditModal({
  isOpen,
  onClose,
  scheduleId,
  auditRow,
  onSuccess,
}: Props) {
  const [status, setStatus] = useState<RowStatus>("CONFIRMED");
  const [auditType, setAuditType] = useState<AuditType>("INITIAL");
  const [auditStage, setAuditStage] = useState("");
  const [auditMode, setAuditMode] = useState<AuditMode>("ONSITE");
  const [accreditation, setAccreditation] = useState("");
  const [leadAuditorId, setLeadAuditorId] = useState<number | null>(null);
  const [coAuditorIds, setCoAuditorIds] = useState<number[]>([]); // 🆕
  const [auditTime, setAuditTime] = useState("09:00:00");
  const [notes, setNotes] = useState("");

  const [users, setUsers] = useState<UserOpt[]>([]);
  const [submitting, setSubmitting] = useState(false);

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

  // Prefill from the row when modal opens
  useEffect(() => {
    if (!isOpen || !auditRow) return;
    setStatus(auditRow.status);
    setAuditType(auditRow.audit_type);
    setAuditStage(auditRow.audit_stage ?? "");
    setAuditMode(auditRow.audit_mode);
    setAccreditation(auditRow.accreditation ?? "");
    setLeadAuditorId(auditRow.lead_auditor_id ?? null);
    // 🆕 Prefill from whichever shape the row came back with.
    setCoAuditorIds(
      (auditRow.co_auditors?.map((u) => u.id) ??
        auditRow.co_auditor_ids ??
        []) as number[],
    );
    setAuditTime(auditRow.audit_time ?? "09:00:00");
    setNotes(auditRow.notes ?? "");
  }, [isOpen, auditRow]);

  if (!isOpen || !auditRow || !scheduleId) return null;

  const handleSave = async () => {
    if (!leadAuditorId) {
      toast.error("Pick a lead auditor");
      return;
    }
    setSubmitting(true);
    try {
      await updateAuditRow(scheduleId, auditRow.id, {
        status,
        audit_type: auditType,
        audit_stage: auditStage.trim() || undefined,
        audit_mode: auditMode,
        accreditation: accreditation.trim() || undefined,
        lead_auditor_id: leadAuditorId,
        co_auditor_ids: coAuditorIds, // 🆕 send [] to clear, matches UpdateAuditRowDto
        audit_time: auditTime,
        audit_time_label: toTimeLabel(auditTime),
        notes: notes.trim() || undefined,
      });
      toast.success("Audit row updated.");
      onSuccess?.();
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Failed to update audit row");
    } finally {
      setSubmitting(false);
    }
  };

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

  // ✅ Audit-mode value for the Select. Falls back to a synthesized option
  // showing the raw stored mode if it isn't one of AUDIT_MODES, so the
  // dropdown never silently blanks to "Select...".
  const auditModeValue =
    AUDIT_MODES.find((o) => o.value === auditMode) ??
    (auditMode ? { value: auditMode, label: String(auditMode) } : null);

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div style={modalStyle} onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={headerStyle}>
          <div style={{ flex: 1 }}>
            <div
              style={{
                fontSize: 16,
                fontWeight: 700,
                color: "#fff",
                marginBottom: 4,
              }}
            >
              ✏️ Edit Audit Row
            </div>
            <div
              style={{
                fontSize: 12,
                color: "rgba(255,255,255,0.85)",
                fontFamily: "'IBM Plex Mono', monospace",
              }}
            >
              {auditRow.audit_code} · {auditRow.company?.name ?? "—"}
            </div>
          </div>
          <button
            onClick={onClose}
            style={closeBtnStyle}
            type="button"
            aria-label="Close"
          >
            <FiX size={18} />
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: "20px 22px" }}>
          {/* Current status pill */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              marginBottom: 18,
              fontSize: 12,
              color: "#64748b",
            }}
          >
            <span>Current status:</span>
            <span
              style={{
                display: "inline-block",
                padding: "3px 10px",
                borderRadius: 12,
                fontSize: 11,
                fontWeight: 700,
                backgroundColor: STATUS_META[auditRow.status]?.bg ?? "#f1f5f9",
                color: STATUS_META[auditRow.status]?.color ?? "#475569",
              }}
            >
              {STATUS_META[auditRow.status]?.label ?? auditRow.status}
            </span>
          </div>

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 14,
            }}
          >
            {/* Status (new value) */}
            <div>
              <label style={fieldLabel}>Status</label>
              <Select<SelectOption>
                classNamePrefix="rselect"
                options={STATUS_OPTIONS as SelectOption[]}
                value={
                  STATUS_OPTIONS.find((o) => o.value === status) ?? null
                }
                onChange={(opt) =>
                  setStatus((opt?.value as RowStatus) ?? "CONFIRMED")
                }
                isSearchable={false}
              />
            </div>

            {/* Lead Auditor */}
            <div>
              <label style={fieldLabel}>Lead Auditor</label>
              <Select<SelectOption>
                classNamePrefix="rselect"
                options={users.map((u) => ({
                  value: u.id,
                  label: `${u.firstName} ${u.lastName}`,
                }))}
                value={
                  leadAuditorId
                    ? {
                        value: leadAuditorId,
                        label: (() => {
                          const u = users.find((x) => x.id === leadAuditorId);
                          return u
                            ? `${u.firstName} ${u.lastName}`
                            : `User #${leadAuditorId}`;
                        })(),
                      }
                    : null
                }
                onChange={(opt) => {
                  const newLeadId = opt ? Number(opt.value) : null;
                  setLeadAuditorId(newLeadId);
                  // Keep the same person from being lead AND co-auditor at once.
                  setCoAuditorIds((prev) =>
                    prev.filter((id) => id !== newLeadId),
                  );
                }}
                placeholder="Pick auditor..."
              />
            </div>

            {/* Co-Auditor(s) — 🆕 */}
            <div style={{ gridColumn: "1 / -1" }}>
              <label style={fieldLabel}>Co-Auditor(s)</label>
              <Select<SelectOption, true>
                isMulti
                classNamePrefix="rselect"
                options={users
                  .filter((u) => u.id !== leadAuditorId)
                  .map((u) => ({
                    value: u.id,
                    label: `${u.firstName} ${u.lastName}`,
                  }))}
                value={coAuditorIds.map((id) => {
                  const u = users.find((x) => x.id === id);
                  return {
                    value: id,
                    label: u ? `${u.firstName} ${u.lastName}` : `User #${id}`,
                  };
                })}
                onChange={(opts) =>
                  setCoAuditorIds((opts ?? []).map((o) => Number(o.value)))
                }
                placeholder="Add co-auditor(s), if any..."
              />
            </div>

            {/* Audit Time */}
            <div>
              <label style={fieldLabel}>Audit Time</label>
              <input
                type="time"
                style={inputStyle}
                value={toTimeInput(auditTime)}
                onChange={(e) => setAuditTime(toDbTime(e.target.value))}
              />
            </div>

            {/* Audit Mode */}
            <div>
              <label style={fieldLabel}>Audit Mode</label>
              <Select<SelectOption>
                classNamePrefix="rselect"
                options={AUDIT_MODES as SelectOption[]}
                value={auditModeValue}
                onChange={(opt) =>
                  setAuditMode((opt?.value as AuditMode) ?? "ONSITE")
                }
                isSearchable={false}
              />
            </div>

            {/* Audit Type */}
            <div>
              <label style={fieldLabel}>Audit Type</label>
              <Select<SelectOption>
                classNamePrefix="rselect"
                options={AUDIT_TYPES as SelectOption[]}
                value={AUDIT_TYPES.find((o) => o.value === auditType) ?? null}
                onChange={(opt) =>
                  setAuditType((opt?.value as AuditType) ?? "INITIAL")
                }
                isSearchable={false}
              />
            </div>

            {/* Stage */}
            <div>
              <label style={fieldLabel}>Stage</label>
              <input
                type="text"
                style={inputStyle}
                value={auditStage}
                onChange={(e) => setAuditStage(e.target.value)}
                placeholder="e.g., Stage 1"
              />
            </div>

            {/* Accreditation */}
            <div style={{ gridColumn: "1 / -1" }}>
              <label style={fieldLabel}>Accreditation</label>
              <input
                type="text"
                style={inputStyle}
                value={accreditation}
                onChange={(e) => setAccreditation(e.target.value)}
                placeholder="e.g., ASCB"
              />
            </div>

            {/* Notes */}
            <div style={{ gridColumn: "1 / -1" }}>
              <label style={fieldLabel}>Notes</label>
              <textarea
                rows={2}
                style={{ ...inputStyle, resize: "vertical" }}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Optional notes about this audit row"
              />
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={footerStyle}>
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            style={cancelBtnStyle}
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleSave}
            disabled={submitting}
            style={saveBtnStyle}
          >
            <FiSave size={14} />
            {submitting ? "Saving..." : "Save changes"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Inline styles (kept local so this file is drop-in) ────────────────────
const overlayStyle: React.CSSProperties = {
  position: "fixed",
  inset: 0,
  background: "rgba(15, 23, 42, 0.55)",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  zIndex: 1000,
  padding: 16,
};

const modalStyle: React.CSSProperties = {
  background: "#ffffff",
  borderRadius: 12,
  width: "100%",
  maxWidth: 560,
  maxHeight: "90vh",
  overflow: "auto",
  boxShadow: "0 24px 48px rgba(0,0,0,0.25)",
};

const headerStyle: React.CSSProperties = {
  background: "linear-gradient(135deg, #4a0080 0%, #8b14d4 100%)",
  padding: "16px 22px",
  display: "flex",
  alignItems: "flex-start",
  gap: 12,
};

const closeBtnStyle: React.CSSProperties = {
  background: "rgba(255,255,255,0.18)",
  border: "1px solid rgba(255,255,255,0.3)",
  color: "#ffffff",
  width: 32,
  height: 32,
  borderRadius: 6,
  cursor: "pointer",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
};

const footerStyle: React.CSSProperties = {
  padding: "14px 22px",
  borderTop: "1px solid #e2e8f0",
  display: "flex",
  justifyContent: "flex-end",
  gap: 8,
};

const cancelBtnStyle: React.CSSProperties = {
  background: "#ffffff",
  border: "1px solid #cbd5e1",
  color: "#475569",
  padding: "9px 18px",
  borderRadius: 8,
  fontSize: 13,
  fontWeight: 600,
  cursor: "pointer",
};

const saveBtnStyle: React.CSSProperties = {
  background: "linear-gradient(135deg, #4a0080 0%, #8b14d4 100%)",
  border: "none",
  color: "#ffffff",
  padding: "9px 18px",
  borderRadius: 8,
  fontSize: 13,
  fontWeight: 700,
  cursor: "pointer",
  display: "inline-flex",
  alignItems: "center",
  gap: 6,
};

const fieldLabel: React.CSSProperties = {
  display: "block",
  fontSize: 11,
  fontWeight: 700,
  color: "#475569",
  marginBottom: 6,
  textTransform: "uppercase",
  letterSpacing: 0.4,
};

const inputStyle: React.CSSProperties = {
  width: "100%",
  padding: "9px 12px",
  fontSize: 13,
  border: "1px solid #cbd5e1",
  borderRadius: 6,
  background: "#ffffff",
  outline: "none",
  fontFamily: "inherit",
};