"use client";
import {
  UserMenuDetails,
  UserMenuSliderOptions,
} from "@/app/(home)/user/_helper/menuSliderDetails";
import { MenuSliderHandler } from "@/components/menu-slider";
import { Person } from "@/components/tanstack-table/makeData";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { getUserTableColumns } from "@/constant";
import useColumnVisibility from "@/hooks/useColumnVisibility";
import usePagination from "@/hooks/usePagination";
import useRowSelection from "@/hooks/useRowSelection";
import useTable from "@/hooks/useTable";
import Axios from "@/lib/Axios";
import useGlobalSearchStore from "@/store/useGlobalSearchStore";
import useMenuSliderStore from "@/store/useMenuSliderStore";
import { PaginationStructT } from "@/types/global";
import { UserListT } from "@/types/user";
import { useQuery } from "@tanstack/react-query";
import { ColumnDef, SortingState } from "@tanstack/react-table";
import { Pencil, Plus, Trash2 } from "lucide-react";
import Link from "next/link";
import React, { useEffect, useMemo, useState, useRef, useCallback } from "react";
import { useDebounce } from "use-debounce";

type TableHydrateT = {
  offset: number;
  limit: number;
  initData?: PaginationStructT<UserListT[]> | null;
};

export default function TableHydrate({
  offset = 0,
  limit = 10,
  initData,
}: TableHydrateT) {
  const { pagination, setPagination } = usePagination(
    Number(offset),
    Number(limit)
  );

  const { rowSelection, setRowSelection } = useRowSelection();
  const [sorting, setSorting] = useState<SortingState>([]);

  const { columnVisibility, setColumnVisibility } = useColumnVisibility();
  const [_, setData] = React.useState<Person[]>(() => []);
  const { gSearch, setGSearch } = useGlobalSearchStore();

  const [debouncedSearchQuery] = useDebounce(gSearch, 500);

  const [allData, setAllData] = useState<UserListT[]>([]);
  const [visibleCount, setVisibleCount] = useState(30); // Show 30 initially
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [isLoading, setIsLoading] = useState(true);

  const { data, error, isLoading: queryLoading, isSuccess, refetch } = useQuery({
    queryKey: ["posts", pagination, debouncedSearchQuery],
    queryFn: () => fetchData(debouncedSearchQuery),
    initialData: initData?.data || ([] as any),
  });
  
  // Create a custom refetch function that also updates the local state
  const customRefetch = useCallback(async () => {
    try {
      // Refetch the paginated data
      await refetch();
      
      // Also refetch all users to update the local state
      const resp = await Axios.get<PaginationStructT<UserListT[]>>("/users/employees/", {
        params: {
          offset: 0,
          limit: 10000, // Large number to fetch all
        },
      });
      setAllData(resp.data.data || []);
      
      // Reset visible count to show updated data immediately
      setVisibleCount(30);
    } catch (error) {
      console.error("Error refetching data:", error);
    }
  }, [refetch]);
  
  const { columns } = getUserTableColumns(customRefetch);

  const { setInnerElement, setOptionsElement } = useMenuSliderStore();

  // Add filteredData for search
  const filteredData = useMemo(() => {
    if (!debouncedSearchQuery) return allData;
    const lower = debouncedSearchQuery.toLowerCase();
    return allData.filter(row => {
      return (
        row.user?.name?.toLowerCase().includes(lower) ||
        row.user?.email?.toLowerCase().includes(lower) ||
        row.role?.name?.toLowerCase().includes(lower) ||
        row.reports_to?.user?.name?.toLowerCase().includes(lower)
      );
    });
  }, [allData, debouncedSearchQuery]);

  const memoizedData = useMemo(() => filteredData.slice(0, visibleCount), [filteredData, visibleCount]);

  const { Table, table } = useTable({
    setPagination,
    pagination,
    columns: columns,
    data: memoizedData || [],
    setData,
    rowSelection,
    setRowSelection,
    columnVisibility,
    setColumnVisibility,
    onRowClick: rowHandler,
    sorting,
    setSorting,
    rowCount: filteredData.length,
  });

  async function rowHandler(data: UserListT) {
    setColumnVisibility({
      action: false,
      status: false,
    });
    setInnerElement(UserMenuDetails(data));
    setOptionsElement(UserMenuSliderOptions(data));
    await MenuSliderHandler();
    setColumnVisibility({
      action: true,
      status: true,
    });
  }

  async function fetchData(search: string) {
    return Axios.get<PaginationStructT<UserListT[]>>("/users/employees/", {
      params: {
        offset: pagination.pageIndex * pagination.pageSize,
        limit: pagination.pageSize,
        search: search,
      },
    }).then((res) => res.data);
  }

  // Fetch all users once on mount
  useEffect(() => {
    async function fetchAllUsers() {
      setIsLoading(true);
      try {
        const resp = await Axios.get<PaginationStructT<UserListT[]>>("/users/employees/", {
          params: {
            offset: 0,
            limit: 10000, // Large number to fetch all
          },
        });
        setAllData(resp.data.data || []);
      } catch (e) {
        // Optionally handle error
      } finally {
        setIsLoading(false);
      }
    }
    fetchAllUsers();
  }, []);

  // Scroll handler to reveal more items
  useEffect(() => {
    const container = tableContainerRef.current;
    if (!container) return;
    const handleScroll = () => {
      if (
        container.scrollTop + container.clientHeight >=
        container.scrollHeight - 100
      ) {
        setVisibleCount((prev) => Math.min(prev + 30, allData.length));
      }
    };
    container.addEventListener("scroll", handleScroll);
    return () => container.removeEventListener("scroll", handleScroll);
  }, [allData.length]);

  // Reset visibleCount when search query changes
  useEffect(() => {
    setVisibleCount(10);
  }, [debouncedSearchQuery]);

  useEffect(() => {
    // document.documentElement.style.setProperty("--row-width", "100rem");

    return () => {
      setGSearch("");
    };
  }, []);

  return (
    <div className="" ref={tableContainerRef} style={{ maxHeight: "70vh", overflowY: "auto" }}>
      <div className="my-5 flex gap-1 items-center">
        <Link href="user/manage-user">
          <Button className="bg-brownish hover:bg-yellowish">
            <p className="mr-2">Add User</p> <Plus />
          </Button>
        </Link>

        <div className="ml-10 w-96">
          <Input
            placeholder="search"
            onChange={(e) => setGSearch(e.currentTarget.value)}
          />
        </div>
      </div>
      <div className="relative">
        {isLoading ? (
          <div className="text-center py-2">Loading...</div>
        ) : (
          <Table />
        )}
        {/* Loader for infinite scroll */}
        {visibleCount < filteredData.length && !isLoading && (
          <div className="text-center py-2 text-gray-400 text-xs">Loading more...</div>
        )}
      </div>
    </div>
  );
}
