"use client";

import React, { useState, useEffect } from "react";
import toast from "react-hot-toast";
import {
  LuBan,
  LuX,
  LuTriangleAlert,
  LuPencilLine,
  LuShieldAlert,
  LuKeyboard,
  LuCheck,
  LuCircleX,
} from "react-icons/lu";
import styles from "../../commonstyle/FormStyles.module.css";
import {
  bulkCancelAuditSchedule,
  getAuditSchedule,
} from "@/lib/api/audit-schedule.api";
import ScheduleSummaryCard from "./../ScheduleSummaryCard";
import type {
  AuditScheduleRow,
  CancellationReason,
  AuditSchedule,
} from "@/lib/api/types/audit-schedule.types";

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

const REASONS: { value: CancellationReason; label: string }[] = [
  { value: "EMERGENCY", label: "Emergency (office closure, urgent event)" },
  { value: "CLIENT_REQUEST", label: "Client requested cancellation" },
  { value: "INTERNAL", label: "Internal reasons" },
  { value: "OTHER", label: "Other (specify in notes)" },
];

export default function BulkCancelModal({
  isOpen,
  onClose,
  schedule,
  onSuccess,
}: Props) {
  const [reason, setReason] = useState<CancellationReason>("EMERGENCY");
  const [notes, setNotes] = useState("");
  const [confirmText, setConfirmText] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [detail, setDetail] = useState<AuditSchedule | null>(null);
  const [loadingDetail, setLoadingDetail] = useState(false);

  useEffect(() => {
    if (!isOpen || !schedule) {
      setDetail(null);
      return;
    }
    setLoadingDetail(true);
    getAuditSchedule(schedule.id)
      .then(setDetail)
      .catch(() => setDetail(null))
      .finally(() => setLoadingDetail(false));
  }, [isOpen, schedule]);

  useEffect(() => {
    if (!isOpen) {
      setReason("EMERGENCY");
      setNotes("");
      setConfirmText("");
    }
  }, [isOpen]);

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

  const activeRows = detail
    ? (detail.rows ?? []).filter(
        (r) => r.status !== "CANCELLED" && r.status !== "COMPLETED",
      )
    : [];
  const displayCount = detail
    ? activeRows.length
    : loadingDetail
      ? null
      : schedule.row_count;

  const expectedConfirm = "CANCEL ALL";
  const confirmMatches = confirmText === expectedConfirm;

  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!confirmMatches) {
      toast.error(`Type "${expectedConfirm}" to confirm`);
      return;
    }
    if (!notes.trim()) {
      toast.error("Please add a brief note");
      return;
    }
    setSubmitting(true);
    try {
      const res = await bulkCancelAuditSchedule(schedule.id, {
        cancellation_reason: reason,
        cancellation_notes: notes.trim(),
      });
      toast.success(
        `${res.cancelled_count} audit(s) cancelled. Notifications sent.`,
      );
      onSuccess?.();
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Bulk cancel failed");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{
          maxWidth: 680,
          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={{
                position: "relative",
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                width: 38,
                height: 38,
                borderRadius: 10,
                background: "rgba(220, 38, 38, 0.15)",
                color: "#fca5a5",
                flexShrink: 0,
              }}
            >
              <LuBan size={20} />
            </div>
            <div>
              <h2
                className={styles.modalTitle}
                style={{
                  fontWeight: 700,
                  letterSpacing: -0.3,
                  margin: 0,
                }}
              >
                Bulk Cancel Schedule
              </h2>
              <p
                className={styles.modalSubtitle}
                style={{ margin: "2px 0 0", fontWeight: 400 }}
              >
                Cancel every active audit in this schedule 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}>
            {/* ══ Schedule summary card ═════════════════════════════ */}
            <ScheduleSummaryCard
              schedule={schedule}
              detail={detail}
              activeCount={displayCount}
              loading={loadingDetail}
            />

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

            <div className={styles.formGroup}>
              <label
                className={`${styles.label} ${styles.labelRequired}`}
                style={{
                  fontWeight: 600,
                  fontSize: 12,
                  letterSpacing: 0.4,
                  textTransform: "uppercase",
                  color: "#475569",
                }}
              >
                Reason
              </label>
              <select
                className={styles.select}
                value={reason}
                onChange={(e) =>
                  setReason(e.target.value as CancellationReason)
                }
                style={{
                  fontFamily: "inherit",
                  fontSize: 14,
                  fontWeight: 500,
                }}
              >
                {REASONS.map((r) => (
                  <option key={r.value} value={r.value}>
                    {r.label}
                  </option>
                ))}
              </select>
            </div>

            <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: "#dc2626" }} />
              Explanation
            </div>

            <div className={styles.formGroup}>
              <label
                className={`${styles.label} ${styles.labelRequired}`}
                style={{
                  fontWeight: 600,
                  fontSize: 12,
                  letterSpacing: 0.4,
                  textTransform: "uppercase",
                  color: "#475569",
                }}
              >
                Briefly explain the cancellation
              </label>
              <textarea
                className={styles.textarea}
                rows={4}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="This will appear in all cancellation notifications sent to stakeholders"
                maxLength={500}
                style={{
                  fontFamily: "inherit",
                  fontSize: 14,
                  lineHeight: 1.5,
                  resize: "vertical",
                }}
              />
              <div
                style={{
                  fontSize: 11,
                  color: notes.length > 450 ? "#dc2626" : "#9ca3af",
                  textAlign: "right",
                  marginTop: 6,
                  fontWeight: 500,
                  fontVariantNumeric: "tabular-nums",
                }}
              >
                {notes.length} / 500
              </div>
            </div>

            {/* ══ Confirmation 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>
              <LuShieldAlert size={15} style={{ color: "#dc2626" }} />
              Final Confirmation
            </div>

            <div
              style={{
                padding: 18,
                background:
                  "linear-gradient(180deg, #fffbeb 0%, #fff7ed 100%)",
                border: "1.5px solid #fed7aa",
                borderRadius: 14,
                boxShadow: "0 1px 2px rgba(0,0,0,0.03)",
              }}
            >
              {/* Warning header */}
              <div
                style={{
                  display: "flex",
                  alignItems: "flex-start",
                  gap: 10,
                  marginBottom: 14,
                  paddingBottom: 14,
                  borderBottom: "1px dashed #fed7aa",
                }}
              >
                <div
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    justifyContent: "center",
                    width: 28,
                    height: 28,
                    borderRadius: 8,
                    background: "#fef3c7",
                    color: "#b45309",
                    flexShrink: 0,
                  }}
                >
                  <LuTriangleAlert size={15} />
                </div>
                <div>
                  <div
                    style={{
                      fontWeight: 700,
                      fontSize: 13,
                      color: "#78350f",
                      letterSpacing: -0.1,
                      marginBottom: 2,
                    }}
                  >
                    This action cannot be undone in bulk
                  </div>
                  <div
                    style={{
                      fontSize: 12,
                      color: "#92400e",
                      lineHeight: 1.5,
                      fontWeight: 400,
                    }}
                  >
                    To reverse, each audit would need to be rescheduled
                    individually.
                  </div>
                </div>
              </div>

              {/* Type-to-confirm */}
              <label
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 6,
                  fontWeight: 600,
                  fontSize: 12,
                  letterSpacing: 0.4,
                  textTransform: "uppercase",
                  color: "#7c2d12",
                  marginBottom: 8,
                }}
              >
                <LuKeyboard size={13} />
                Type to confirm
              </label>

              <div
                style={{
                  fontSize: 13,
                  color: "#7c2d12",
                  marginBottom: 10,
                  fontWeight: 500,
                }}
              >
                Type{" "}
                <code
                  style={{
                    background: "#fff",
                    padding: "3px 10px",
                    borderRadius: 6,
                    border: "1px solid #fed7aa",
                    color: "#9a3412",
                    fontFamily:
                      "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
                    fontWeight: 700,
                    fontSize: 12.5,
                    letterSpacing: 0.5,
                  }}
                >
                  {expectedConfirm}
                </code>{" "}
                in the field below to confirm.
              </div>

              <div style={{ position: "relative" }}>
                <input
                  type="text"
                  className={styles.input}
                  value={confirmText}
                  onChange={(e) =>
                    setConfirmText(e.target.value.toUpperCase())
                  }
                  placeholder={expectedConfirm}
                  style={{
                    fontFamily:
                      "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
                    textTransform: "uppercase",
                    letterSpacing: 1.5,
                    fontSize: 14,
                    fontWeight: 700,
                    paddingRight: 40,
                    background: "#fff",
                    border: `1.5px solid ${
                      confirmText.length === 0
                        ? "#fed7aa"
                        : confirmMatches
                          ? "#16a34a"
                          : "#dc2626"
                    }`,
                    transition: "border 0.15s ease",
                  }}
                />
                {confirmText.length > 0 && (
                  <div
                    style={{
                      position: "absolute",
                      right: 12,
                      top: "50%",
                      transform: "translateY(-50%)",
                      display: "inline-flex",
                      alignItems: "center",
                      justifyContent: "center",
                      width: 22,
                      height: 22,
                      borderRadius: "50%",
                      background: confirmMatches ? "#16a34a" : "#dc2626",
                      color: "#fff",
                    }}
                  >
                    {confirmMatches ? (
                      <LuCheck size={13} strokeWidth={3} />
                    ) : (
                      <LuCircleX size={13} strokeWidth={2.5} />
                    )}
                  </div>
                )}
              </div>

              {confirmText.length > 0 && !confirmMatches && (
                <div
                  style={{
                    marginTop: 8,
                    fontSize: 12,
                    color: "#b91c1c",
                    fontWeight: 500,
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  <LuCircleX size={12} />
                  Text does not match — must be exactly{" "}
                  <strong style={{ fontWeight: 700 }}>
                    {expectedConfirm}
                  </strong>
                </div>
              )}
              {confirmMatches && (
                <div
                  style={{
                    marginTop: 8,
                    fontSize: 12,
                    color: "#15803d",
                    fontWeight: 600,
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  <LuCheck size={12} strokeWidth={3} />
                  Confirmation verified
                </div>
              )}
            </div>
          </div>

          <div className={styles.modalFooter}>
            <button
              type="button"
              className={styles.cancelBtn}
              onClick={onClose}
              disabled={submitting}
              style={{
                fontWeight: 600,
                letterSpacing: -0.1,
              }}
            >
              Keep Schedule
            </button>
            <button
              type="submit"
              className={styles.saveBtn}
              disabled={
                submitting ||
                loadingDetail ||
                !confirmMatches ||
                !notes.trim() ||
                displayCount === 0
              }
              style={{
                background: confirmMatches
                  ? "linear-gradient(135deg, #dc2626 0%, #991b1b 100%)"
                  : "linear-gradient(135deg, #94a3b8 0%, #64748b 100%)",
                boxShadow: confirmMatches
                  ? "0 4px 12px rgba(220, 38, 38, 0.3)"
                  : "none",
                fontWeight: 700,
                letterSpacing: -0.1,
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                transition: "all 0.2s ease",
              }}
            >
              <LuBan size={15} />
              {submitting
                ? "Cancelling..."
                : loadingDetail
                  ? "Loading..."
                  : `Cancel ${displayCount ?? "..."} Audits`}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}