"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 { getShopWizardId, saveShopWizardId } from "@/hooks/useShopWizardId";
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 ShopNamePage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const searchParams = useSearchParams();
  const { request, loading } = useAxios();
  const isEditMode = searchParams.get("edit") === "1";
  const [editShopId] = useState(() => (isEditMode ? getShopWizardId() : null));

  const formik = useFormik({
    initialValues: { name: "", description: "" },
    validationSchema: yup.object({
      name: yup.string().trim().required(t("shops.nameRequired")),
    }),
    onSubmit: async (values) => {
      try {
        if (editShopId) {
          await request("PATCH", `/shops/${editShopId}/basic`, {
            name: values.name.trim(),
            description: values.description.trim() || undefined,
          });
          router.push("/shops/new/logo");
          return;
        }

        const response = await request<{ shopId: string }>(
          "POST",
          "/shops/draft",
          { name: values.name.trim(), description: values.description.trim() || undefined }
        );
        if (response?.shopId) {
          saveShopWizardId(String(response.shopId));
        }
        router.push("/shops/new/logo");
      } catch (err: unknown) {
        const message =
          (err as { response?: { data?: { message?: string } } })?.response
            ?.data?.message || t("shops.unknownError");
        toast.error(message);
      }
    },
  });

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

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <form
          onSubmit={formik.handleSubmit}
          className="flex w-full flex-1 flex-col items-center"
        >
          <AuthPageContent>
            <span className="text-xl font-bold mb-4">{t("shops.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("shops.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>
            )}

            <textarea
              name="description"
              className="mt-4 h-28 w-full max-w-sm rounded-3xl border border-neutral-300 bg-white p-4 font-medium dark:border-neutral-600 dark:bg-neutral-950 dark:text-neutral-50"
              placeholder={t("shops.descriptionPlaceholder")}
              value={formik.values.description}
              onChange={formik.handleChange}
            />
          </AuthPageContent>
          <AuthFormFooter>
            <AuthNextButton
              type="submit"
              loading={loading}
              disabled={loading || !formik.values.name.trim()}
            >
              {t("shops.saveAndContinue")}
            </AuthNextButton>
          </AuthFormFooter>
        </form>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default ShopNamePage;
