"use client";

import { useState } from "react";
import { useGetPaymentOptions } from "@/hooks/useApi";
import { membershipService } from "@/services/membershipService";
import { FiChevronRight, FiX } from "react-icons/fi";
import Image from "next/image";
import toast from "react-hot-toast";
import { TEXT } from "@/branding";
import { useAppSettings } from "@/lib/settingsContext";
import { getErrorMessage } from "@/lib/utils";
import { openRazorpayCheckout, PAYMENT_LOGOS } from "@/lib/razorpay";
import type { MembershipPlan, PaymentOption } from "@/types";

interface MembershipPaymentModalProps {
  plan: MembershipPlan;
  onClose: () => void;
  onSuccess: () => void;
}

export default function MembershipPaymentModal({ plan, onClose, onSuccess }: MembershipPaymentModalProps) {
  const { data, isLoading } = useGetPaymentOptions();
  const { settings } = useAppSettings();
  const [placing, setPlacing] = useState(false);
  const [activeMethod, setActiveMethod] = useState<string | null>(null);

  /* result is a keyed object — convert to array and filter visible ones */
  const methods: PaymentOption[] = Object.values(data?.result ?? {}).filter((m) => m.visibility === 1);

  /* ── Called only after the gateway confirms payment succeeded ── */
  const completeSubscription = async () => {
    setPlacing(true);
    try {
      const res = await membershipService.subscribe(plan.id, plan.price);
      if (res.status === 200) {
        toast.success(res.message || TEXT.membership.subscribeSuccess);
        onSuccess();
        onClose();
      } else {
        toast.error(res.message || TEXT.common.error);
        setActiveMethod(null);
      }
    } catch (err) {
      toast.error(getErrorMessage(err));
      setActiveMethod(null);
    } finally {
      setPlacing(false);
    }
  };

  const openPayment = (method: PaymentOption) => {
    const pgName = method.name.toLowerCase();
    setActiveMethod(pgName);

    if (pgName !== "razorpay") {
      toast(`${method.name} coming soon`);
      setActiveMethod(null);
      return;
    }

    openRazorpayCheckout({
      key: method.key_1,
      amount: plan.price,
      currency: settings.currency,
      name: TEXT.appName,
      description: `${plan.name} — ${TEXT.membership.title}`,
      onSuccess: completeSubscription,
      onDismiss: () => setActiveMethod(null),
      onNotConfigured: () => {
        toast.error(TEXT.payment.gatewayNotConfigured);
        setActiveMethod(null);
      },
    });
  };

  const Spinner = () => (
    <span className="w-5 h-5 border-2 border-primary-700 border-t-transparent rounded-full animate-spin flex-shrink-0" />
  );

  return (
    <div
      className="fixed inset-0 bg-black/40 flex items-end sm:items-center justify-center z-[80]"
      onClick={onClose}
    >
      <div
        className="bg-white dark:bg-dm-surface rounded-t-2xl sm:rounded-2xl w-full sm:max-w-[420px] overflow-hidden shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100 dark:border-dm-border">
          <div>
            <h3 className="font-bold text-gray-900 dark:text-dm-text">{TEXT.payment.selectMethod}</h3>
            <p className="text-xs text-gray-400 dark:text-dm-muted mt-0.5">
              {plan.name} · {settings.currencyCode}{plan.price}
              {TEXT.membership.perPlan(plan.duration_type, plan.duration_value)}
            </p>
          </div>
          <button
            onClick={onClose}
            disabled={placing}
            className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-dm-surface2 text-gray-400 dark:text-dm-muted disabled:opacity-40"
          >
            <FiX size={18} />
          </button>
        </div>

        <div className="p-4 space-y-2 max-h-[60vh] overflow-y-auto">
          {isLoading ? (
            <div className="space-y-2">
              {[1, 2, 3].map((i) => (
                <div key={i} className="h-14 bg-gray-100 dark:bg-dm-surface2 rounded-xl animate-pulse" />
              ))}
            </div>
          ) : methods.length === 0 ? (
            <p className="text-sm text-gray-400 text-center py-8">{TEXT.payment.gatewayNotConfigured}</p>
          ) : (
            <div className="bg-gray-50 dark:bg-dm-surface2 rounded-xl overflow-hidden divide-y divide-gray-100 dark:divide-dm-border">
              {methods.map((method) => {
                const pgKey = method.name.toLowerCase();
                const logo = PAYMENT_LOGOS[pgKey];
                const isActive = activeMethod === pgKey && placing;

                return (
                  <button
                    key={method.id}
                    onClick={() => openPayment(method)}
                    disabled={placing}
                    className="w-full px-4 py-3.5 flex items-center justify-between hover:bg-gray-100 dark:hover:bg-dm-surface disabled:opacity-60 disabled:cursor-not-allowed transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-12 h-8 bg-white dark:bg-dm-surface2 rounded-md border border-gray-200 dark:border-dm-border flex items-center justify-center p-1 flex-shrink-0">
                        {logo ? (
                          <Image
                            src={logo}
                            alt={method.name}
                            width={40}
                            height={24}
                            className="object-contain w-full h-full"
                            unoptimized
                          />
                        ) : (
                          <span className="text-xs text-gray-400">Pay</span>
                        )}
                      </div>
                      <span className="font-medium text-gray-800 text-sm dark:text-dm-text">{method.name}</span>
                    </div>
                    {isActive ? <Spinner /> : <FiChevronRight size={16} className="text-gray-400" />}
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
