"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { useShopWizardId } from "@/hooks/useShopWizardId";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

function ShopLogoPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const shopId = useShopWizardId();
  const [logoPreview, setLogoPreview] = useState<string | null>(null);
  const [logoFile, setLogoFile] = useState<File | null>(null);

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

  const selectImage = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    setLogoFile(file);
    const reader = new FileReader();
    reader.onload = (e) => setLogoPreview(e.target?.result as string);
    reader.readAsDataURL(file);
  };

  const goNext = () => router.push("/shops/new/shipping");

  const handleUpload = async () => {
    if (!logoFile || !shopId) {
      toast.error(t("shops.logoRequired"));
      return;
    }
    const formData = new FormData();
    formData.append("logo", logoFile);
    try {
      await request("PATCH", `/shops/${shopId}/logo`, formData);
      goNext();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  if (!shopId) return null;

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <AuthPageContent>
          <span className="text-xl font-bold mb-4">{t("shops.logoTitle")}</span>

          <div className="relative aspect-square w-[200px] bg-gray-200 rounded-3xl overflow-hidden mb-4">
            {logoPreview ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={logoPreview}
                alt="shop logo"
                className="h-full w-full object-cover"
              />
            ) : (
              <label
                htmlFor="shopLogoInput"
                className="flex h-full w-full cursor-pointer items-center justify-center"
              >
                <Image
                  src="/images/icons/gallery-add.svg"
                  width={100}
                  height={100}
                  alt="add logo icon"
                />
              </label>
            )}
          </div>

          <input
            id="shopLogoInput"
            type="file"
            accept="image/*"
            className="hidden"
            onChange={selectImage}
          />

          <AuthNextButton className="mt-4" type="button">
            <label className="h-full w-full cursor-pointer" htmlFor="shopLogoInput">
              {t("shops.selectLogo")}
            </label>
          </AuthNextButton>
        </AuthPageContent>

        <AuthFormFooter onSkip={goNext} skipDisabled={loading}>
          <AuthNextButton onClick={handleUpload} loading={loading} disabled={loading}>
            {t("shops.saveAndContinue")}
          </AuthNextButton>
        </AuthFormFooter>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default ShopLogoPage;
