"use client";

import { useState } from "react";
import { Dialog, DialogPanel, DialogTitle } from '@headlessui/react'
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import CheckoutForm from '@/_components/CheckoutForm';
import Loading from "@/_components/Loading";
import { useCheckout } from '@/_hooks/useCheckout';
import { useCurrency } from "@/_hooks/useCurrency";
import { useTranslation } from 'next-i18next';

const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_KEY!);

export default function CheckoutModal({ isOpen, setIsOpen }: { isOpen: boolean; setIsOpen: (open: boolean) => void }) {
  const { t } = useTranslation("common");
  const { clientSecret, fetchCheckout } = useCheckout();
  const { loading, currency, setCurrency, convertedSubtotal } = useCurrency();
  const [checkout, setCheckout] = useState<boolean>(false);

  const currencySymbols: { [key: string]: string } = {
    usd: "$",
    eur: "€",
    gbp: "£",
  };

  function close() {
    setIsOpen(false)
    setCheckout(false);
  }

  function handleCheckoutClick() {
    setCheckout(true);
    if (!currency || !convertedSubtotal) return;
    fetchCheckout(convertedSubtotal, currency);
  }

  const options = clientSecret
    ? {
      clientSecret,
      appearance: {
        theme: "flat" as const,
        variables: {
          colorPrimary: '#f6339a',
        }
      }
    }
    : undefined;

  return (
    <Dialog open={isOpen} as="div" className="relative z-100 focus:outline-none" onClose={close}>
      {!currency && !clientSecret && !checkout && (
        <div className="flex justify-center py-10">
          <Loading />
        </div>
      )}
      <div className="fixed inset-0 z-10 w-screen overflow-y-auto">
        <div className="flex min-h-full items-center justify-center p-4">
          <DialogPanel
            transition
            className="w-full max-w-md rounded-xl bg-white/5 p-6 backdrop-blur-2xl duration-300 ease-out data-closed:transform-[scale(95%)] data-closed:opacity-0"
          >
            <DialogTitle as="h3" className="text-base/7 font-medium text-black">
              {t("checkout.checkoutTitle")}
            </DialogTitle>
            <p className="mt-2 text-sm/6 text-black/50">
              {t("checkout.checkoutDescription")}
            </p>
            <div className="border-t border-gray-200 px-4 py-6 sm:px-6">
              <div className="flex justify-between text-base font-medium text-gray-900">
                <p>{t("checkout.totalAmount")}</p>
                <p>
                  {loading ? "..." : (
                    `${currencySymbols[currency || "usd"]}${convertedSubtotal}`
                  )}
                </p>
              </div>
              <p className="mt-0.5 text-sm text-gray-500">
                {t("checkout.shippingAndTaxes")}
              </p>
              <div className="mt-4">
                <label htmlFor="currency" className="block text-sm font-medium text-gray-700">
                  {t("checkout.selectCurrency")}
                </label>
                <select
                  id="currency"
                  name="currency"
                  value={currency || 'usd'}
                  onChange={(e) => setCurrency(e.target.value)}
                  className="mt-1 w-full border p-2 h-10 rounded-md border-gray-300 shadow-sm focus:border-pink-500 focus:ring focus:ring-pink-200 sm:text-sm"
                >
                  <option value="gbp">GBP (£)</option>
                  <option value="eur">EUR (€)</option>
                  <option value="usd">USD ($)</option>
                </select>
              </div>
              <button
                onClick={handleCheckoutClick}
                className="mt-4 w-full bg-pink-600 text-white py-2 px-4 rounded-md hover:bg-pink-700 focus:outline-none focus:ring-2 focus:ring-pink-500 focus:ring-offset-2"
              >
                {t("checkout.proceedToPayment")}
              </button>
            </div>
            {clientSecret && checkout && (
              <Elements key={clientSecret} stripe={stripePromise} options={options}>
                <CheckoutForm />
              </Elements>
            )}
          </DialogPanel>
        </div>
      </div>
    </Dialog>
  )
}
