"use client";

import React, { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
  PlusIcon,
  ArrowPathIcon,
  XMarkIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { TopUpModal } from "./TopUpModal";
import { ChangePlanModal } from "./ChangePlanModal";
import { ReissueSimModal } from "./ReissueSimModal";
import { apiClient } from "@/core/api";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { Button } from "@/components/atoms/button";

// Shared style constants
const PROCESSING_TEXT = "Processing...";
const ACTION_BUTTON_BASE_CLASSES =
  "w-full flex items-center justify-start px-4 py-4 rounded-lg text-sm font-medium transition-colors duration-[var(--cp-duration-normal)]";
const ACTIVE_BUTTON_FOCUS_CLASSES =
  "focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background";
const DISABLED_BUTTON_CLASSES = "text-muted-foreground bg-muted cursor-not-allowed";
const SHADOW_CLASSES = "shadow-[var(--cp-shadow-1)] hover:shadow-[var(--cp-shadow-2)]";

interface SimActionsProps {
  subscriptionId: number;
  simType: "physical" | "esim";
  status: string;
  onTopUpSuccess?: () => void;
  onPlanChangeSuccess?: () => void;
  onCancelSuccess?: () => void;
  onReissueSuccess?: () => void;
  embedded?: boolean;
  currentPlanCode?: string;
}

type ActiveInfoType = "topup" | "reissue" | "cancel" | "changePlan" | null;

// Action button component to reduce repetition
interface ActionButtonProps {
  onClick: () => void;
  disabled: boolean;
  isEnabled: boolean;
  enabledClasses: string;
  icon: React.ReactNode;
  label: string;
  description: string;
  isLoading?: boolean;
  disabledReason?: string | null;
}

function ActionButton({
  onClick,
  disabled,
  isEnabled,
  enabledClasses,
  icon,
  label,
  description,
  isLoading,
  disabledReason,
}: ActionButtonProps): React.ReactElement {
  const buttonClasses = `${ACTION_BUTTON_BASE_CLASSES} ${
    isEnabled
      ? `${enabledClasses} ${SHADOW_CLASSES} ${ACTIVE_BUTTON_FOCUS_CLASSES}`
      : DISABLED_BUTTON_CLASSES
  }`;

  return (
    <button onClick={onClick} disabled={disabled} className={buttonClasses}>
      <div className="flex items-center">
        {icon}
        <div className="text-left">
          <div className="font-medium">{isLoading ? PROCESSING_TEXT : label}</div>
          <div className="text-xs opacity-90">{description}</div>
        </div>
      </div>
      {!isEnabled && disabledReason && (
        <div className="mt-3 w-full rounded-md border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-muted-foreground">
          {disabledReason}
        </div>
      )}
    </button>
  );
}

// Reissue button has different structure, so separate component
interface ReissueButtonProps {
  onClick: () => void;
  disabled: boolean;
  isEnabled: boolean;
  disabledReason: string | null;
}

function ReissueButton({
  onClick,
  disabled,
  isEnabled,
  disabledReason,
}: ReissueButtonProps): React.ReactElement {
  const enabledClasses =
    "border-success/30 bg-success-soft text-foreground hover:bg-success-soft/80";
  const disabledClasses = "text-muted-foreground bg-muted border-border cursor-not-allowed";
  const buttonClasses = `w-full flex flex-col items-start justify-start rounded-lg border px-4 py-4 text-left text-sm font-medium transition-colors duration-[var(--cp-duration-normal)] ${
    isEnabled
      ? `${enabledClasses} ${SHADOW_CLASSES} ${ACTIVE_BUTTON_FOCUS_CLASSES}`
      : disabledClasses
  }`;

  return (
    <button onClick={onClick} disabled={disabled} className={buttonClasses}>
      <div className="flex w-full items-center justify-between">
        <div className="flex items-center">
          <ArrowPathIcon className="h-4 w-4 mr-3" />
          <div className="text-left">
            <div className="font-medium">Reissue SIM</div>
            <div className="text-xs opacity-70">
              Configure replacement options and submit your request.
            </div>
          </div>
        </div>
      </div>
      {!isEnabled && disabledReason && (
        <div className="mt-3 w-full rounded-md border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-muted-foreground">
          {disabledReason}
        </div>
      )}
    </button>
  );
}

// Action info panel component
interface ActionInfoPanelProps {
  activeInfo: ActiveInfoType;
}

function ActionInfoPanel({ activeInfo }: ActionInfoPanelProps): React.ReactElement | null {
  if (!activeInfo) return null;

  const infoContent: Record<
    NonNullable<ActiveInfoType>,
    { icon: React.ReactNode; title: string; text: React.ReactNode }
  > = {
    topup: {
      icon: <PlusIcon className="h-4 w-4 text-primary mr-2 mt-0.5 flex-shrink-0" />,
      title: "Top Up Data:",
      text: "Add additional data quota to your SIM service. You can choose the amount and schedule it for later if needed.",
    },
    reissue: {
      icon: <ArrowPathIcon className="h-4 w-4 text-success mr-2 mt-0.5 flex-shrink-0" />,
      title: "Reissue SIM:",
      text: "Submit a replacement request for either a physical SIM or an eSIM. eSIM users can optionally supply a new EID to pair with the replacement profile.",
    },
    cancel: {
      icon: <XMarkIcon className="h-4 w-4 text-danger mr-2 mt-0.5 flex-shrink-0" />,
      title: "Cancel SIM:",
      text: "Permanently cancel your SIM service. This action cannot be undone and will terminate your service immediately.",
    },
    changePlan: {
      icon: (
        <svg
          className="h-4 w-4 text-primary mr-2 mt-0.5 flex-shrink-0"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"
          />
        </svg>
      ),
      title: "Change Plan:",
      text: (
        <>
          Switch to a different data plan.{" "}
          <span className="text-warning font-medium">
            Important: Plan changes must be requested before the 25th of the month. Changes will
            take effect on the 1st of the following month.
          </span>
        </>
      ),
    },
  };

  const info = infoContent[activeInfo];

  return (
    <div className="mt-6 text-sm text-muted-foreground bg-muted border border-border rounded-lg p-4">
      <div className="flex items-start">
        {info.icon}
        <div>
          <strong>{info.title}</strong> {info.text}
        </div>
      </div>
    </div>
  );
}

// Cancel confirmation modal component
interface CancelConfirmModalProps {
  onCancel: () => void;
  onConfirm: () => void;
  loading: boolean;
}

function CancelConfirmModal({
  onCancel,
  onConfirm,
  loading,
}: CancelConfirmModalProps): React.ReactElement {
  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div className="fixed inset-0 bg-background/70 backdrop-blur-sm transition-opacity"></div>
        <div className="inline-block align-bottom bg-card rounded-lg text-left overflow-hidden shadow-[var(--cp-shadow-3)] border border-border transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div className="bg-card px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div className="sm:flex sm:items-start">
              <div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-danger-soft sm:mx-0 sm:h-10 sm:w-10">
                <ExclamationTriangleIcon className="h-6 w-6 text-danger" />
              </div>
              <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                <h3 className="text-lg leading-6 font-medium text-foreground">
                  Cancel SIM Service
                </h3>
                <div className="mt-2">
                  <p className="text-sm text-muted-foreground">
                    Are you sure you want to cancel this SIM service? This action cannot be undone
                    and will permanently terminate your service.
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div className="bg-muted px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse gap-3">
            <Button
              variant="destructive"
              onClick={onConfirm}
              loading={loading}
              loadingText="Processing…"
            >
              Cancel SIM
            </Button>
            <Button variant="outline" onClick={onCancel} disabled={loading}>
              Back
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Status banners component
interface StatusBannersProps {
  success: string | null;
  error: string | null;
  isActive: boolean;
}

function StatusBanners({ success, error, isActive }: StatusBannersProps): React.ReactElement {
  return (
    <>
      {success && (
        <div className="mb-4">
          <AlertBanner variant="success" title="Success" size="sm" elevated>
            {success}
          </AlertBanner>
        </div>
      )}
      {error && (
        <div className="mb-4">
          <AlertBanner variant="error" title="Unable to complete action" size="sm" elevated>
            {error}
          </AlertBanner>
        </div>
      )}
      {!isActive && (
        <div className="mb-4">
          <AlertBanner variant="warning" title="Not available" size="sm" elevated>
            SIM management actions are only available for active services.
          </AlertBanner>
        </div>
      )}
    </>
  );
}

// Action buttons grid component
interface ActionButtonsGridProps {
  canTopUp: boolean;
  canReissue: boolean;
  canCancel: boolean;
  isActive: boolean;
  loading: string | null;
  reissueDisabledReason: string | null;
  onTopUpClick: () => void;
  onChangePlanClick: () => void;
  onReissueClick: () => void;
  onCancelClick: () => void;
}

function ActionButtonsGrid({
  canTopUp,
  canReissue,
  canCancel,
  isActive,
  loading,
  reissueDisabledReason,
  onTopUpClick,
  onChangePlanClick,
  onReissueClick,
  onCancelClick,
}: ActionButtonsGridProps): React.ReactElement {
  const isNotLoading = loading === null;

  return (
    <div className="space-y-3">
      <ActionButton
        onClick={onTopUpClick}
        disabled={!canTopUp || !isNotLoading}
        isEnabled={canTopUp && isNotLoading}
        enabledClasses="text-primary-foreground bg-primary hover:bg-primary-hover"
        icon={<PlusIcon className="h-4 w-4 mr-3" />}
        label="Top Up Data"
        description="Add more data to your plan"
        isLoading={loading === "topup"}
      />
      <ActionButton
        onClick={onChangePlanClick}
        disabled={!isActive || !isNotLoading}
        isEnabled={isActive && isNotLoading}
        enabledClasses="text-secondary-foreground bg-secondary hover:bg-secondary/80"
        icon={<ArrowPathIcon className="h-4 w-4 mr-3" />}
        label="Change Plan"
        description="Switch to a different plan"
        isLoading={loading === "change-plan"}
      />
      <ReissueButton
        onClick={onReissueClick}
        disabled={!canReissue || !isNotLoading}
        isEnabled={canReissue && isNotLoading}
        disabledReason={reissueDisabledReason}
      />
      <ActionButton
        onClick={onCancelClick}
        disabled={!canCancel || !isNotLoading}
        isEnabled={canCancel && isNotLoading}
        enabledClasses="text-danger bg-danger-soft border border-danger/30 hover:bg-danger-soft/80"
        icon={<XMarkIcon className="h-4 w-4 mr-3" />}
        label="Cancel SIM"
        description="Permanently cancel service"
        isLoading={loading === "cancel"}
      />
    </div>
  );
}

// Custom hook for SIM actions state management
function useSimActionsState(subscriptionId: number, onCancelSuccess?: () => void) {
  const router = useRouter();
  const [showTopUpModal, setShowTopUpModal] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [showReissueModal, setShowReissueModal] = useState(false);
  const [loading, setLoading] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [showChangePlanModal, setShowChangePlanModal] = useState(false);
  const [activeInfo, setActiveInfo] = useState<ActiveInfoType>(null);

  const handleCancelSim = async (): Promise<void> => {
    setLoading("cancel");
    setError(null);

    try {
      await apiClient.POST("/api/subscriptions/{id}/sim/cancel", {
        params: { path: { id: subscriptionId } },
        body: {},
      });

      setSuccess("SIM service cancelled successfully");
      setShowCancelConfirm(false);
      onCancelSuccess?.();
    } catch (err: unknown) {
      setError(
        process.env.NODE_ENV === "development"
          ? err instanceof Error
            ? err.message
            : "Failed to cancel SIM service"
          : "Unable to cancel SIM service right now. Please try again."
      );
    } finally {
      setLoading(null);
    }
  };

  React.useEffect(() => {
    if (!success && !error) return;
    const timer = setTimeout(() => {
      setSuccess(null);
      setError(null);
    }, 5000);
    return () => clearTimeout(timer);
  }, [success, error]);

  const handleTopUpClick = (): void => {
    setActiveInfo("topup");
    try {
      router.push(`/account/subscriptions/${subscriptionId}/sim/top-up`);
    } catch {
      setShowTopUpModal(true);
    }
  };

  const handleChangePlanClick = (): void => {
    setActiveInfo("changePlan");
    try {
      router.push(`/account/subscriptions/${subscriptionId}/sim/change-plan`);
    } catch {
      setShowChangePlanModal(true);
    }
  };

  const handleReissueClick = (): void => {
    setActiveInfo("reissue");
    setShowReissueModal(true);
  };

  const handleCancelClick = (): void => {
    setActiveInfo("cancel");
    try {
      router.push(`/account/subscriptions/${subscriptionId}/cancel`);
    } catch {
      setShowCancelConfirm(true);
    }
  };

  return {
    showTopUpModal,
    setShowTopUpModal,
    showCancelConfirm,
    setShowCancelConfirm,
    showReissueModal,
    setShowReissueModal,
    showChangePlanModal,
    setShowChangePlanModal,
    loading,
    error,
    setError,
    success,
    setSuccess,
    activeInfo,
    setActiveInfo,
    handleCancelSim,
    handleTopUpClick,
    handleChangePlanClick,
    handleReissueClick,
    handleCancelClick,
  };
}

export function SimActions({
  subscriptionId,
  simType,
  status,
  onTopUpSuccess,
  onPlanChangeSuccess,
  onCancelSuccess,
  onReissueSuccess,
  embedded = false,
  currentPlanCode,
}: SimActionsProps): React.ReactElement {
  const state = useSimActionsState(subscriptionId, onCancelSuccess);

  const isActive = status === "active";
  const reissueDisabledReason = useMemo(
    () => (isActive ? null : "SIM must be active to request a reissue."),
    [isActive]
  );

  const containerClasses = embedded
    ? ""
    : "bg-card shadow-[var(--cp-shadow-1)] rounded-xl border border-border";
  const contentClasses = embedded ? "" : "px-6 lg:px-8 py-6";

  return (
    <div id="sim-actions" className={containerClasses}>
      {!embedded && (
        <div className="px-6 py-6 border-b border-border">
          <h3 className="text-lg font-semibold tracking-tight text-foreground mb-1">
            SIM Management Actions
          </h3>
          <p className="text-sm text-muted-foreground">Manage your SIM service</p>
        </div>
      )}

      <div className={contentClasses}>
        <StatusBanners success={state.success} error={state.error} isActive={isActive} />
        <ActionButtonsGrid
          canTopUp={isActive}
          canReissue={isActive}
          canCancel={isActive}
          isActive={isActive}
          loading={state.loading}
          reissueDisabledReason={reissueDisabledReason}
          onTopUpClick={state.handleTopUpClick}
          onChangePlanClick={state.handleChangePlanClick}
          onReissueClick={state.handleReissueClick}
          onCancelClick={state.handleCancelClick}
        />
        <ActionInfoPanel activeInfo={state.activeInfo} />
      </div>

      {state.showTopUpModal && (
        <TopUpModal
          subscriptionId={subscriptionId}
          onClose={() => {
            state.setShowTopUpModal(false);
            state.setActiveInfo(null);
          }}
          onSuccess={() => {
            state.setShowTopUpModal(false);
            state.setSuccess("Data top-up completed successfully");
            onTopUpSuccess?.();
          }}
          onError={message => state.setError(message)}
        />
      )}

      {state.showChangePlanModal && (
        <ChangePlanModal
          subscriptionId={subscriptionId}
          currentPlanCode={currentPlanCode ?? ""}
          onClose={() => {
            state.setShowChangePlanModal(false);
            state.setActiveInfo(null);
          }}
          onSuccess={() => {
            state.setShowChangePlanModal(false);
            state.setSuccess("SIM plan change submitted successfully");
            onPlanChangeSuccess?.();
          }}
          onError={message => state.setError(message)}
        />
      )}

      {state.showReissueModal && (
        <ReissueSimModal
          subscriptionId={subscriptionId}
          currentSimType={simType}
          onClose={() => {
            state.setShowReissueModal(false);
            state.setActiveInfo(null);
          }}
          onSuccess={() => {
            state.setShowReissueModal(false);
            state.setSuccess("SIM reissue request submitted successfully");
            onReissueSuccess?.();
          }}
          onError={message => state.setError(message)}
        />
      )}

      {state.showCancelConfirm && (
        <CancelConfirmModal
          onCancel={() => {
            state.setShowCancelConfirm(false);
            state.setActiveInfo(null);
          }}
          onConfirm={() => void state.handleCancelSim()}
          loading={state.loading === "cancel"}
        />
      )}
    </div>
  );
}
