'useclient';
import {useState} from "react";
import {
  useStripe,
  useElements,
  PaymentElement,
} from "@stripe/react-stripe-js";
import Button from "./Button";
import { useCartStore } from "@/_stores/useCartStore";
import { useTranslation } from 'next-i18next';

export default function CheckoutForm() {
  const { t } = useTranslation("common");
  const [status, setStatus] = useState<"idle" | "processing" | "success" | "error">("idle");
  const stripe = useStripe();
  const elements = useElements();
  const bookingId = useCartStore((state) => state.bookingId);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!stripe || !elements || !bookingId) return;
    setStatus("processing");
    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        return_url: `${window.location.origin}/candidate/booking/confirmation?bookingId=${bookingId}`,
      },
    });

    if (error) {
      setStatus("error");
      console.error(error);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="max-w-lg mx-auto p-4">
      {status === "processing" && <div>{t("checkout.processingPayment")}</div>}
      {status === "success" && <div>{t("checkout.paymentSuccess")}</div>}
      {status === "error" && <div>{t("checkout.paymentError")}</div>}
      <PaymentElement />
      <div className="text-center mt-4 mx-auto">
        <Button type="submit" disabled={!stripe}>
          {t("checkout.payButton")}
        </Button>
      </div>
    </form>
  );
}
