"use client";

import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import Header from "@/components/main/Header";
import TabNavigation from "@/components/TabNavigation";
import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import ExpandableBio from "@/components/profile/ExpandableBio";
import ShareShopModal from "@/components/shops/ShareShopModal";
import ShopContactInfoModal from "@/components/shops/ShopContactInfoModal";
import ShopMyOrdersModal from "@/components/shops/ShopMyOrdersModal";
import useAxios from "@/hooks/useAxios";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { useUser } from "@/hooks/useUser";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";
import { profileActionBtnClass } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import { IShopProductListing } from "@/types/types";
import dynamic from "next/dynamic";
import Image from "next/image";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

const LocationModal = dynamic(
  () => import("@/components/models/ModelPage/LocationModal"),
  { ssr: false }
);

type PublicShop = {
  _id: string;
  name: string;
  logo?: string | null;
  description?: string | null;
  has_physical_location?: boolean;
  province?: { name: string } | null;
  city?: { name: string } | null;
  address?: string | null;
  lat?: string | null;
  lng?: string | null;
  contact?: {
    mobile?: string | null;
    landline?: string | null;
    telegram?: string | null;
    whatsapp?: string | null;
    instagram?: string | null;
  } | null;
  response_schedule?: { day: string; start_time?: string | null; end_time?: string | null }[];
  owner?: {
    _id: string;
    user_name: string;
  } | null;
  productCount: number;
  rating: { average: number; count: number };
  isFollowing: boolean;
  followedAt?: string | null;
  isOwner: boolean;
  createdAt?: string;
};

type PerformanceTier = "weak" | "average" | "good" | "veryGood" | "excellent";

function getPerformanceTier(percent: number): PerformanceTier {
  if (percent < 60) return "weak";
  if (percent < 70) return "average";
  if (percent < 80) return "good";
  if (percent < 90) return "veryGood";
  return "excellent";
}

function monthsSince(dateStr: string): number {
  const diffMs = Date.now() - new Date(dateStr).getTime();
  return Math.floor(diffMs / (1000 * 60 * 60 * 24 * 30));
}

export default function ShopProfileClient() {
  const { t, i18n } = useTranslation("common");
  const isFa = (i18n.language || "fa").toLowerCase().startsWith("fa");
  const router = useRouter();
  const params = useParams<{ shopId: string }>();
  const shopId = params.shopId;
  const { request } = useAxios();
  const requireAuth = useRequireAuth();
  const currentUser = useUser();

  const [shop, setShop] = useState<PublicShop | null>(null);
  const [isFollowing, setIsFollowing] = useState(false);
  const [followedAt, setFollowedAt] = useState<string | null>(null);
  const [followLoading, setFollowLoading] = useState(false);
  const [showContactModal, setShowContactModal] = useState(false);
  const [showOrdersModal, setShowOrdersModal] = useState(false);
  const [showLocationModal, setShowLocationModal] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);

  useEffect(() => {
    request<{ shop: PublicShop }>("GET", `/shops/public/${shopId}`)
      .then((res) => {
        const data = res?.shop || null;
        setShop(data);
        setIsFollowing(Boolean(data?.isFollowing));
        setFollowedAt(data?.followedAt || null);
      })
      .catch(() => setShop(null));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shopId]);

  const { data, isLoading } = useInfiniteScroll({
    endpoint: "/shop-products",
    queryKey: ["shop-products", shopId],
    params: { shopId },
  });
  const listings: IShopProductListing[] =
    data?.pages.flatMap((page) => page.docs || []) || [];

  const toggleFollow = async () => {
    if (!requireAuth() || !shop || followLoading) return;
    const nextFollowing = !isFollowing;
    setIsFollowing(nextFollowing);
    setFollowLoading(true);
    try {
      const res = await request<{ is_following: boolean; followed_at: string | null }>(
        "POST",
        `/shops/${shop._id}/follow`,
        {}
      );
      setIsFollowing(res?.is_following ?? nextFollowing);
      setFollowedAt(res?.followed_at || null);
      toast.success(
        (res?.is_following ?? nextFollowing)
          ? t("shops.shopFollowSuccess")
          : t("shops.shopUnfollowSuccess")
      );
    } catch {
      setIsFollowing(!nextFollowing);
    } finally {
      setFollowLoading(false);
    }
  };

  const handleMessage = () => {
    if (!requireAuth() || !shop || !currentUser?._id) return;
    router.push(`/settings/chats/shop/${shop._id}/${currentUser._id}`);
  };

  if (!shop) return null;

  const percent =
    shop.rating.count > 0 ? Math.round((shop.rating.average / 5) * 100) : null;
  const performanceTier = percent != null ? getPerformanceTier(percent) : null;
  const hasDescription = Boolean(shop.description?.trim());

  const shopTenureLabel = shop.createdAt
    ? monthsSince(shop.createdAt) < 1
      ? t("shops.lessThanOneMonth")
      : t("shops.monthsCount", { count: monthsSince(shop.createdAt) })
    : t("shops.followButton");

  const followLabel = isFollowing
    ? followedAt
      ? monthsSince(followedAt) < 1
        ? t("shops.lessThanOneMonth")
        : t("shops.monthsCount", { count: monthsSince(followedAt) })
      : t("shops.unfollowButton")
    : shopTenureLabel;

  return (
    <>
      <Header />
      <LocalePageShell>
        <Container className="pb-28">
          <div className="mx-auto w-full max-w-md" dir={isFa ? "ltr" : "rtl"}>
            <div className="flex w-full items-center justify-between py-2">
              <div className="flex flex-col items-center text-xs md:text-sm">
                <div className="mt-2 flex gap-5">
                  <div className="flex flex-col items-center font-semibold max-sm:text-[10px]">
                    <span>{shop.productCount}</span>
                    <span>{t("shops.productsLabel")}</span>
                  </div>
                  <div className="flex flex-col items-center font-semibold text-[#0C8002] max-sm:text-[10px]">
                    <span>
                      {performanceTier
                        ? t(`shops.performance.${performanceTier}`)
                        : t("shops.underReview")}
                    </span>
                    <span>{t("shops.performanceLabel")}</span>
                  </div>
                  <div className="flex flex-col items-center font-semibold text-[#3A59A9] max-sm:text-[10px]">
                    <span>{percent != null ? `${percent}%` : t("shops.newShop")}</span>
                    <span>{t("shops.satisfactionLabel")}</span>
                  </div>
                </div>
              </div>
              <ProfileAvatar
                src={shop.logo}
                alt={shop.name}
                size="md"
                rounded="xl"
                className="md:h-[120px] md:w-[120px]"
              />
            </div>

            <div className="grid w-full grid-cols-3 items-end py-2 text-xs font-semibold md:text-sm">
              <div className="flex items-center">
                <span>{shop.rating.count > 0 ? shop.rating.average.toFixed(1) : "0"}</span>
                <Image width={22} height={22} alt="star icon" src="/images/icons/star1.png" />
              </div>
              <div className="flex items-center justify-center">
                <span>{shop.rating.count}</span>
                <Image width={22} height={22} alt="rate icon" src="/images/icons/medal-star.png" />
              </div>
              <div
                className={cn(
                  "flex min-w-0 max-w-full flex-col",
                  isFa ? "items-end" : "items-start"
                )}
              >
                <h3
                  className={cn(
                    "max-w-full truncate whitespace-nowrap",
                    isFa ? "text-right" : "text-left"
                  )}
                >
                  {shop.name}
                </h3>
              </div>
            </div>

            <div className="w-full py-2 text-xs font-semibold md:text-sm">
              <div
                className={cn(
                  "flex w-full gap-3",
                  hasDescription
                    ? "items-baseline justify-between"
                    : "items-center justify-end"
                )}
              >
                {hasDescription ? (
                  <div
                    className={cn(
                      "min-w-0 flex-1 leading-6",
                      isFa ? "text-right" : "text-left"
                    )}
                  >
                    <ExpandableBio
                      bio={shop.description}
                      className={cn("leading-6", isFa ? "text-right" : "text-left")}
                    />
                  </div>
                ) : null}
                <div
                  className={cn(
                    "shrink-0 leading-6 text-[#387E65]",
                    isFa ? "text-right" : "text-left"
                  )}
                >
                  {shop.has_physical_location ? t("shops.inPerson") : t("shops.onlineOnly")}
                </div>
              </div>
            </div>

            <div className="mt-2 grid grid-cols-3 gap-1 md:mt-4 md:gap-4">
              <button type="button" onClick={handleMessage} className={profileActionBtnClass}>
                {t("shops.sendMessage")}
              </button>
              <button
                type="button"
                onClick={() => setShowOrdersModal(true)}
                className={profileActionBtnClass}
              >
                {t("shops.myOrdersFromShop")}
              </button>
              <button
                type="button"
                onClick={() => setShowContactModal(true)}
                className={profileActionBtnClass}
              >
                {t("shops.contactInfoButton")}
              </button>
              <button
                type="button"
                onClick={() => void toggleFollow()}
                disabled={followLoading}
                className={profileActionBtnClass}
              >
                {followLabel}
              </button>
              {shop.has_physical_location && (
                <button
                  type="button"
                  onClick={() => setShowLocationModal(true)}
                  className={profileActionBtnClass}
                >
                  {t("shops.showLocation")}
                </button>
              )}
              <button
                type="button"
                onClick={() => setShowShareModal(true)}
                className={profileActionBtnClass}
              >
                {t("shops.share.title")}
              </button>
            </div>

            <div className="mt-4">
              {isLoading ? (
                <p className="py-16 text-center text-sm text-neutral-500">
                  {t("common.loading")}
                </p>
              ) : listings.length === 0 ? (
                <p className="py-16 text-center text-sm text-neutral-500">
                  {t("shops.noProductsYet")}
                </p>
              ) : (
                <div className="grid grid-cols-3 gap-0.5 sm:gap-1">
                  {listings.map((listing) => {
                    const primaryImage =
                      listing.images?.[listing.primaryImageIndex] || listing.images?.[0];
                    const tileId = listing.tileId || listing._id;
                    return (
                      <button
                        key={tileId}
                        type="button"
                        onClick={() =>
                          router.push(`/shops/profile/${shopId}/reel/${tileId}`)
                        }
                        className="relative aspect-square overflow-hidden rounded-md bg-neutral-100 sm:rounded-xl dark:bg-neutral-800"
                      >
                        {listing.isTaggedPost && (
                          <span className="absolute right-1 top-1 z-10 rounded-full bg-black/50 px-1.5 py-0.5 text-[9px] font-semibold text-white">
                            {t("shops.taggedPostBadge")}
                          </span>
                        )}
                        {primaryImage && (
                          <Image
                            src={IMAGE_BASE_URL + primaryImage}
                            alt={listing.title}
                            fill
                            className="object-cover"
                            sizes="33vw"
                            unoptimized
                          />
                        )}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </Container>
      </LocalePageShell>
      <TabNavigation currentPage="/settings" />

      <ShareShopModal
        open={showShareModal}
        onClose={() => setShowShareModal(false)}
        shopId={shop._id}
        shopName={shop.name}
        shopLogo={shop.logo}
        responseSchedule={shop.response_schedule}
      />
      <ShopContactInfoModal
        open={showContactModal}
        onClose={() => setShowContactModal(false)}
        contactInfo={shop.contact || {}}
      />
      <ShopMyOrdersModal
        open={showOrdersModal}
        onClose={() => setShowOrdersModal(false)}
        shopId={shop._id}
      />
      {showLocationModal && shop.has_physical_location && (
        <LocationModal
          isOpen={showLocationModal}
          onClose={() => setShowLocationModal(false)}
          location={{
            address: shop.address || undefined,
            lat: shop.lat || undefined,
            lng: shop.lng || undefined,
            city: shop.city || undefined,
            province: shop.province || undefined,
          }}
        />
      )}
    </>
  );
}
