"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import RoundedInput from "@/components/elements/RoundedInput";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import {
  getBookingWizardId,
  saveBookingWizardId,
} from "@/hooks/useBookingWizardId";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

function BookingNamePage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const searchParams = useSearchParams();
  const { request, loading } = useAxios();
  const isEditMode = searchParams.get("edit") === "1";
  const [editConfigId] = useState(() =>
    isEditMode ? getBookingWizardId() : null
  );

  const formik = useFormik({
    initialValues: { name: "" },
    validationSchema: yup.object({
      name: yup.string().trim().required(t("booking.nameRequired")),
    }),
    onSubmit: async (values) => {
      try {
        if (editConfigId) {
          router.push("/settings/booking/new/services?edit=1");
          return;
        }

        const response = await request<{ configId: string }>(
          "POST",
          "/bookings/draft",
          { name: values.name.trim() }
        );
        if (response?.configId) {
          saveBookingWizardId(String(response.configId));
        }
        router.push("/settings/booking/new/services");
      } catch (err: unknown) {
        const message =
          (err as { response?: { data?: { message?: string } } })?.response
            ?.data?.message || t("shops.unknownError");
        toast.error(message);
      }
    },
  });

  useEffect(() => {
    if (!editConfigId) return;
    request<{ config: { name: string } }>(
      "GET",
      `/bookings/${editConfigId}`
    ).then((res) => {
      if (!res?.config) return;
      formik.setValues({ name: res.config.name || "" });
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [editConfigId]);

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <form
          onSubmit={formik.handleSubmit}
          className="flex w-full flex-1 flex-col items-center pb-28"
        >
          <AuthPageContent>
            <span className="text-xl font-bold mb-4">
              {t("booking.nameTitle")}
            </span>
            <RoundedInput
              name="name"
              type="text"
              className={`max-w-[290px] text-center ${
                formik.touched.name && formik.errors.name
                  ? "border-red-500 dark:border-red-500"
                  : ""
              }`}
              placeholder={t("booking.namePlaceholder")}
              value={formik.values.name}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.touched.name && formik.errors.name && (
              <small className="mt-2 block text-center text-red-500">
                {formik.errors.name}
              </small>
            )}
          </AuthPageContent>
          <AuthFormFooter className="fixed inset-x-0 bottom-[calc(5.5rem+env(safe-area-inset-bottom))] z-20 mx-auto mt-0 w-full max-w-xl bg-background/95 px-4 py-3 backdrop-blur-sm">
            <AuthNextButton
              type="submit"
              loading={loading}
              disabled={loading || !formik.values.name.trim()}
            >
              {t("shops.saveAndContinue")}
            </AuthNextButton>
          </AuthFormFooter>
        </form>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default BookingNamePage;
