import React, { useEffect, useState } from 'react';
import {
  useItemsPerOverviewPage,
  useStatsLoading,
  UsePaginationOverviewData,
} from './store/store';
import Filters from './filters/Filters';
import styled from 'styled-components';
import { useCustomerData, useStickyStatus } from '../store';
import HeaderFilter from './header-filters/HeaderFilter';
import { useApiHook } from '@bjsdistribution/dms-component-library';
import { useAtom, useClientData } from '../order-view/store';
import { ClientData } from './common/interface';
import ReturnFilter from './return-order-table/return-orders-filters/ReturnFilter';
import { Text } from './filters/FilterStyle';
import ReturnTable from './table/ReturnTable';
import { overviewfiltersReducerAtom } from './header-filters/overViewFilter';
import Pagination from './table-view/Pagination';
import { notification } from 'antd';
import { ApiResponse } from '../types';

function ReturnMainTable() {
  const [state] = useAtom(overviewfiltersReducerAtom);
  const [paginationObj, setPaginationObject] = UsePaginationOverviewData();
  const [, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useItemsPerOverviewPage();
  const { 'x-filters': filters, 'x-pagination': pagination } = state;
  const { page, total } = paginationObj;
  // const [selectedClient] = useTableName();
  const [isScrolled] = useStickyStatus();
  const [, setLoading] = useStatsLoading();
  const [, setClientData] = useClientData();
  const [, setCustomers] = useCustomerData();
  // const [tableName] = useTableName();
  const queryParams = new URLSearchParams(location.search);

  const customerId = queryParams.get('customerId');

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };
  const handleItemsPerPageChange = (itemsPerPage: number) => {
    setItemsPerPage(itemsPerPage);
  };

  //API for client data
  const { data: fetchedCustomerData, loading: loading } = useApiHook<
    ApiResponse
  >({
    endpoint: `/v1/return/product/customers/`,
    method: 'GET',
    //@ts-ignore
    pagination: { is_pagination: false },
  });

  useEffect(() => {
    if (fetchedCustomerData && fetchedCustomerData?.data) {
      setCustomers(fetchedCustomerData?.data);
    }
  }, [loading]);

  const {
    data: fetchedClientData,
    loading: statsDataLoading,
    paginationData,
  } = useApiHook<{
    data: ClientData[];
  }>({
    endpoint: `/v1/return/product/stats/`,
    method: 'GET',
    //@ts-ignore
    pagination: pagination,
    filters: filters,
  });

  useEffect(() => {
    setLoading(statsDataLoading);
    if (fetchedClientData && fetchedClientData.data) {
      const result = fetchedClientData?.data;
      setClientData(result);
      if (paginationData) {
        try {
          const { count, ...rest } = JSON.parse(paginationData);
          setPaginationObject(rest);
        } catch (error) {
          console.error('Error parsing paginationData:', error);
          notification.error({
            message: 'Error',
            description: 'Failed to parse pagination data',
          });
        }
      }
    }
  }, [statsDataLoading]);

  return (
    <>
      <DashBoardWrapper className={` ${isScrolled ? 'stickyTableHead' : ''}`}>
        {/* <RouterHeader /> */}
        <div className="Tableconatiner">
          <HeaderFilter />
          <Container>
            <Row>
              <Text>Client Return</Text>
              {customerId ? <ReturnFilter /> : <Filters />}
            </Row>
            <ReturnTable />
          </Container>
          {total > 0 && (
            <Pagination
              currentPage={page}
              totalItems={total}
              itemsPerPage={itemsPerPage}
              onPageChange={handlePageChange}
              onItemsPerPageChange={handleItemsPerPageChange}
            ></Pagination>
          )}
        </div>
      </DashBoardWrapper>
    </>
  );
}

export default ReturnMainTable;

const Row = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;
const Container = styled.div`
  position: relative;
  top: -46px;
`;
const DashBoardWrapper = styled.section`
  .Tableconatiner {
    border-radius: 12px;
    background: #fff;
    box-shadow: -2px 0px 12px 0px rgba(56, 71, 109, 0.1);
    display: block;
    padding: 15px 20px;
  }
  .headerWrap,
  .tableData,
  .styleCovered {
    transition: all ease 0.5s;
  }
  &.stickyTableHead {
    h2 {
      font-size: 21px;
    }
    .headerWrap {
      height: 84px;
      padding: 10px;
      border-radius: 0px 0px 15px 15px;
      > div {
        position: relative;
        z-index: 10;
      }
    }
    .styleCovered {
      margin-top: -32px;
      width: 67%;
      float: right;
      gap: 5px;
      padding-right: 11px;

      li {
        padding: 4px 10px 5px 5px;
        gap: 5px;
        .svgCover {
          width: 30px;
          height: 30px;
          svg {
            height: auto;
            width: 58%;
          }
        }
        .countDigit {
          font-size: 19px;
        }
      }
      .countMess {
        font-size: 13px;
      }
    }
    .dmsBulkFilter {
      min-height: unset;
      gap: 4px;
      > div {
        padding: 4px 12px;
        label {
          font-size: 11px;
        }
      }
    }

    .StyledFilterList {
      gap: 4px;
      li {
        height: 29px;
        padding: 3px 8px;
        gap: 4px;
        .StyledFilterBtnIcon {
          width: 20px;
          height: 20px;
          svh {
            width: 10px;
            height: auto;
          }
        }
        .StyledFilterBtnLabel {
          font-size: 13px;
        }
      }
    }
    .StyledFilterLabel {
      padding-left: 10px;
      span {
        font-size: 13px;
      }
    }
    .cardcontainer.tableData {
      max-height: calc(100vh - 310px);
      min-height: calc(100vh - 310px);
    }

    .tableData {
      max-height: calc(100vh - 320px);
      min-height: calc(100vh - 320px);

      margin-top: 8px;
      thead {
        position: sticky;
        top: 0;
        z-index: 9;
        th {
          font-size: 13px;
          padding: 2px 15px;
        }
      }
    }
  }
`;
