import React, { useState } from "react";
import { __ } from "@wordpress/i18n";
import Modal from "@libs/modal";
import { formatDateForSite } from "@/libs/dateTime";
import { AlertTriangle } from "lucide-react";

/**
 * Cancel Subscription Modal
 *
 * Provides admin with options for cancelling a subscription:
 * - Cancel immediately
 * - Cancel at end of billing period (sets _waiting_cancellation meta)
 * - Optional reason input
 *
 * @param {boolean} isOpen - Controls modal visibility
 * @param {function} onClose - Callback when modal closes
 * @param {function} onConfirm - Callback when cancellation is confirmed
 * @param {object} subscription - Subscription data object
 * @param {boolean} loading - External loading state (optional)
 */
const CancelModal = ({
  isOpen,
  onClose,
  onConfirm,
  subscription,
  loading: externalLoading = false,
}) => {
  const [cancelType, setCancelType] = useState("immediate");
  const [reason, setReason] = useState("");
  const [internalLoading, setInternalLoading] = useState(false);

  const loading = externalLoading || internalLoading;

  const handleConfirm = async () => {
    if (!subscription?.id) {
      return;
    }

    setInternalLoading(true);
    try {
      await onConfirm({
        subscription_id: subscription.id,
        cancel_type: cancelType,
        reason: reason.trim(),
      });
      // Reset form state
      setCancelType("immediate");
      setReason("");
      onClose();
    } catch (error) {
      console.error("Cancel failed:", error);
    } finally {
      setInternalLoading(false);
    }
  };

  const handleClose = () => {
    if (!loading) {
      setCancelType("immediate");
      setReason("");
      onClose();
    }
  };

  const getNextPaymentDate = () => {
    if (subscription?.next_payment_date_display) {
      return subscription.next_payment_date_display;
    }

    if (subscription?.next_payment_date) {
      return formatDateForSite(subscription.next_payment_date);
    }
    return __("the next payment date", "arraysubs");
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose}
      title={__("Cancel Subscription", "arraysubs")}
      size="md"
      closeOnBackdrop={!loading}
      closeOnEsc={!loading}
    >
      <div className="arraysubs-cancel-modal">
        <div className="arraysubs-cancel-modal__warning">
          <AlertTriangle size={20} />
          <p>
            {__(
              "Are you sure you want to cancel this subscription?",
              "arraysubs",
            )}
          </p>
        </div>

        <div className="arraysubs-cancel-modal__options">
          <label
            className={`arraysubs-cancel-modal__option ${
              cancelType === "immediate"
                ? "arraysubs-cancel-modal__option--selected"
                : ""
            }`}
          >
            <input
              type="radio"
              name="cancel_type"
              value="immediate"
              checked={cancelType === "immediate"}
              onChange={(e) => setCancelType(e.target.value)}
              disabled={loading}
            />
            <span>
              <strong>{__("Cancel Immediately", "arraysubs")}</strong>
              <small>
                {__(
                  "Subscription will be cancelled right now. Customer will lose access immediately.",
                  "arraysubs",
                )}
              </small>
            </span>
          </label>

          <label
            className={`arraysubs-cancel-modal__option ${
              cancelType === "end_of_period"
                ? "arraysubs-cancel-modal__option--selected"
                : ""
            }`}
          >
            <input
              type="radio"
              name="cancel_type"
              value="end_of_period"
              checked={cancelType === "end_of_period"}
              onChange={(e) => setCancelType(e.target.value)}
              disabled={loading}
            />
            <span>
              <strong>{__("Cancel at End of Period", "arraysubs")}</strong>
              <small>
                {__("Subscription will remain active until", "arraysubs")}{" "}
                <strong>{getNextPaymentDate()}</strong>.{" "}
                {__("No further payments will be collected.", "arraysubs")}
              </small>
            </span>
          </label>
        </div>

        <div className="arraysubs-cancel-modal__reason">
          <label htmlFor="cancel-reason">
            {__("Reason", "arraysubs")}{" "}
            <span className="arraysubs-cancel-modal__optional">
              ({__("optional", "arraysubs")})
            </span>
          </label>
          <textarea
            id="cancel-reason"
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            placeholder={__("Enter cancellation reason...", "arraysubs")}
            rows={3}
            disabled={loading}
          />
        </div>

        <div className="arraysubs-cancel-modal__actions">
          <button
            type="button"
            className="button"
            onClick={handleClose}
            disabled={loading}
          >
            {__("Keep Subscription", "arraysubs")}
          </button>
          <button
            type="button"
            className="button arraysubs-btn--danger"
            onClick={handleConfirm}
            disabled={loading}
          >
            {loading
              ? __("Cancelling...", "arraysubs")
              : __("Confirm Cancellation", "arraysubs")}
          </button>
        </div>
      </div>
    </Modal>
  );
};

export default CancelModal;
