"use client";

import { useEffect, useRef } from "react";
import { useForm, Controller, Resolver } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
// import { useBooking } from "@/context/BookingContext";
// import { convertExpirationDateToISO } from "@/lib/bookingUtils";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useTranslations } from "next-intl";

interface PaymentMethodProps {
  onFormValidChange?: (isValid: boolean) => void;
}

export default function PaymentMethod({
  onFormValidChange,
}: PaymentMethodProps) {
  const t = useTranslations("ReservationPage");
  const tValidation = useTranslations("Validation");
  // COMMENTED OUT: Payment method data should not be saved to context
  // const { setPaymentInformation } = useBooking();

  const validationSchema = yup.object().shape({
    paymentType: yup
      .string()
      .required(tValidation("paymentMethodRequired"))
      .oneOf(
        ["credit-card", "debit-card", "paypal"],
        tValidation("selectPaymentMethod")
      ),
    cardNumber: yup.string().when("paymentType", {
      is: (val: string) => val === "credit-card" || val === "debit-card",
      then: (schema) =>
        schema
          .required(tValidation("phoneRequired"))
          .min(13, tValidation("phoneRequired"))
          .max(19, tValidation("phoneRequired")),
      otherwise: (schema) => schema.notRequired(),
    }),
    expireDate: yup.string().when("paymentType", {
      is: (val: string) => val === "credit-card" || val === "debit-card",
      then: (schema) =>
        schema
          .required(tValidation("phoneRequired"))
          .length(5, tValidation("phoneRequired")),
      otherwise: (schema) => schema.notRequired(),
    }),
  });

  type FormValues = yup.InferType<typeof validationSchema>;

  const {
    control,
    // watch,
    setValue,
    formState: { isValid, errors },
  } = useForm<FormValues>({
    resolver: yupResolver(validationSchema) as Resolver<FormValues>,
    mode: "onChange",
    defaultValues: {
      paymentType: "",
      cardNumber: undefined,
      expireDate: undefined,
    },
  });

  // const formValues = watch();

  const prevIsValidRef = useRef<boolean>(isValid);
  const callbackRef = useRef(onFormValidChange);
  const cardNumberRef = useRef<HTMLInputElement>(null);
  const expireDateRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    callbackRef.current = onFormValidChange;
  }, [onFormValidChange]);

  useEffect(() => {
    if (prevIsValidRef.current !== isValid) {
      prevIsValidRef.current = isValid;
      callbackRef.current?.(isValid);
    }
  }, [isValid]);

  // Save payment information to context - COMMENTED OUT: Payment method data should not be saved
  // const paymentType = watch("paymentType");
  // const cardNumber = watch("cardNumber");
  // const expireDate = watch("expireDate");

  // useEffect(() => {
  //   if (
  //     isValid &&
  //     paymentType &&
  //     cardNumber &&
  //     expireDate &&
  //     expireDate.length === 5
  //   ) {
  //     try {
  //       const isoDate = convertExpirationDateToISO(expireDate);
  //       setPaymentInformation({
  //         payment_method: paymentType,
  //         card_number: cardNumber.replace(/\s/g, ""),
  //         expire_date: isoDate,
  //       });
  //     } catch {
  //       // Invalid date format, skip saving
  //     }
  //   }
  // }, [isValid, paymentType, cardNumber, expireDate, setPaymentInformation]);

  return (
    <Accordion type="single" collapsible defaultValue="item-1">
      <AccordionItem value="item-1">
        <AccordionTrigger className="text-[16px] font-bold">
          {t("paymentMethod")}
        </AccordionTrigger>
        <AccordionContent className="pt-5 flex flex-col gap-5">
          <div className="flex flex-col gap-1">
            <Label htmlFor="payment-type">
              {t("paymentType")}
              <span className="text-red-500 ml-px">*</span>
            </Label>
            <Controller
              name="paymentType"
              control={control}
              render={({ field }) => (
                <>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <SelectTrigger id="payment-type">
                      <SelectValue placeholder={t("selectPaymentMethod")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="credit-card">
                        {t("creditCardPayment")}
                      </SelectItem>
                      <SelectItem value="debit-card">
                        {t("debitCardPayment")}
                      </SelectItem>
                      <SelectItem value="paypal">{t("paypal")}</SelectItem>
                    </SelectContent>
                  </Select>
                  {errors.paymentType && (
                    <p className="text-sm text-red-500">
                      {errors.paymentType.message}
                    </p>
                  )}
                </>
              )}
            />
          </div>

          {/* Card Details Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
            {/* Card Number - Full Width */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="card-number">
                {t("cardNumber")}
                <span className="text-red-500 ml-px">*</span>
              </Label>
              <Controller
                name="cardNumber"
                control={control}
                render={({ field }) => (
                  <>
                    <Input
                      id="card-number"
                      placeholder={t("cardNumberPlaceholder")}
                      type="text"
                      maxLength={19}
                      {...field}
                      ref={(e) => {
                        field.ref(e);
                        cardNumberRef.current = e;
                      }}
                      onChange={(e) => {
                        let value = e.target.value.replace(/\D/g, "");

                        if (value.length > 16) {
                          value = value.slice(0, 16);
                        }

                        const formattedValue = value
                          .replace(/(\d{4})(?=\d)/g, "$1 ")
                          .trim();

                        const input = e.target as HTMLInputElement;
                        input.value = formattedValue;
                        field.onChange(formattedValue);
                      }}
                    />
                    {errors.cardNumber && (
                      <p className="text-sm text-red-500">
                        {errors.cardNumber.message}
                      </p>
                    )}
                  </>
                )}
              />
            </div>

            {/* CVV */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="cvv">{t("cvv")}</Label>
              <Input
                id="cvv"
                placeholder={t("cvvPlaceholder")}
                type="text"
                maxLength={3}
              />
            </div>

            {/* Expiration Date */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="expiration-date">
                {t("expirationDate")}
                <span className="text-red-500 ml-px">*</span>
              </Label>
              <Controller
                name="expireDate"
                control={control}
                render={({ field }) => (
                  <>
                    <Input
                      id="expiration-date"
                      placeholder={t("expirationDatePlaceholder")}
                      type="text"
                      maxLength={5}
                      {...field}
                      ref={(e) => {
                        field.ref(e);
                        expireDateRef.current = e;
                      }}
                      onChange={(e) => {
                        let value = e.target.value.replace(/\D/g, "");

                        if (value.length >= 2) {
                          value = value.slice(0, 2) + "/" + value.slice(2, 4);
                        }

                        const input = e.target as HTMLInputElement;
                        input.value = value;
                        field.onChange(value);

                        // Validate expiration date
                        if (value.length === 5) {
                          const [month, year] = value.split("/");
                          const monthNum = parseInt(month, 10);
                          const yearNum = parseInt(year, 10);
                          const currentDate = new Date();
                          const currentYear = currentDate.getFullYear() % 100; // Get last 2 digits
                          const currentMonth = currentDate.getMonth() + 1; // Get current month (1-12)

                          // Validate month (1-12)
                          if (monthNum < 1 || monthNum > 12) {
                            setValue("expireDate", value, {
                              shouldValidate: true,
                            });
                            return;
                          }

                          // Validate year and date
                          if (
                            yearNum < currentYear ||
                            (yearNum === currentYear && monthNum < currentMonth)
                          ) {
                            setValue("expireDate", value, {
                              shouldValidate: true,
                            });
                            return;
                          }
                        }
                      }}
                      onKeyDown={(e) => {
                        if (e.key === "Backspace") {
                          const input = e.target as HTMLInputElement;
                          if (
                            input.value.length === 3 &&
                            input.value[2] === "/"
                          ) {
                            input.value = input.value.slice(0, 2);
                            field.onChange(input.value);
                          }
                        }
                      }}
                    />
                    {errors.expireDate && (
                      <p className="text-sm text-red-500">
                        {errors.expireDate.message}
                      </p>
                    )}
                  </>
                )}
              />
            </div>
          </div>
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  );
}
