/**
 * Skip & Pause Status Card Component
 *
 * Displays skip/pause status and provides controls for managing
 * skip renewals and vacation mode on a subscription.
 *
 * @package ArraySubs
 */

import React, { useState, useEffect } from "react";
import { __ } from "@wordpress/i18n";
import { buildUrl } from "@/libs/url";
import { formatDateForSite } from "@/libs/dateTime";
import Modal from "@libs/modal";
import Form, { useForm } from "rc-field-form";
import FormBuilder from "@libs/form-builder";
import { useConfirm } from "@libs/confirm-dialog";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
import {
  CalendarX,
  Play,
  Pause,
  RotateCcw,
  FastForward,
  Loader2,
  AlertCircle,
  CheckCircle,
  Calendar,
} from "lucide-react";

/**
 * Skip/Pause Card Component
 *
 * @param {Object} props
 * @param {number} props.subscriptionId - Subscription ID
 * @param {string} props.subscriptionStatus - Current subscription status
 * @param {Function} props.onUpdate - Callback when data is updated
 * @param {Function} props.showToast - Toast notification function
 */
const SkipPauseCard = ({
  subscriptionId,
  subscriptionStatus,
  onUpdate,
  showToast,
}) => {
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [skipStatus, setSkipStatus] = useState(null);
  const [pauseStatus, setPauseStatus] = useState(null);
  const [skipModalOpen, setSkipModalOpen] = useState(false);
  const [modifySkipModalOpen, setModifySkipModalOpen] = useState(false);
  const [pauseModalOpen, setPauseModalOpen] = useState(false);
  const [skipForm] = useForm();
  const [modifySkipForm] = useForm();
  const [pauseForm] = useForm();
  const { confirm, confirmDialog } = useConfirm();
  const { env } = window.arraySubs;

  useEffect(() => {
    fetchStatus();
  }, [subscriptionId]);

  /**
   * Fetch skip and pause status
   */
  const fetchStatus = async () => {
    setLoading(true);
    try {
      const [skipResponse, pauseResponse] = await Promise.all([
        fetch(
          buildUrl(
            `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/skip`,
          ),
          { headers: { "X-WP-Nonce": env.nonce } },
        ),
        fetch(
          buildUrl(
            `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/pause-status`,
          ),
          { headers: { "X-WP-Nonce": env.nonce } },
        ),
      ]);

      if (skipResponse.ok) {
        const skipData = await skipResponse.json();
        setSkipStatus(skipData.content);
      }

      if (pauseResponse.ok) {
        const pauseData = await pauseResponse.json();
        setPauseStatus(pauseData.content);
      }
    } catch (error) {
      console.error("Error fetching skip/pause status:", error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * Skip renewal cycles
   */
  const handleSkip = async (values) => {
    setActionLoading(true);
    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/skip`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
          body: JSON.stringify({
            cycles: parseInt(values.cycles) || 1,
            reason: values.reason || "",
          }),
        },
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(
          result.message || __("Failed to skip renewal", "arraysubs"),
        );
      }

      showToast(
        result.message || __("Renewal skipped successfully", "arraysubs"),
        "success",
      );
      setSkipModalOpen(false);
      skipForm.resetFields();
      fetchStatus();
      onUpdate?.();
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setActionLoading(false);
    }
  };

  /**
   * Undo skip
   */
  const handleUndoSkip = async () => {
    try {
      await confirm({
        title: __("Undo Skip", "arraysubs"),
        message: __(
          "Are you sure you want to undo the skip? The original renewal date will be restored.",
          "arraysubs",
        ),
        confirmText: __("Undo Skip", "arraysubs"),
        loadingText: __("Undoing…", "arraysubs"),
        variant: "info",
        onConfirm: async () => {
          setActionLoading(true);
          try {
            const response = await fetch(
              `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/skip`,
              {
                method: "DELETE",
                headers: {
                  "Content-Type": "application/json",
                  "X-WP-Nonce": env.nonce,
                },
              },
            );

            const result = await response.json();

            if (!response.ok) {
              throw new Error(
                result.message || __("Failed to undo skip", "arraysubs"),
              );
            }

            showToast(
              result.message || __("Skip undone successfully", "arraysubs"),
              "success",
            );
            fetchStatus();
            onUpdate?.();
          } finally {
            setActionLoading(false);
          }
        },
      });
    } catch (error) {
      showToast(error.message, "error");
    }
  };

  /**
   * Modify skip cycles
   */
  const handleModifySkip = async (values) => {
    setActionLoading(true);
    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/skip`,
        {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
          body: JSON.stringify({
            cycles: parseInt(values.cycles),
          }),
        },
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(
          result.message || __("Failed to modify skip", "arraysubs"),
        );
      }

      showToast(
        result.message || __("Skip modified successfully", "arraysubs"),
        "success",
      );
      setModifySkipModalOpen(false);
      modifySkipForm.resetFields();
      fetchStatus();
      onUpdate?.();
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setActionLoading(false);
    }
  };

  /**
   * Pause subscription
   */
  const handlePause = async (values) => {
    setActionLoading(true);
    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/pause`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
          body: JSON.stringify({
            duration_days: parseInt(values.duration_days) || 0,
            reason: values.reason || "",
          }),
        },
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(
          result.message || __("Failed to pause subscription", "arraysubs"),
        );
      }

      showToast(
        result.message || __("Subscription paused successfully", "arraysubs"),
        "success",
      );
      setPauseModalOpen(false);
      pauseForm.resetFields();
      fetchStatus();
      onUpdate?.();
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setActionLoading(false);
    }
  };

  /**
   * Resume subscription
   */
  const handleResume = async () => {
    try {
      await confirm({
        title: __("Resume Subscription", "arraysubs"),
        message: __(
          "Are you sure you want to resume this subscription?",
          "arraysubs",
        ),
        confirmText: __("Resume Now", "arraysubs"),
        loadingText: __("Resuming…", "arraysubs"),
        variant: "info",
        onConfirm: async () => {
          setActionLoading(true);
          try {
            const response = await fetch(
              `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/resume`,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  "X-WP-Nonce": env.nonce,
                },
              },
            );

            const result = await response.json();

            if (!response.ok) {
              throw new Error(
                result.message ||
                  __("Failed to resume subscription", "arraysubs"),
              );
            }

            showToast(
              result.message ||
                __("Subscription resumed successfully", "arraysubs"),
              "success",
            );
            fetchStatus();
            onUpdate?.();
          } finally {
            setActionLoading(false);
          }
        },
      });
    } catch (error) {
      showToast(error.message, "error");
    }
  };

  /**
   * Format date for display
   */
  const formatDate = (dateString) => {
    if (!dateString) return "-";
    return formatDateForSite(dateString);
  };

  // Check if actions are available based on subscription status
  const canSkipOrPause =
    subscriptionStatus === "arraysubs-active" ||
    subscriptionStatus === "arraysubs-trial";

  const isPaused = subscriptionStatus === "arraysubs-on-hold";

  const getPauseIdleMessage = () => {
    const statusMessages = {
      "arraysubs-cancelled": __("Subscription is cancelled", "arraysubs"),
      "arraysubs-expired": __("Subscription is expired", "arraysubs"),
      "arraysubs-pending": __("Subscription is pending", "arraysubs"),
    };

    return (
      statusMessages[subscriptionStatus] ||
      __("Subscription is active", "arraysubs")
    );
  };

  if (loading) {
    return (
      <div className="detail-card">
        <div className="detail-card__header">
          <CalendarX size={20} />
          <h3>{__("Skip & Pause", "arraysubs")}</h3>
        </div>
        <div className="detail-card__body">
          <div className="arraysubs-loading-inline">
            <Loader2 className="arraysubs-spin" size={20} />
            {__("Loading...", "arraysubs")}
          </div>
        </div>
      </div>
    );
  }

  // Skip form fields
  const skipFormItems = [
    {
      field: "Number",
      name: "cycles",
      label: __("Cycles to Skip", "arraysubs"),
      min: 1,
      max: skipStatus?.max_cycles || 3,
      helperText: `${__("Maximum:", "arraysubs")} ${
        skipStatus?.max_cycles || 3
      }`,
      rules: [
        {
          required: true,
          message: __("Number of cycles is required", "arraysubs"),
        },
      ],
    },
    {
      field: "TextArea",
      name: "reason",
      label: __("Reason (Optional)", "arraysubs"),
      placeholder: __("Enter reason for skipping...", "arraysubs"),
      rows: 2,
    },
  ];

  // Modify skip form fields
  const modifySkipFormItems = [
    {
      field: "Number",
      name: "cycles",
      label: __("New Cycle Count", "arraysubs"),
      min: 1,
      max: skipStatus?.max_cycles || 3,
      helperText: `${__("Current:", "arraysubs")} ${
        skipStatus?.skip_remaining || 0
      }`,
      rules: [
        {
          required: true,
          message: __("Number of cycles is required", "arraysubs"),
        },
      ],
    },
  ];

  // Pause form fields
  const pauseFormItems = [
    {
      field: "Number",
      name: "duration_days",
      label: __("Duration (Days)", "arraysubs"),
      min: 0,
      max: pauseStatus?.max_duration_days || 90,
      helperText:
        pauseStatus?.max_duration_days > 0
          ? `${__("Maximum:", "arraysubs")} ${
              pauseStatus?.max_duration_days
            } ${__("days", "arraysubs")}`
          : __("0 = indefinite (until manually resumed)", "arraysubs"),
    },
    {
      field: "TextArea",
      name: "reason",
      label: pauseStatus?.require_reason
        ? __("Reason", "arraysubs")
        : __("Reason (Optional)", "arraysubs"),
      placeholder: __("Enter reason for pausing...", "arraysubs"),
      rows: 2,
      rules: pauseStatus?.require_reason
        ? [{ required: true, message: __("Reason is required", "arraysubs") }]
        : [],
    },
  ];

  return (
    <div className="detail-card arraysubs-skip-pause-card">
      <div className="detail-card__header">
        <CalendarX size={20} />
        <h3>{__("Skip & Pause", "arraysubs")}</h3>
      </div>
      <div className="detail-card__body">
        {/* Skip Status Section */}
        {skipStatus && (
          <div className="arraysubs-skip-pause-section">
            <h4 className="arraysubs-skip-pause-section__title">
              <FastForward size={16} />
              {__("Skip Renewals", "arraysubs")}
            </h4>

            {skipStatus.is_skipping ? (
              <div className="arraysubs-status-box arraysubs-status-box--warning">
                <div className="arraysubs-status-box__content">
                  <AlertCircle size={18} />
                  <div>
                    <strong>
                      {__("Currently Skipping", "arraysubs")}:{" "}
                      {skipStatus.skip_remaining}{" "}
                      {skipStatus.skip_remaining === 1
                        ? __("cycle", "arraysubs")
                        : __("cycles", "arraysubs")}
                    </strong>
                    <p>
                      {__("Skipped on:", "arraysubs")}{" "}
                      {formatDate(skipStatus.skip_started_date)}
                      <br />
                      {__("Original Next Payment:", "arraysubs")}{" "}
                      {formatDate(skipStatus.original_next_payment_date)}
                      {skipStatus.skip_reason && (
                        <>
                          <br />
                          {__("Reason:", "arraysubs")} {skipStatus.skip_reason}
                        </>
                      )}
                    </p>
                  </div>
                </div>
                <div className="arraysubs-status-box__actions">
                  <button
                    type="button"
                    className="button button-small"
                    onClick={() => {
                      modifySkipForm.setFieldsValue({
                        cycles: skipStatus.skip_remaining,
                      });
                      setModifySkipModalOpen(true);
                    }}
                    disabled={actionLoading}
                  >
                    {__("Modify", "arraysubs")}
                  </button>
                  <SpinnerButton
                    type="button"
                    className="button button-small arraysubs-btn--danger"
                    onClick={handleUndoSkip}
                    loading={actionLoading}
                    loadingText={__("Wait…", "arraysubs")}
                  >
                    <RotateCcw size={14} />
                    {__("Undo Skip", "arraysubs")}
                  </SpinnerButton>
                </div>
              </div>
            ) : (
              <div className="arraysubs-status-box arraysubs-status-box--info">
                <div className="arraysubs-status-box__content">
                  <CheckCircle size={18} />
                  <span>{__("No cycles currently skipped", "arraysubs")}</span>
                </div>
                {canSkipOrPause && skipStatus.can_skip && (
                  <button
                    type="button"
                    className="button button-small"
                    onClick={() => setSkipModalOpen(true)}
                    disabled={actionLoading}
                  >
                    <FastForward size={14} />
                    {__("Skip Renewal", "arraysubs")}
                  </button>
                )}
              </div>
            )}
          </div>
        )}

        {/* Pause Status Section */}
        {pauseStatus && (
          <div className="arraysubs-skip-pause-section">
            <h4 className="arraysubs-skip-pause-section__title">
              <Pause size={16} />
              {__("Vacation Mode", "arraysubs")}
            </h4>

            {isPaused && pauseStatus.is_paused ? (
              <div className="arraysubs-status-box arraysubs-status-box--paused">
                <div className="arraysubs-status-box__content">
                  <Pause size={18} />
                  <div>
                    <strong>{__("Subscription Paused", "arraysubs")}</strong>
                    <p>
                      {__("Paused on:", "arraysubs")}{" "}
                      {formatDate(pauseStatus.paused_date)}
                      {pauseStatus.resume_date && (
                        <>
                          <br />
                          {__("Scheduled Resume:", "arraysubs")}{" "}
                          {formatDate(pauseStatus.resume_date)}
                        </>
                      )}
                      {pauseStatus.pause_reason && (
                        <>
                          <br />
                          {__("Reason:", "arraysubs")}{" "}
                          {pauseStatus.pause_reason}
                        </>
                      )}
                    </p>
                  </div>
                </div>
                <SpinnerButton
                  type="button"
                  className="button button-small button-primary"
                  onClick={handleResume}
                  loading={actionLoading}
                  loadingText={__("Resuming…", "arraysubs")}
                >
                  <Play size={14} />
                  {__("Resume Now", "arraysubs")}
                </SpinnerButton>
              </div>
            ) : (
              <div className="arraysubs-status-box arraysubs-status-box--info">
                <div className="arraysubs-status-box__content">
                  <CheckCircle size={18} />
                  <span>{getPauseIdleMessage()}</span>
                </div>
                {canSkipOrPause && pauseStatus.can_pause && (
                  <button
                    type="button"
                    className="button button-small"
                    onClick={() => setPauseModalOpen(true)}
                    disabled={actionLoading}
                  >
                    <Pause size={14} />
                    {__("Pause Subscription", "arraysubs")}
                  </button>
                )}
              </div>
            )}

            {/* Pause History Summary */}
            {pauseStatus.pause_count > 0 && (
              <div className="arraysubs-pause-history-summary">
                <Calendar size={14} />
                <span>
                  {pauseStatus.pause_count}{" "}
                  {pauseStatus.pause_count === 1
                    ? __("pause in history", "arraysubs")
                    : __("pauses in history", "arraysubs")}
                </span>
              </div>
            )}
          </div>
        )}

        {/* No Features Enabled */}
        {!skipStatus?.enabled && !pauseStatus?.enabled && (
          <div className="arraysubs-status-box arraysubs-status-box--disabled">
            <AlertCircle size={18} />
            <span>
              {__(
                "Skip & Pause features are not enabled. Enable them in Settings.",
                "arraysubs",
              )}
            </span>
          </div>
        )}
      </div>

      {/* Skip Modal */}
      <Modal
        isOpen={skipModalOpen}
        onClose={() => setSkipModalOpen(false)}
        title={__("Skip Renewal Cycles", "arraysubs")}
        size="small"
      >
        <Form
          form={skipForm}
          onFinish={handleSkip}
          initialValues={{ cycles: 1, reason: "" }}
        >
          <FormBuilder formItems={skipFormItems} form={skipForm} />
          <div className="arraysubs-modal-actions">
            <button
              type="button"
              className="button"
              onClick={() => setSkipModalOpen(false)}
              disabled={actionLoading}
            >
              {__("Cancel", "arraysubs")}
            </button>
            <button
              type="submit"
              className="button button-primary"
              disabled={actionLoading}
            >
              {actionLoading ? (
                <>
                  <Loader2 className="arraysubs-spin" size={14} />
                  {__("Skipping...", "arraysubs")}
                </>
              ) : (
                __("Skip Cycles", "arraysubs")
              )}
            </button>
          </div>
        </Form>
      </Modal>

      {/* Modify Skip Modal */}
      <Modal
        isOpen={modifySkipModalOpen}
        onClose={() => setModifySkipModalOpen(false)}
        title={__("Modify Skip Cycles", "arraysubs")}
        size="small"
      >
        <Form form={modifySkipForm} onFinish={handleModifySkip}>
          <FormBuilder formItems={modifySkipFormItems} form={modifySkipForm} />
          <div className="arraysubs-modal-actions">
            <button
              type="button"
              className="button"
              onClick={() => setModifySkipModalOpen(false)}
              disabled={actionLoading}
            >
              {__("Cancel", "arraysubs")}
            </button>
            <button
              type="submit"
              className="button button-primary"
              disabled={actionLoading}
            >
              {actionLoading ? (
                <>
                  <Loader2 className="arraysubs-spin" size={14} />
                  {__("Updating...", "arraysubs")}
                </>
              ) : (
                __("Update Skip", "arraysubs")
              )}
            </button>
          </div>
        </Form>
      </Modal>

      {/* Pause Modal */}
      <Modal
        isOpen={pauseModalOpen}
        onClose={() => setPauseModalOpen(false)}
        title={__("Pause Subscription", "arraysubs")}
        size="small"
      >
        <Form
          form={pauseForm}
          onFinish={handlePause}
          initialValues={{ duration_days: 30, reason: "" }}
        >
          <FormBuilder formItems={pauseFormItems} form={pauseForm} />
          <div className="arraysubs-modal-actions">
            <button
              type="button"
              className="button"
              onClick={() => setPauseModalOpen(false)}
              disabled={actionLoading}
            >
              {__("Cancel", "arraysubs")}
            </button>
            <button
              type="submit"
              className="button button-primary"
              disabled={actionLoading}
            >
              {actionLoading ? (
                <>
                  <Loader2 className="arraysubs-spin" size={14} />
                  {__("Pausing...", "arraysubs")}
                </>
              ) : (
                __("Pause Subscription", "arraysubs")
              )}
            </button>
          </div>
        </Form>
      </Modal>

      {confirmDialog}
    </div>
  );
};

export default SkipPauseCard;
