"use client";

import React, { useEffect, useState } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { rejectAuditRequest } from "@/lib/api/audit-request.api";
import {
  formatDate,
  formatTime,
  CERTIFICATION_TYPE_META,
} from "@/lib/api/mappers/audit-request.mappers";
import type { AuditRequest } from "@/lib/api/types/audit-request.types";

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

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

// Pre-defined reasons + free-text option
const REJECTION_REASON_PRESETS: SelectOption[] = [
  {
    value: "Client contract expired",
    label: "Client contract expired or terminated",
  },
  {
    value: "Auditor unavailable",
    label: "No auditor available for requested date",
  },
  {
    value: "Duplicate request",
    label: "Duplicate — request already submitted",
  },
  {
    value: "Out of scope",
    label: "Out of scope — standards not supported",
  },
  {
    value: "Client not ready",
    label: "Client not ready for audit (gap analysis needed)",
  },
  {
    value: "Documentation missing",
    label: "Required documentation missing",
  },
  { value: "OTHER", label: "Other (specify in notes)" },
];

export default function RejectRequestModal({
  isOpen,
  onClose,
  request,
  onSuccess,
}: Props) {
  const [reasonPreset, setReasonPreset] = useState<string>(
    REJECTION_REASON_PRESETS[0].value,
  );
  const [customNotes, setCustomNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);

  // Reset on close
  useEffect(() => {
    if (!isOpen) {
      setReasonPreset(REJECTION_REASON_PRESETS[0].value);
      setCustomNotes("");
    }
  }, [isOpen]);

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

  // Combine the preset + custom notes into the final rejection_reason
  const buildReason = (): string => {
    const preset = REJECTION_REASON_PRESETS.find(
      (r) => r.value === reasonPreset,
    );
    if (reasonPreset === "OTHER") {
      return customNotes.trim();
    }
    const presetLabel = preset?.label ?? reasonPreset;
    return customNotes.trim()
      ? `${presetLabel}. ${customNotes.trim()}`
      : presetLabel;
  };

  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    const reason = buildReason();
    if (!reason || reason.length < 5) {
      return toast.error(
        reasonPreset === "OTHER"
          ? "Please describe the reason (min 5 characters)"
          : "Reason is required",
      );
    }

    const confirmed = window.confirm(
      `Reject this audit request?\n\n` +
        `Company: ${request.company?.name ?? "—"}\n` +
        `Request #${request.id}\n` +
        `Reason: ${reason}\n\n` +
        `This will:\n` +
        `• Mark the request as REJECTED\n` +
        `• Notify the marketing submitter\n` +
        `• Send a red-themed email with the reason\n\n` +
        `This action cannot be undone. Proceed?`,
    );
    if (!confirmed) return;

    setSubmitting(true);
    try {
      await rejectAuditRequest(request.id, { rejection_reason: reason });
      toast.success(
        "❌ Request rejected. Marketing has been notified.",
        { duration: 4000 },
      );
      onSuccess?.();
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Failed to reject request");
    } finally {
      setSubmitting(false);
    }
  };

  const certLabel =
    CERTIFICATION_TYPE_META[request.certification_type]?.label ??
    request.certification_type;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 640, width: "95%" }}
      >
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>❌ Reject Audit Request</h2>
            <p className={styles.modalSubtitle}>
              Decline request #{request.id} and notify the submitter
            </p>
          </div>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            type="button"
            aria-label="Close"
          >
            ✕
          </button>
        </div>

        {/* Request summary — what we're rejecting */}
        <div
          style={{
            padding: "14px 24px",
            background: "#fef2f2",
            borderBottom: "2px solid #fecaca",
            fontSize: 13,
            color: "#7f1d1d",
          }}
        >
          <div style={{ fontWeight: 700, marginBottom: 6 }}>
            📋 Request Being Rejected
          </div>
          <div style={{ display: "grid", gap: 4 }}>
            <div>
              <strong>Company:</strong> {request.company?.name ?? "—"}
            </div>
            <div>
              <strong>Auditee:</strong> {request.auditee_name}
            </div>
            <div>
              <strong>Proposed:</strong> {formatDate(request.proposed_date)} at{" "}
              {formatTime(request.proposed_time)}
            </div>
            <div>
              <strong>Type:</strong> {certLabel}
            </div>
            <div>
              <strong>Requested by:</strong>{" "}
              {request.requested_by
                ? `${request.requested_by.firstName} ${request.requested_by.lastName}`
                : "—"}
            </div>
          </div>
        </div>

        <form onSubmit={handleSubmit} className={styles.form}>
          <div className={styles.formBody}>
            <div className={styles.sectionHeader}>
              <span className={styles.sectionDot}></span>
              Rejection Reason
            </div>

            <div className={`${styles.formGroup} ${styles.full}`}>
              <label className={`${styles.label} ${styles.labelRequired}`}>
                Reason
              </label>
              <Select<SelectOption>
                classNamePrefix="rselect"
                options={REJECTION_REASON_PRESETS}
                value={
                  REJECTION_REASON_PRESETS.find(
                    (r) => r.value === reasonPreset,
                  ) ?? null
                }
                onChange={(opt) => setReasonPreset(opt?.value ?? "OTHER")}
                isSearchable={false}
              />
            </div>

            <div className={`${styles.formGroup} ${styles.full}`}>
              <label
                className={`${styles.label} ${
                  reasonPreset === "OTHER" ? styles.labelRequired : ""
                }`}
              >
                Additional Notes{" "}
                {reasonPreset === "OTHER" ? "" : "(Optional)"}
              </label>
              <textarea
                className={styles.textarea}
                rows={4}
                value={customNotes}
                onChange={(e) => setCustomNotes(e.target.value)}
                placeholder={
                  reasonPreset === "OTHER"
                    ? "Please describe the reason in detail..."
                    : "Add any additional context for the submitter..."
                }
                maxLength={500}
              />
              <div
                style={{
                  marginTop: 4,
                  fontSize: 11,
                  color: "#9ca3af",
                  textAlign: "right",
                }}
              >
                {customNotes.length}/500
              </div>
            </div>

            {/* Preview of what the submitter will see */}
            <div
              style={{
                padding: "12px 14px",
                background: "#fef2f2",
                border: "1px solid #fecaca",
                borderRadius: 8,
                fontSize: 12,
                color: "#7f1d1d",
              }}
            >
              <div style={{ fontWeight: 700, marginBottom: 6 }}>
                📧 Preview — what marketing will see:
              </div>
              <div style={{ fontStyle: "italic" }}>
                "{buildReason() || "(please select a reason)"}"
              </div>
            </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,#dc2626,#ef4444)",
              }}
            >
              {submitting ? "Rejecting..." : "❌ Reject Request"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
