"use client";

import { AnimatePresence, motion } from "framer-motion";
import { X } from "lucide-react";
import React, { useEffect, useState } from "react";
import { createPortal } from "react-dom";

import { BillingRegion } from "@/api/types/auth";

interface RegionOption {
  value: BillingRegion;
  flag: string;
  label: string;
  features: string[];
}

const REGION_OPTIONS: RegionOption[] = [
  {
    value: "INDIA",
    flag: "🇮🇳",
    label: "India",
    features: [
      "Prices in INR",
      "GST invoice",
      "Pay using Indian payment methods",
    ],
  },
  {
    value: "OUTSIDE_INDIA",
    flag: "🌍",
    label: "Outside India",
    features: ["Prices in USD", "International cards accepted"],
  },
];

interface BillingRegionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onContinue?: (region: BillingRegion) => void;
  defaultValue?: BillingRegion;
  loading?: boolean;
}

const BillingRegionModal: React.FC<BillingRegionModalProps> = ({
  isOpen,
  onClose,
  onContinue,
  defaultValue,
  loading = false,
}) => {
  const [selected, setSelected] = useState<BillingRegion | null>(
    defaultValue ?? null,
  );

  // Reset the selection to the current default each time the modal opens.
  // Done during render (React's "adjust state when a prop changes" pattern)
  // rather than in an effect — so an in-flight save that re-renders the parent
  // (new onClose ref / loading flag) never snaps the selection back to the
  // previous value before the modal closes.
  const [wasOpen, setWasOpen] = useState(isOpen);
  if (isOpen !== wasOpen) {
    setWasOpen(isOpen);
    if (isOpen) setSelected(defaultValue ?? null);
  }

  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };

    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    document.addEventListener("keydown", handleKeyDown);

    return () => {
      document.body.style.overflow = originalOverflow;
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, onClose]);

  const handleContinue = () => {
    if (!selected) return;
    onContinue?.(selected);
  };

  if (typeof document === "undefined") return null;

  return createPortal(
    <AnimatePresence>
      {isOpen && (
        <motion.div
          role="dialog"
          aria-modal="true"
          aria-labelledby="billing-region-title"
          onClick={onClose}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          className="fixed inset-0 z-[100] flex items-center justify-center bg-black/10 px-4 backdrop-blur-sm"
        >
          <motion.div
            onClick={(e) => e.stopPropagation()}
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
            transition={{ duration: 0.2 }}
            className="relative w-full max-w-[420px] bg-white rounded-[19px] shadow-xl"
          >
            {/* Close button */}
            <button
              onClick={onClose}
              aria-label="Close"
              className="absolute top-[11px] right-[12px] w-[29px] h-[29px] bg-white rounded-full border border-[#DBDBDB] flex items-center justify-center hover:bg-neutral-50 transition-colors cursor-pointer z-10"
            >
              <X size={16} className="text-[#737373]" strokeWidth={1.5} />
            </button>

            {/* Content */}
            <div className="flex flex-col gap-5 px-6 pt-8 pb-7">
              {/* Title + subtitle */}
              <div className="flex flex-col gap-1.5">
                <h2
                  id="billing-region-title"
                  className="font-sans text-[22px] font-bold leading-[1.3] tracking-[-0.02em] text-black"
                >
                  Choose your billing region
                </h2>
                <p className="font-sans text-[16px] font-semibold leading-[1.3] text-black">
                  Where would you like to be billed?
                </p>
              </div>

              {/* Options */}
              <div className="flex flex-col gap-3">
                {REGION_OPTIONS.map((option) => {
                  const isActive = selected === option.value;
                  return (
                    <label
                      key={option.value}
                      className={`flex flex-col gap-2 px-4 py-3.5 rounded-[12px] border cursor-pointer transition-colors ${
                        isActive
                          ? "border-[#08A1EE] bg-[#F0F9FF]"
                          : "border-[#DBDBDB] hover:border-[#B8B8B8]"
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <input
                          type="radio"
                          name="billing-region"
                          value={option.value}
                          checked={isActive}
                          onChange={() => setSelected(option.value)}
                          className="w-[18px] h-[18px]  cursor-pointer shrink-0"
                        />
                        <span className="text-[18px] leading-none">
                          {option.flag}
                        </span>
                        <span className="font-sans text-[16px] font-semibold text-black">
                          {option.label}
                        </span>
                      </div>
                      <ul className="flex flex-col gap-1 pl-[30px]">
                        {option.features.map((feature) => (
                          <li
                            key={feature}
                            className="flex items-start gap-2 font-sans text-[14px] text-[#484848]"
                          >
                            <span className="mt-[7px] w-1 h-1 rounded-full bg-[#484848] shrink-0" />
                            <span>{feature}</span>
                          </li>
                        ))}
                      </ul>
                    </label>
                  );
                })}
              </div>

              {/* Continue */}
              <button
                type="button"
                onClick={handleContinue}
                disabled={!selected || loading}
                className="w-full h-[46px] bg-[#08A1EE] rounded-[34px] font-sans text-[16px] font-bold text-white hover:bg-[#0791d4] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed shadow-[0px_1px_2px_0px_rgba(0,0,0,0.08)]"
              >
                {loading ? "Saving…" : "Continue"}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>,
    document.body,
  );
};

export default BillingRegionModal;
