import React, { useState } from "react";
import { __ } from "@wordpress/i18n";
import Modal from "@libs/modal";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
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 [additionalDetails, setAdditionalDetails] = useState("");
  const [internalLoading, setInternalLoading] = useState(false);

  const loading = externalLoading || internalLoading;
  const fallbackReasons = [
    { value: "too_expensive", label: __("Too expensive", "arraysubs") },
    { value: "not_using", label: __("Not using it enough", "arraysubs") },
    {
      value: "found_alternative",
      label: __("Found a better alternative", "arraysubs"),
    },
    {
      value: "missing_features",
      label: __("Missing features I need", "arraysubs"),
    },
    { value: "technical_issues", label: __("Technical issues", "arraysubs") },
    {
      value: "temporary_pause",
      label: __("Just need a temporary break", "arraysubs"),
    },
    { value: "other", label: __("Other", "arraysubs") },
  ];
  const reasonOptions =
    Array.isArray(subscription?.cancellation_reasons) &&
    subscription.cancellation_reasons.length > 0
      ? subscription.cancellation_reasons
      : fallbackReasons;

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

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

  const handleClose = () => {
    if (!loading) {
      setCancelType("immediate");
      setReason("");
      setAdditionalDetails("");
      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>
          <select
            id="cancel-reason"
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            disabled={loading}
          >
            <option value="">{__("Select a reason...", "arraysubs")}</option>
            {reasonOptions.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>

        <div className="arraysubs-cancel-modal__reason">
          <label htmlFor="cancel-additional-details">
            {__("Additional Details", "arraysubs")}{" "}
            <span className="arraysubs-cancel-modal__optional">
              ({__("optional", "arraysubs")})
            </span>
          </label>
          <textarea
            id="cancel-additional-details"
            value={additionalDetails}
            onChange={(e) => setAdditionalDetails(e.target.value)}
            placeholder={__(
              "Add details for the cancellation record...",
              "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>
          <SpinnerButton
            type="button"
            className="button arraysubs-btn--danger"
            onClick={handleConfirm}
            loading={loading}
            loadingText={__("Cancelling…", "arraysubs")}
          >
            {__("Confirm Cancellation", "arraysubs")}
          </SpinnerButton>
        </div>
      </div>
    </Modal>
  );
};

export default CancelModal;
