"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 { getProductWizardId, saveProductWizardId } from "@/hooks/useProductWizardId";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type CatalogProduct = {
  _id: string;
  name: string;
  description?: string | null;
};

function ProductNamePage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams<{ shopId: string }>();
  const searchParams = useSearchParams();
  const shopId = params.shopId;
  const { request, loading } = useAxios();
  const isEditMode = searchParams.get("edit") === "1";
  const [editListingId] = useState(() =>
    isEditMode ? getProductWizardId(shopId) : null
  );

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [catalogProductId, setCatalogProductId] = useState<string | null>(null);
  const [sourceListingId, setSourceListingId] = useState<string | null>(null);
  const [suggestions, setSuggestions] = useState<CatalogProduct[]>([]);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (!editListingId) return;
    request<{ listing: { title: string; description?: string | null } }>(
      "GET",
      `/shop-products/${editListingId}`
    ).then((res) => {
      if (res?.listing) {
        setName(res.listing.title);
        setDescription(res.listing.description || "");
      }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [editListingId]);

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (!name.trim()) {
      setSuggestions([]);
      return;
    }
    debounceRef.current = setTimeout(() => {
      request<{ products: CatalogProduct[] }>(
        "GET",
        `/shop-products/catalog/search?q=${encodeURIComponent(name.trim())}`
      )
        .then((res) => setSuggestions(res?.products || []))
        .catch(() => setSuggestions([]));
    }, 350);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [name]);

  const handleNameChange = (value: string) => {
    setName(value);
    setCatalogProductId(null);
    setSourceListingId(null);
  };

  const handlePick = (product: CatalogProduct) => {
    setName(product.name);
    setDescription(product.description || "");
    setCatalogProductId(product._id);
    setSuggestions([]);
    setSourceListingId(null);
    request<{ listings: { _id: string }[] }>(
      "GET",
      `/shop-products/catalog/${product._id}/listings`,
      null,
      { noToast: true }
    )
      .then((res) => setSourceListingId(res?.listings?.[0]?._id || null))
      .catch(() => setSourceListingId(null));
  };

  const handleSubmit = async () => {
    if (!name.trim()) {
      toast.error(t("shops.productNameRequired"));
      return;
    }
    try {
      if (editListingId) {
        await request("PATCH", `/shop-products/${editListingId}`, {
          title: name.trim(),
          description: description.trim() || undefined,
        });
        router.push(`/shops/${shopId}/products/new/category`);
        return;
      }

      const response = await request<{ listing: { _id: string } }>(
        "POST",
        "/shop-products",
        {
          shopId,
          catalogProductId: catalogProductId || undefined,
          name: name.trim(),
          description: description.trim() || undefined,
          cloneFromListingId: sourceListingId || undefined,
        }
      );
      if (response?.listing?._id) {
        saveProductWizardId(shopId, response.listing._id);
      }
      router.push(`/shops/${shopId}/products/new/category`);
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

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

          <div className="relative w-full max-w-sm">
            <RoundedInput
              name="productName"
              type="text"
              placeholder={t("shops.productNamePlaceholder")}
              value={name}
              onChange={(e) => handleNameChange(e.target.value)}
            />
            {suggestions.length > 0 && (
              <div className="absolute z-10 mt-1 w-full rounded-2xl border border-neutral-200 bg-white shadow-lg dark:border-neutral-700 dark:bg-neutral-900">
                {suggestions.map((product) => (
                  <button
                    type="button"
                    key={product._id}
                    onClick={() => handlePick(product)}
                    className="block w-full px-4 py-2 text-right text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800"
                  >
                    {product.name}
                  </button>
                ))}
              </div>
            )}
          </div>

          <textarea
            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.productDescriptionPlaceholder")}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />

          {sourceListingId && (
            <p className="mt-3 w-full max-w-sm text-center text-xs text-neutral-500">
              {t("shops.prefillFromSimilarProductHint")}
            </p>
          )}
        </AuthPageContent>
        <AuthFormFooter>
          <AuthNextButton
            type="button"
            loading={loading}
            disabled={loading || !name.trim()}
            onClick={handleSubmit}
          >
            {t("shops.saveAndContinue")}
          </AuthNextButton>
        </AuthFormFooter>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default ProductNamePage;
