"use client";

import React, { useEffect, useState } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import {
  LuRefreshCw,
  LuCalendarClock,
  LuClock,
  LuPencilLine,
  LuX,
  LuArrowRight,
  LuCalendar,
  LuUsers,
} from "react-icons/lu";
import styles from "../../commonstyle/FormStyles.module.css";
import { rescheduleAuditRow } from "@/lib/api/audit-schedule.api";
import { fetchApi } from "@/lib/api/http";
import { AUDIT_SCHEDULES_API_BASE_URL } from "@/lib/api/audit-schedule.api";
import AuditDetailsCard from "./../AuditDetailsCard";
import type {
  AuditRow,
  MiniUser,
} from "@/lib/api/types/audit-schedule.types";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  auditRow: AuditRow | null;
  currentScheduleDate?: string;
  coordinator?: MiniUser | null;
  onSuccess?: () => void;
}

// NOTE: kept for reference / fallback — the "New Audit Time" field now uses a
// native clock picker (<input type="time">) instead of this fixed dropdown.
const TIME_LABEL_OPTIONS = [
  { value: "09.00AM", time: "09:00:00" },
  { value: "10.00AM", time: "10:00:00" },
  { value: "11.00AM", time: "11:00:00" },
  { value: "12.00PM", time: "12:00:00" },
  { value: "01.00PM", time: "13:00:00" },
  { value: "02.00PM", time: "14:00:00" },
  { value: "03.00PM", time: "15:00:00" },
  { value: "04.00PM", time: "16:00:00" },
];

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

export default function RescheduleRowModal({
  isOpen,
  onClose,
  auditRow,
  currentScheduleDate,
  coordinator,
  onSuccess,
}: Props) {
  const [newDate, setNewDate] = useState("");
  const [timeLabel, setTimeLabel] = useState("09.00AM");
  const [reason, setReason] = useState("");
  const [submitting, setSubmitting] = useState(false);

  // ✅ NEW — clock picker state. `clockTime` is "HH:MM" for the native input.
  // `useClock` lets the clock drive the time + label (true by default).
  const [useClock, setUseClock] = useState(true);
  const [clockTime, setClockTime] = useState("09:00");

  // 🆕 Reassign lead / co-auditor(s) while rescheduling.
  const [users, setUsers] = useState<UserOpt[]>([]);
  const [leadAuditorId, setLeadAuditorId] = useState<number | null>(null);
  const [coAuditorIds, setCoAuditorIds] = useState<number[]>([]);

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

  // Prefill from the row's current assignment when it opens.
  useEffect(() => {
    if (!isOpen || !auditRow) return;
    setLeadAuditorId(auditRow.lead_auditor_id ?? null);
    setCoAuditorIds(
      (auditRow.co_auditors?.map((u) => u.id) ??
        auditRow.co_auditor_ids ??
        []) as number[],
    );
  }, [isOpen, auditRow]);

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

  // ── Time helpers ────────────────────────────────────────────────────────
  // "09:00" → "09:00:00"
  const toDbTime = (t: string): string =>
    t ? (t.length === 5 ? `${t}:00` : t) : "09:00:00";

  // "14:30" → "02.30PM"  (label format your system uses)
  const toTimeLabel = (t: string): string => {
    if (!t) return "09.00AM";
    const [hhRaw, mm] = t.split(":");
    const hh = parseInt(hhRaw, 10) || 0;
    const period = hh >= 12 ? "PM" : "AM";
    const hour12 = hh % 12 === 0 ? 12 : hh % 12;
    return `${String(hour12).padStart(2, "0")}.${mm}${period}`;
  };

  // ✅ When the clock is active, time + label come from the clock; otherwise
  // they come from the fixed dropdown (kept for reference / fallback).
  const selectedTime = useClock
    ? toDbTime(clockTime)
    : TIME_LABEL_OPTIONS.find((t) => t.value === timeLabel)?.time ?? "09:00:00";

  const effectiveTimeLabel = useClock ? toTimeLabel(clockTime) : timeLabel;

  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!newDate) return toast.error("Please select a new date");
    if (!reason.trim())
      return toast.error("Please provide a reason for the reschedule");
    if (currentScheduleDate && newDate === currentScheduleDate) {
      return toast.error("New date must be different from the current date");
    }

    setSubmitting(true);
    try {
      await rescheduleAuditRow(auditRow.id, {
        new_audit_date: newDate,
        new_audit_time: selectedTime,
        new_audit_time_label: effectiveTimeLabel,
        reschedule_reason: reason.trim(),
        new_lead_auditor_id: leadAuditorId ?? undefined, // 🆕
        new_co_auditor_ids: coAuditorIds, // 🆕
      });
      toast.success("Audit rescheduled. Notifications sent to stakeholders.");
      onSuccess?.();
      onClose();
      setNewDate("");
      setTimeLabel("09.00AM");
      setClockTime("09:00");
      setReason("");
    } catch (err: any) {
      toast.error(err?.message || "Failed to reschedule audit");
    } finally {
      setSubmitting(false);
    }
  };

  const minDate = (() => {
    const d = new Date();
    d.setDate(d.getDate() + 1);
    return d.toISOString().split("T")[0];
  })();

  const rescheduleCount = (auditRow as any).reschedule_count ?? 0;

  // Pretty-print new date when chosen
  const previewNewDate = newDate
    ? new Date(newDate).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    })
    : null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{
          maxWidth: 660,
          width: "95%",
          fontFamily:
            "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
          letterSpacing: -0.01,
        }}
      >
        <div className={styles.modalHeader}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                width: 38,
                height: 38,
                borderRadius: 10,
                background: "rgba(245, 158, 11, 0.18)",
                color: "#fcd34d",
                flexShrink: 0,
              }}
            >
              <LuRefreshCw size={19} />
            </div>
            <div>
              <h2
                className={styles.modalTitle}
                style={{
                  fontWeight: 700,
                  letterSpacing: -0.3,
                  margin: 0,
                }}
              >
                Reschedule Audit
              </h2>
              <p
                className={styles.modalSubtitle}
                style={{ margin: "2px 0 0", fontWeight: 400 }}
              >
                Move the audit to a new date and notify all stakeholders
              </p>
            </div>
          </div>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            type="button"
          >
            <LuX size={18} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className={styles.form}>
          <div className={styles.formBody}>
            {/* Audit info card */}
            <AuditDetailsCard
              auditRow={auditRow}
              scheduleDate={currentScheduleDate}
              variant="reschedule"
              coordinator={coordinator}
              footerNote={
                rescheduleCount > 0
                  ? `Already rescheduled ${rescheduleCount} time(s) · Marketing, Auditor & Coordinator will be notified.`
                  : "Marketing, Auditor & Coordinator will be notified via email + in-app."
              }
            />

            {/* New Schedule section */}
            <div
              className={styles.sectionHeader}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                fontWeight: 700,
                fontSize: 14,
                letterSpacing: -0.1,
              }}
            >
              <span className={styles.sectionDot}></span>
              <LuCalendarClock size={15} style={{ color: "#b45309" }} />
              New Schedule
            </div>

            <div className={styles.grid2}>
              <div className={styles.formGroup}>
                <label
                  className={`${styles.label} ${styles.labelRequired}`}
                  style={{
                    fontWeight: 600,
                    fontSize: 12,
                    letterSpacing: 0.4,
                    textTransform: "uppercase",
                    color: "#475569",
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  <LuCalendar size={13} />
                  New Audit Date
                </label>
                <input
                  type="date"
                  className={styles.input}
                  value={newDate}
                  onChange={(e) => setNewDate(e.target.value)}
                  min={minDate}
                  style={{
                    fontFamily: "inherit",
                    fontSize: 14,
                    fontWeight: 500,
                  }}
                />
              </div>

              <div className={styles.formGroup}>
                <label
                  className={styles.label}
                  style={{
                    fontWeight: 600,
                    fontSize: 12,
                    letterSpacing: 0.4,
                    textTransform: "uppercase",
                    color: "#475569",
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  <LuClock size={13} />
                  New Audit Time
                </label>

                {/* ✅ NEW — native clock picker */}
                <input
                  type="time"
                  className={styles.input}
                  value={clockTime}
                  onChange={(e) => {
                    setClockTime(e.target.value);
                    setUseClock(true);
                  }}
                  style={{
                    fontFamily: "inherit",
                    fontSize: 14,
                    fontWeight: 500,
                  }}
                />

                {/* OLD fixed-time dropdown — kept for reference, no longer used
                <select
                  className={styles.select}
                  value={timeLabel}
                  onChange={(e) => setTimeLabel(e.target.value)}
                  style={{
                    fontFamily: "inherit",
                    fontSize: 14,
                    fontWeight: 500,
                  }}
                >
                  {TIME_LABEL_OPTIONS.map((t) => (
                    <option key={t.value} value={t.value}>
                      {t.value} ({t.time})
                    </option>
                  ))}
                </select>
                */}
              </div>
            </div>

            {/* Date transition preview */}
            {previewNewDate && (
              <div
                style={{
                  marginTop: 4,
                  padding: "12px 16px",
                  background:
                    "linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%)",
                  border: "1px solid #fde68a",
                  borderRadius: 10,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 14,
                  fontSize: 13,
                  fontWeight: 600,
                }}
              >
                <div style={{ textAlign: "center" }}>
                  <div
                    style={{
                      fontSize: 10,
                      color: "#92400e",
                      letterSpacing: 0.6,
                      textTransform: "uppercase",
                      marginBottom: 2,
                    }}
                  >
                    From
                  </div>
                  <div
                    style={{
                      color: "#78350f",
                      fontWeight: 700,
                      fontVariantNumeric: "tabular-nums",
                    }}
                  >
                    {currentScheduleDate
                      ? new Date(currentScheduleDate).toLocaleDateString(
                        "en-GB",
                        {
                          day: "2-digit",
                          month: "short",
                          year: "numeric",
                        },
                      )
                      : "—"}
                  </div>
                </div>
                <LuArrowRight size={18} style={{ color: "#b45309" }} />
                <div style={{ textAlign: "center" }}>
                  <div
                    style={{
                      fontSize: 10,
                      color: "#92400e",
                      letterSpacing: 0.6,
                      textTransform: "uppercase",
                      marginBottom: 2,
                    }}
                  >
                    To
                  </div>
                  <div
                    style={{
                      color: "#78350f",
                      fontWeight: 700,
                      fontVariantNumeric: "tabular-nums",
                    }}
                  >
                    {previewNewDate} · {effectiveTimeLabel}
                  </div>
                </div>
              </div>
            )}

            {/* Reassign Auditor section — 🆕 */}
            <div
              className={styles.sectionHeader}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                fontWeight: 700,
                fontSize: 14,
                letterSpacing: -0.1,
                marginTop: 8,
              }}
            >
              <span className={styles.sectionDot}></span>
              <LuUsers size={15} style={{ color: "#b45309" }} />
              Reassign Auditor (optional)
            </div>

            <div className={styles.grid2}>
              <div className={styles.formGroup}>
                <label
                  className={styles.label}
                  style={{
                    fontWeight: 600,
                    fontSize: 12,
                    letterSpacing: 0.4,
                    textTransform: "uppercase",
                    color: "#475569",
                  }}
                >
                  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);
                    setCoAuditorIds((prev) =>
                      prev.filter((id) => id !== newLeadId),
                    );
                  }}
                  placeholder="Keep current lead auditor..."
                />
              </div>

              <div className={styles.formGroup}>
                <label
                  className={styles.label}
                  style={{
                    fontWeight: 600,
                    fontSize: 12,
                    letterSpacing: 0.4,
                    textTransform: "uppercase",
                    color: "#475569",
                  }}
                >
                  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="Keep current co-auditor(s)..."
                />
              </div>
            </div>
            <p
              style={{
                fontSize: 11,
                color: "#94a3b8",
                margin: "-6px 0 0",
              }}
            >
              Leave as-is to keep the same auditor(s). If you change either
              field, the previous auditor will still see this audit on their
              My Audits list, marked as Rescheduled.
            </p>

            {/* Reason section */}
            <div
              className={styles.sectionHeader}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                fontWeight: 700,
                fontSize: 14,
                letterSpacing: -0.1,
                marginTop: 8,
              }}
            >
              <span className={styles.sectionDot}></span>
              <LuPencilLine size={15} style={{ color: "#b45309" }} />
              Reschedule Reason
            </div>

            <div className={styles.formGroup}>
              <label
                className={`${styles.label} ${styles.labelRequired}`}
                style={{
                  fontWeight: 600,
                  fontSize: 12,
                  letterSpacing: 0.4,
                  textTransform: "uppercase",
                  color: "#475569",
                }}
              >
                Why is this audit being rescheduled?
              </label>
              <textarea
                className={styles.textarea}
                rows={4}
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                placeholder="e.g., 'Auditor unavailable on original date'"
                maxLength={500}
                style={{
                  fontFamily: "inherit",
                  fontSize: 14,
                  lineHeight: 1.5,
                  resize: "vertical",
                }}
              />
              <div
                style={{
                  fontSize: 11,
                  color: reason.length > 450 ? "#dc2626" : "#9ca3af",
                  textAlign: "right",
                  marginTop: 6,
                  fontWeight: 500,
                  fontVariantNumeric: "tabular-nums",
                }}
              >
                {reason.length} / 500
              </div>
            </div>
          </div>

          <div className={styles.modalFooter}>
            <button
              type="button"
              className={styles.cancelBtn}
              onClick={onClose}
              disabled={submitting}
              style={{
                fontWeight: 600,
                letterSpacing: -0.1,
              }}
            >
              Cancel
            </button>
            <button
              type="submit"
              className={styles.saveBtn}
              disabled={submitting || !newDate || !reason.trim()}
              style={{
                background:
                  "linear-gradient(135deg, #f59e0b 0%, #b45309 100%)",
                boxShadow: "0 4px 12px rgba(245, 158, 11, 0.3)",
                fontWeight: 700,
                letterSpacing: -0.1,
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              <LuRefreshCw size={15} />
              {submitting ? "Rescheduling..." : "Confirm Reschedule"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}