"use client";

import { useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";

import { productApi } from "@/api/product-api.service";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { removeFalsyValues } from "@/features/app";
import { mapToIPost, type IPost } from "@/lib/utils";
import MessageService from "@/services/message.service";
import {
  ChevronLeft,
  ChevronRight,
  Edit,
  Eye,
  EyeOff,
  MoreHorizontal,
  Search,
  X,
} from "lucide-react";
import { useDebounce } from "use-debounce";
import Loader from "./loader";
import ProductModal from "./product-modal";

export function PostTable() {
  const msg = new MessageService("popup");

  const [searchTerm, setSearchTerm] = useState("");
  const [filter, setFilter] = useState<Record<string, any>>({});
  const [statusFilter, setStatusFilter] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);

  const [search] = useDebounce(searchTerm, 400);

  const queryKey = useMemo(
    () => ["products", { currentPage, search, filter }],
    [currentPage, search, filter]
  );

  // --- React Query fetch ---
  const { data: rawProducts, isLoading } = useQuery({
    queryKey,
    queryFn: async () => {
      const { data } = await productApi.index(
        removeFalsyValues({
          skip: (currentPage - 1) * productApi.item_per_page,
          where: {
            productModelCode: searchTerm,
            status_listing:
              filter?.statusFilter === "all" ? undefined : filter.statusFilter,
          },
        })
      );
      return data;
    },
  });

  const { data: publistedProducts } = useQuery({
    queryKey: ["publised-products"],
    queryFn: async () => {
      const { data } = await productApi.getPublistedProducts();
      return data ?? [];
    },
    staleTime: 0, // luôn coi là stale -> gọi lại API mỗi lần mount
    refetchOnMount: "always",
  });

  const data: IPost[] = useMemo(() => {
    if (!rawProducts || !rawProducts?.data) return [];
    return rawProducts?.data.map((item: any) => mapToIPost(item));
  }, [rawProducts]);

  const formatPrice = (price: number) =>
    new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
    }).format(price);

  const clearFilters = () => {
    setSearchTerm("");
    setFilter({});
    setCurrentPage(1);
  };

  const activeFiltersCount = [filter.statusFilter, searchTerm !== ""].filter(
    Boolean
  ).length;

  const totalPages = useMemo(() => {
    if (!rawProducts?.total) return 0;

    return Math.ceil(rawProducts.total / productApi.item_per_page);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [rawProducts?.total, productApi.item_per_page]);

  // --- reset page when filter changes ---
  // eslint-disable-next-line react-hooks/exhaustive-deps
  // useMemo(() => setCurrentPage(1), [filteredPosts.length]);

  const from = useMemo(() => {
    return (currentPage - 1) * productApi.item_per_page + 1;
  }, [currentPage]);

  const to = useMemo(() => {
    return Math.min(
      currentPage * productApi.item_per_page,
      rawProducts?.total ?? 0
    );
  }, [currentPage, rawProducts]);

  // popup.ts
  const handleActionListing = async (data: IPost) => {
    const res = await productApi.get(data);

    if (!res || !res.data?.data) return;

    if (data.status) {
      msg.send("content", "popup-to-content", {
        type: "unlist",
        data: data,
      });
    } else {
      console.log({
        a: { ...data, ...mapToIPost({ ...res.data?.data }) },
        b: data,
      });
      msg.send("content", "popup-to-content", {
        type: "publist",
        data: { ...data, images: mapToIPost({ ...res.data?.data }).images },
      });
    }
  };

  // const handleUnListing = async (data: IPost) => {
  //   msg.send("content", "popup-to-content", {
  //     type: "unlist",
  //     data: data,
  //   });
  // };

  // const handleRePublist = async (data: IPost) => {
  //   const res = await productApi.get(data);

  //   if (!res || !res.data?.data) return;

  //   msg.send("content", "popup-to-content", {
  //     type: "re-publist",
  //     data: mapToIPost({ ...data, ...res.data?.data }),
  //   });
  // };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>

        <div className="flex items-center gap-2">
          <Button
            variant={filter.statusFilter === "listed" ? "default" : "ghost"}
            onClick={() => setFilter({ statusFilter: "listed" })}
          >
            Listed
          </Button>
          <Button
            variant={filter.statusFilter === "unlisted" ? "default" : "ghost"}
            onClick={() => setFilter({ statusFilter: "unlisted" })}
          >
            Un listed
          </Button>

          {activeFiltersCount > 0 && (
            <Button onClick={clearFilters} size={"icon"}>
              <X />
            </Button>
          )}
        </div>
      </div>

      <div className="flex items-center justify-between text-sm text-muted-foreground">
        <span>
          Showing {from}-{to} of {rawProducts?.total ?? 0} products
        </span>
      </div>

      <div className="rounded-md border overflow-x-auto relative">
        {isLoading && (
          <div className="absolute inset-0 bg-[rgba(255,255,255,.6)] flex items-center justify-center z-10">
            <Loader />
          </div>
        )}

        <Table className="min-w-[500px]">
          <TableHeader>
            <TableRow>
              <TableHead className="min-w-[200px]">Name</TableHead>
              <TableHead className="w-[80px]">Price</TableHead>
              <TableHead className="w-[80px]">Status</TableHead>
              <TableHead className="w-[80px] text-center sticky right-0 bg-background border-l shadow-[-4px_0_8px_rgba(0,0,0,0.1)]">
                Actions
              </TableHead>
            </TableRow>
          </TableHeader>

          <TableBody className="relative">
            {data.length === 0 && !isLoading ? (
              <TableRow>
                <TableCell
                  colSpan={10}
                  className="text-center py-8 text-muted-foreground"
                >
                  No products found
                </TableCell>
              </TableRow>
            ) : (
              data.map((post) => {
                const status = publistedProducts.some((item: any) =>
                  item.title.includes(post.sku)
                );

                post.status = status;

                return (
                  <TableRow key={post.id}>
                    <TableCell className="font-medium">
                      <div
                        className="truncate max-w-[200px] w-fit"
                        title={post.title}
                      >
                        {post.title}
                      </div>
                      <div
                        className="text-sm text-muted-foreground truncate max-w-[200px]"
                        title={post.description}
                      >
                        {post.description}
                      </div>
                    </TableCell>
                    <TableCell className="font-semibold">
                      {formatPrice(post.price)}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">
                        {post?.status ? "Listed" : "Unlisted"}
                      </Badge>
                    </TableCell>

                    <TableCell className="text-center sticky right-0 bg-background border-l shadow-[-4px_0_8px_rgba(0,0,0,0.1)]">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0 mx-auto"
                          >
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <ProductModal data={post}>
                            <DropdownMenuItem
                              onSelect={(e) => {
                                e.preventDefault(); // Ngăn dropdown đóng lại
                                e.stopPropagation();
                              }}
                            >
                              <Edit className="h-4 w-4 mr-2" /> Edit
                            </DropdownMenuItem>
                          </ProductModal>
                          <DropdownMenuItem
                            onClick={() => handleActionListing(post)}
                          >
                            {post.status ? (
                              <EyeOff className="h-4 w-4 mr-2" />
                            ) : (
                              <Eye className="h-4 w-4 mr-2" />
                            )}
                            {post.status ? "Unlist" : "List"}
                          </DropdownMenuItem>
                          {/* <DropdownMenuItem onClick={() => handleUnListing(post)}>
                          unList
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleRePublist(post)}>
                          re publist
                        </DropdownMenuItem> */}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-end gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            Previous
          </Button>

          <div className="flex items-center gap-1">
            {totalPages <= 7 ? (
              // Show all pages if 7 or fewer
              Array.from({ length: totalPages }, (_, i) => (
                <Button
                  key={i + 1}
                  variant={currentPage === i + 1 ? "default" : "outline"}
                  size="sm"
                  onClick={() => setCurrentPage(i + 1)}
                  className="w-8 h-8 p-0"
                >
                  {i + 1}
                </Button>
              ))
            ) : (
              // Show pages with ellipsis for more than 7 pages
              <>
                {/* First page */}
                <Button
                  variant={currentPage === 1 ? "default" : "outline"}
                  size="sm"
                  onClick={() => setCurrentPage(1)}
                  className="w-8 h-8 p-0"
                >
                  1
                </Button>

                {/* Left ellipsis */}
                {currentPage > 4 && (
                  <span className="px-2 text-muted-foreground">...</span>
                )}

                {/* Middle pages */}
                {Array.from({ length: 3 }, (_, i) => {
                  let pageNum;
                  if (currentPage <= 4) {
                    pageNum = i + 2;
                  } else if (currentPage >= totalPages - 3) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 1 + i;
                  }

                  if (pageNum > 1 && pageNum < totalPages) {
                    return (
                      <Button
                        key={pageNum}
                        variant={
                          currentPage === pageNum ? "default" : "outline"
                        }
                        size="sm"
                        onClick={() => setCurrentPage(pageNum)}
                        className="w-8 h-8 p-0"
                      >
                        {pageNum}
                      </Button>
                    );
                  }
                  return null;
                }).filter(Boolean)}

                {/* Right ellipsis */}
                {currentPage < totalPages - 3 && (
                  <span className="px-2 text-muted-foreground">...</span>
                )}

                {/* Last page */}
                <Button
                  variant={currentPage === totalPages ? "default" : "outline"}
                  size="sm"
                  onClick={() => setCurrentPage(totalPages)}
                  className="w-8 h-8 p-0"
                >
                  {totalPages}
                </Button>
              </>
            )}
          </div>

          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              setCurrentPage((prev) => Math.min(totalPages, prev + 1))
            }
            disabled={currentPage === totalPages}
          >
            Next
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      )}
    </div>
  );
}
