"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import Header from "@/components/main/Header";
import SellerOrderItem from "@/components/shops/orders/SellerOrderItem";
import BuyerOrderItem from "@/components/shops/orders/BuyerOrderItem";
import useAxios from "@/hooks/useAxios";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { toggleBtnClass } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import { staticIconUrl } from "@/components/main/BaseUrl";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

const FILTER_SELLER = "seller";
const FILTER_BUYER = "buyer";

type MyShop = {
  _id: string;
  name: string;
  logo?: string | null;
  status: string;
};

export default function ShopSettingsPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request } = useAxios();
  const [filter, setFilter] = useState<string>(FILTER_BUYER);
  const [myShops, setMyShops] = useState<MyShop[] | null>(null);
  const [searchText, setSearchText] = useState("");
  const [search, setSearch] = useState("");

  useEffect(() => {
    request<{ shops: MyShop[] }>("GET", "/shops/mine")
      .then((res) => {
        const shops = res?.shops || [];
        setMyShops(shops);
        if (shops.length > 0) setFilter(FILTER_SELLER);
      })
      .catch(() => setMyShops([]));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleAddShop = () => {
    if (!myShops || myShops.length === 0) {
      router.push("/shops/new/name");
      return;
    }
    // Shop(s) already exist — go add a product to the most recent one.
    router.push(`/shops/${myShops[0]._id}/products/new/name`);
  };

  const primaryShopId = myShops && myShops.length > 0 ? myShops[0]._id : null;

  const { data: sellerOrdersData, isLoading: sellerOrdersLoading } = useInfiniteScroll({
    endpoint: "/orders",
    queryKey: ["seller-orders", search],
    params: { role: "seller", ...(search ? { q: search } : {}) },
  });
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const sellerOrders: any[] =
    filter === FILTER_SELLER
      ? sellerOrdersData?.pages.flatMap((page) => page.docs || []) || []
      : [];

  const { data: buyerOrdersData, isLoading: buyerOrdersLoading } = useInfiniteScroll({
    endpoint: "/orders",
    queryKey: ["buyer-orders", search],
    params: { role: "buyer", ...(search ? { q: search } : {}) },
  });
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const buyerOrders: any[] =
    filter === FILTER_BUYER
      ? buyerOrdersData?.pages.flatMap((page) => page.docs || []) || []
      : [];

  return (
    <>
      <Header />
      <LocalePageShell>
      <Container>
        <div className="flex items-center justify-between">
          <span className="w-20 shrink-0" />
          <PageTitle>{t("settings.nav.shop")}</PageTitle>
          {filter === FILTER_SELLER ? (
            <div className="flex w-20 shrink-0 items-center justify-end gap-3">
              <button
                type="button"
                onClick={() => router.push("/settings/shop/list")}
                aria-label={t("shops.mySwitcher")}
              >
                <Image
                  width={24}
                  height={24}
                  alt=""
                  src={staticIconUrl("/images/icons/shop-add.svg")}
                  className="dark:invert"
                />
              </button>
              <button type="button" onClick={handleAddShop} aria-label={t("shops.addShop")}>
                <Image
                  width={24}
                  height={24}
                  alt=""
                  src={staticIconUrl("/images/icons/add.svg")}
                  className="dark:invert"
                />
              </button>
            </div>
          ) : (
            <span className="w-20 shrink-0" />
          )}
        </div>

        <div className="text-xs md:text-sm">
          <UserDetails />
          <div className="mx-auto mt-6 w-full max-w-md">
            <RoundedInput
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") setSearch(searchText);
              }}
              placeholder={t("shops.searchOrderPlaceholder")}
            />
          </div>
          <div className="mx-auto mt-4 grid w-full max-w-md grid-cols-2 gap-4">
            <RoundedButton
              className={cn(toggleBtnClass(filter === FILTER_SELLER), "h-9")}
              onClick={() => setFilter(FILTER_SELLER)}
            >
              {t("shops.sellerTab")}
            </RoundedButton>
            <RoundedButton
              className={cn(toggleBtnClass(filter === FILTER_BUYER), "h-9")}
              onClick={() => setFilter(FILTER_BUYER)}
            >
              {t("shops.buyerTab")}
            </RoundedButton>
          </div>

          <div className="mx-auto mt-10 w-full max-w-md">
            {filter === FILTER_SELLER ? (
              sellerOrdersLoading ? (
                <p className="text-center text-neutral-500">{t("common.loading")}</p>
              ) : sellerOrders.length === 0 ? (
                <p className="text-center text-neutral-500">
                  {t("shops.sellerOrdersEmpty")}
                </p>
              ) : (
                sellerOrders.map((order) => (
                  <SellerOrderItem key={order._id} order={order} />
                ))
              )
            ) : buyerOrdersLoading ? (
              <p className="text-center text-neutral-500">{t("common.loading")}</p>
            ) : buyerOrders.length === 0 ? (
              <p className="text-center text-neutral-500">
                {t("shops.buyerOrdersEmpty")}
              </p>
            ) : (
              buyerOrders.map((order) => (
                <BuyerOrderItem key={order._id} order={order} />
              ))
            )}
          </div>
        </div>
      </Container>
      </LocalePageShell>
    </>
  );
}
