"use client";

import React, { useState } from "react";
import toast from "react-hot-toast";
import {
  LuX,
  LuShieldAlert,
  LuUserX,
  LuBuilding,
  LuSiren,
  LuCircleHelp,
  LuPencilLine,
  LuCheck,
  LuTriangleAlert,
} from "react-icons/lu";
import styles from "../../commonstyle/FormStyles.module.css";
import { cancelAuditRow } from "@/lib/api/audit-schedule.api";
import AuditDetailsCard from "./../AuditDetailsCard";
import type {
  AuditRow,
  MiniUser,
  CancellationReason,
} from "@/lib/api/types/audit-schedule.types";

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

const REASONS: {
  value: CancellationReason;
  label: string;
  description: string;
  Icon: React.ComponentType<{ size?: number }>;
}[] = [
  {
    value: "CLIENT_REQUEST",
    label: "Client Request",
    description: "Client asked to cancel the audit",
    Icon: LuBuilding,
  },
  {
    value: "INTERNAL",
    label: "Internal",
    description: "Auditor unavailable or scheduling conflict",
    Icon: LuUserX,
  },
  {
    value: "EMERGENCY",
    label: "Emergency",
    description: "Urgent unforeseen event",
    Icon: LuSiren,
  },
  {
    value: "OTHER",
    label: "Other",
    description: "Specify in notes",
    Icon: LuCircleHelp,
  },
];

export default function CancelRowModal({
  isOpen,
  onClose,
  auditRow,
  scheduleTitle,
  scheduleDate,
  coordinator,
  onSuccess,
}: Props) {
  const [reason, setReason] = useState<CancellationReason>("CLIENT_REQUEST");
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);

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

  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!notes.trim()) {
      toast.error("Please add a brief note explaining the cancellation");
      return;
    }
    setSubmitting(true);
    try {
      await cancelAuditRow(auditRow.id, {
        cancellation_reason: reason,
        cancellation_notes: notes.trim(),
      });
      toast.success("Audit cancelled. Notifications sent to stakeholders.");
      onSuccess?.();
      onClose();
      setReason("CLIENT_REQUEST");
      setNotes("");
    } catch (err: any) {
      toast.error(err?.message || "Failed to cancel audit");
    } finally {
      setSubmitting(false);
    }
  };

  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(220, 38, 38, 0.15)",
                color: "#fca5a5",
                flexShrink: 0,
              }}
            >
              <LuShieldAlert size={20} />
            </div>
            <div>
              <h2
                className={styles.modalTitle}
                style={{
                  fontWeight: 700,
                  letterSpacing: -0.3,
                  margin: 0,
                }}
              >
                Cancel Audit
              </h2>
              <p
                className={styles.modalSubtitle}
                style={{ margin: "2px 0 0", fontWeight: 400 }}
              >
                Cancel a single audit 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={scheduleDate}
              variant="cancel"
              coordinator={coordinator}
              footerNote={
                scheduleTitle
                  ? `Marketing, Auditor & Coordinator will be notified · Schedule: ${scheduleTitle}`
                  : "Marketing, Auditor & Coordinator will be notified via email + in-app."
              }
            />

            {/* 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",
                }}
              >
                Select a reason
              </label>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 10,
                  marginTop: 8,
                }}
              >
                {REASONS.map((r) => {
                  const selected = reason === r.value;
                  const ReasonIcon = r.Icon;
                  return (
                    <label
                      key={r.value}
                      style={{
                        position: "relative",
                        display: "flex",
                        gap: 12,
                        padding: "14px 14px 14px 16px",
                        border: `1.5px solid ${selected ? "#dc2626" : "#e5e7eb"}`,
                        background: selected ? "#fef2f2" : "#fff",
                        borderRadius: 12,
                        cursor: "pointer",
                        transition: "all 0.15s ease",
                        boxShadow: selected
                          ? "0 0 0 4px rgba(220, 38, 38, 0.08)"
                          : "none",
                      }}
                    >
                      <input
                        type="radio"
                        name="reason"
                        value={r.value}
                        checked={selected}
                        onChange={() => setReason(r.value)}
                        style={{
                          position: "absolute",
                          opacity: 0,
                          pointerEvents: "none",
                        }}
                      />
                      <div
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          justifyContent: "center",
                          width: 36,
                          height: 36,
                          borderRadius: 10,
                          background: selected ? "#dc2626" : "#f1f5f9",
                          color: selected ? "#fff" : "#64748b",
                          flexShrink: 0,
                          transition: "all 0.15s ease",
                        }}
                      >
                        <ReasonIcon size={16} />
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div
                          style={{
                            fontWeight: 700,
                            fontSize: 13.5,
                            color: selected ? "#991b1b" : "#0f172a",
                            letterSpacing: -0.1,
                          }}
                        >
                          {r.label}
                        </div>
                        <div
                          style={{
                            fontSize: 12,
                            color: "#64748b",
                            marginTop: 2,
                            lineHeight: 1.45,
                            fontWeight: 400,
                          }}
                        >
                          {r.description}
                        </div>
                      </div>
                      {selected && (
                        <div
                          style={{
                            position: "absolute",
                            top: 8,
                            right: 8,
                            width: 18,
                            height: 18,
                            borderRadius: "50%",
                            background: "#dc2626",
                            color: "#fff",
                            display: "inline-flex",
                            alignItems: "center",
                            justifyContent: "center",
                          }}
                        >
                          <LuCheck size={11} strokeWidth={3} />
                        </div>
                      )}
                    </label>
                  );
                })}
              </div>
            </div>

            {/* Notes 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: "#dc2626" }} />
              Cancellation Notes
            </div>

            <div className={styles.formGroup}>
              <label
                className={`${styles.label} ${styles.labelRequired}`}
                style={{
                  fontWeight: 600,
                  fontSize: 12,
                  letterSpacing: 0.4,
                  textTransform: "uppercase",
                  color: "#475569",
                }}
              >
                Explanation
              </label>
              <textarea
                className={styles.textarea}
                rows={4}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Brief explanation (will be visible in audit trail and notifications)"
                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>
          </div>

          <div className={styles.modalFooter}>
            <button
              type="button"
              className={styles.cancelBtn}
              onClick={onClose}
              disabled={submitting}
              style={{
                fontWeight: 600,
                letterSpacing: -0.1,
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              Keep Audit
            </button>
            <button
              type="submit"
              className={styles.saveBtn}
              disabled={submitting || !notes.trim()}
              style={{
                background:
                  "linear-gradient(135deg, #dc2626 0%, #991b1b 100%)",
                boxShadow: "0 4px 12px rgba(220, 38, 38, 0.25)",
                fontWeight: 700,
                letterSpacing: -0.1,
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              <LuShieldAlert size={15} />
              {submitting ? "Cancelling..." : "Confirm Cancellation"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}