"use client";

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

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

export default function BasicInformation({
  onFormValidChange,
}: BasicInformationProps) {
  const t = useTranslations("ReservationPage");
  const tValidation = useTranslations("Validation");
  const bookingContext = useBooking();

  const validationSchema = yup.object({
    firstName: yup
      .string()
      .required(tValidation("firstNameRequired"))
      .min(1, tValidation("firstNameRequired")),
    lastName: yup
      .string()
      .required(tValidation("firstNameRequired"))
      .min(1, tValidation("firstNameRequired")),
    phone: yup
      .string()
      .required(tValidation("phoneRequired"))
      .min(1, tValidation("phoneRequired")),
    email: yup
      .string()
      .required(tValidation("emailRequired"))
      .email(tValidation("emailInvalid")),
  });

  type FormValues = yup.InferType<typeof validationSchema>;

  const {
    control,
    watch,
    formState: { isValid, errors },
  } = useForm<FormValues>({
    resolver: yupResolver(validationSchema),
    mode: "onChange",
    defaultValues: {
      firstName: "",
      lastName: "",
      phone: "",
      email: "",
    },
  });

  const formValues = watch();

  const prevIsValidRef = useRef<boolean>(isValid);
  const callbackRef = useRef(onFormValidChange);
  const prevFormValuesRef = useRef<string>("");
  const setBasicInfoRef = useRef(bookingContext?.setBasicInformation);

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

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

  useEffect(() => {
    if (bookingContext) {
      setBasicInfoRef.current = bookingContext.setBasicInformation;
    }
  }, [bookingContext]);

  useEffect(() => {
    if (
      isValid &&
      formValues.firstName &&
      formValues.lastName &&
      formValues.phone &&
      formValues.email &&
      setBasicInfoRef.current
    ) {
      const formValuesString = JSON.stringify({
        firstName: formValues.firstName,
        lastName: formValues.lastName,
        phone: formValues.phone,
        email: formValues.email,
      });

      if (prevFormValuesRef.current !== formValuesString) {
        prevFormValuesRef.current = formValuesString;
        setBasicInfoRef.current({
          first_name: formValues.firstName,
          last_name: formValues.lastName,
          phone: formValues.phone,
          email: formValues.email,
        });
      }
    }
  }, [
    isValid,
    formValues.firstName,
    formValues.lastName,
    formValues.phone,
    formValues.email,
  ]);

  if (!bookingContext) {
    console.error("BookingContext is not available");
    return null;
  }

  return (
    <Accordion type="single" collapsible defaultValue="item-1">
      <AccordionItem value="item-1">
        <AccordionTrigger className="text-[16px] font-bold">
          {t("basicInformation")}
        </AccordionTrigger>
        <AccordionContent className="pt-5 grid grid-cols-1 sm:grid-cols-2 gap-5">
          <div className="flex flex-col gap-1">
            <Label htmlFor="firstName">
              {t("firstName")}
              <span className="text-red-500 ml-px">*</span>
            </Label>
            <Controller
              name="firstName"
              control={control}
              render={({ field }) => (
                <>
                  <Input
                    id="firstName"
                    placeholder={t("firstName")}
                    {...field}
                  />
                  {errors.firstName && (
                    <p className="text-sm text-red-500">
                      {errors.firstName.message}
                    </p>
                  )}
                </>
              )}
            />
          </div>

          <div className="flex flex-col gap-1">
            <Label htmlFor="lastName">
              {t("lastName")}
              <span className="text-red-500 ml-px">*</span>
            </Label>
            <Controller
              name="lastName"
              control={control}
              render={({ field }) => (
                <>
                  <Input id="lastName" placeholder={t("lastName")} {...field} />
                  {errors.lastName && (
                    <p className="text-sm text-red-500">
                      {errors.lastName.message}
                    </p>
                  )}
                </>
              )}
            />
          </div>

          <div className="flex flex-col gap-1">
            <Label htmlFor="phone">
              {t("yourPhoneNumber")}
              <span className="text-red-500 ml-px">*</span>
            </Label>
            <Controller
              name="phone"
              control={control}
              render={({ field }) => (
                <>
                  <Input
                    id="phone"
                    placeholder={t("yourPhoneNumber")}
                    {...field}
                  />
                  {errors.phone && (
                    <p className="text-sm text-red-500">
                      {errors.phone.message}
                    </p>
                  )}
                </>
              )}
            />
          </div>

          <div className="flex flex-col gap-1">
            <Label htmlFor="email">
              {t("yourEmailAddress")}
              <span className="text-red-500 ml-px">*</span>
            </Label>
            <Controller
              name="email"
              control={control}
              render={({ field }) => (
                <>
                  <Input
                    id="email"
                    type="email"
                    placeholder={t("yourEmailAddress")}
                    {...field}
                  />
                  {errors.email && (
                    <p className="text-sm text-red-500">
                      {errors.email.message}
                    </p>
                  )}
                </>
              )}
            />
          </div>
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  );
}
