import Button from "@/UI/Button";
import CSV from "@/UI/CSV";
import Menu from "@/UI/Menu";
import Pagination from "@/UI/Pagination";
import { loadAllStoreByUser } from "@/redux/rtk/features/store/storeSlice";
import { Popover, Select, Table } from "antd";
import { useEffect, useState } from "react";
import { BsThreeDotsVertical } from "react-icons/bs";
import { useDispatch, useSelector } from "react-redux";
import PrintPdf from "../CommonUi/PrintPdf";
import ColVisibilityDropdown from "../Shared/ColVisibilityDropdown";

const TableComponent = ({
  columns,
  list,
  total,
  loading,
  paginatedThunk,
  children,
  query,
  setProductList,
  storeId,
  setStoreId,
}) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const {
    list: store,
    loading: storeLoading,
    defaultStore,
  } = useSelector((state) => state.store);
  const dispatch = useDispatch();

  const onSelectChange = (newSelectedRowKeys, second) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setProductList(second);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const fetchData = (page, count) => {
    dispatch(paginatedThunk({ ...query, status: true, page, count }));
  };

  const handleChangeStore = (value) => {
    setStoreId(value);
    dispatch(paginatedThunk({ ...query, status: true, storeId: value }));
  };

  // column select
  const [columnsToShow, setColumnsToShow] = useState([]);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    setColumnsToShow(columns);

    // Detect screen size for responsiveness
    const handleResize = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    handleResize();
    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [columns?.length]);

  useEffect(() => {
    dispatch(loadAllStoreByUser());
  }, [dispatch]);

  useEffect(() => {
    if (defaultStore) {
      setStoreId(defaultStore.id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultStore]);

  const columnsToShowHandler = (val) => {
    setColumnsToShow(val);
  };

  return (
    <>
      <div className='mt-2'>
        {/* Mobile View */}
        {isMobile ? (
          <div className='p-4 sm:p-6'>
            {/* Store Select and Filter */}
            <div className='flex justify-between items-center mb-3'>
              {/* Store Select */}
              <div className='filterTag min-w-[130px] max-w-[150px]'>
                <Select
                  placeholder='Select a store'
                  mode={"single"}
                  loading={storeLoading}
                  showSearch={false}
                  value={storeId}
                  onChange={handleChangeStore}
                  maxTagPlaceholder={(item) => (
                    <div className=''>{item.length} Selected</div>
                  )}
                  maxTagCount={0}
                >
                  {store?.map((option) => (
                    <Select.Option key={option.id} value={option.id}>
                      {option.name}
                    </Select.Option>
                  ))}
                </Select>
              </div>

              {/* 3-Dot Menu */}
              <Popover
                content={
                  <div className='flex flex-col gap-2'>
                    <ColVisibilityDropdown
                      options={columns}
                      columns={columns}
                      columnsToShowHandler={columnsToShowHandler}
                    />
                    <PrintPdf
                      list={list}
                      columns={columns}
                      title={"Shortage Products"}
                    />
                    <CSV
                      notButton={true}
                      list={list}
                      columns={columns}
                      title={"Shortage Products"}
                    />
                  </div>
                }
                placement='bottomRight'
                arrow={false}
                trigger='click'
              >
                <button className='p-2 hover:bg-gray-100 rounded-md transition-colors'>
                  <BsThreeDotsVertical className='text-lg text-gray-600' />
                </button>
              </Popover>
            </div>
          </div>
        ) : (
          // Desktop View
          <div className='pb-3'>
            <div className='w-full dark:text-yellow-50 px-3  pt-4 flex flex-wrap gap-2 items-center flex-col-reverse sm:flex-row justify-between'>
              <div className='flex flex-wrap lg:flex-nowrap gap-2 w-full md:w-auto'>
                <div className='filterTag min-w-[130px] max-w-[150px]'>
                  <Select
                    placeholder='Select a store'
                    mode={"single"}
                    loading={storeLoading}
                    showSearch={false}
                    value={storeId}
                    onChange={handleChangeStore}
                    maxTagPlaceholder={(item) => (
                      <div className=''>{item.length} Selected</div>
                    )}
                    maxTagCount={0}
                  >
                    {store?.map((option) => (
                      <Select.Option key={option.id} value={option.id}>
                        {option.name}
                      </Select.Option>
                    ))}
                  </Select>
                </div>
                <div className='hideScrollBar overflow-x-auto w-full flex items-center gap-2'>
                  <ColVisibilityDropdown
                    options={columns}
                    columns={columns}
                    columnsToShowHandler={columnsToShowHandler}
                  />
                </div>
              </div>

              <div className='flex items-center gap-2'>
                <PrintPdf
                  list={list}
                  columns={columns}
                  title={"Shortage Products"}
                />
                <CSV
                  notButton={true}
                  list={list}
                  columns={columns}
                  title={"Shortage Products"}
                />
              </div>
            </div>
          </div>
        )}

        {/* Table */}
        <Table
          loading={loading}
          rowSelection={rowSelection}
          columns={columnsToShow}
          dataSource={
            !!list?.length && list.map((item) => ({ ...item, key: item?.id }))
          }
          pagination={false}
          scroll={{ x: 1000, y: window.innerHeight - 319 }}
        />
      </div>

      {/* Pagination */}
      <div className='flex justify-center mt-3 pt-2 pb-3'>
        {total >= 11 && <Pagination onChange={fetchData} total={total} />}
      </div>
      {children && children}
    </>
  );
};
export default TableComponent;
