import { Checkbox, useApiHook } from '@bjsdistribution/dms-component-library';
import { Empty, notification, Skeleton } from 'antd';
import { format } from 'date-fns';
import { useAtom } from 'jotai';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import DownIcon from '../../../../assets/icons/DownIcon';
import PrinterIcon from '../../../../assets/icons/PrinterIcon';
import CaretDownFilledIcon from '../../../../common/CaretDownFilledIcon';
import SortIcon from '../../../../common/SortIcon';
import PrintDropDownReturn from '../../../order-view/details-filters/left-side-filters/dropdowns/PrintDropDownReturn';
import { usefetchAgain, useReturnData } from '../../../order-view/store';
import {
  useGroupedPayload,
  useLocationData,
  useNewReturnPayload,
  useReturnPayload,
  useSelectAll,
  useSelectedOrders,
} from '../../../store';
import { ApiResponse } from '../../../types';
import { filtersReducerAtom } from '../../header-filters/filterStore';
import { displayValueOrNA } from '../../shared/utlis';
import {
  useLoading,
  UsePaginationData,
  usePrintOptionTOggle,
} from '../../store/store';
import { EmptyDataContainer } from '../../table/table-data/styles';
import { CustomDrop, StyledTable, StyledTableWrapper } from './returnstyles';
import { NavLink } from 'react-router-dom';

const ReturnOrderTable = () => {
  const [state] = useAtom(filtersReducerAtom);
  const [selectedReturnOrder, setSelectedReturnOrder] = useSelectedOrders();
  const [selectAll, setSelectAll] = useSelectAll();
  const { 'x-filters': filters, 'x-pagination': pagination } = state;
  const [returnData, setReturnData] = useReturnData();
  const [load, setLoading] = useLoading();
  const dropdownRefParent = useRef<HTMLDivElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [printToogle, setPrintToggle] = usePrintOptionTOggle();
  const [createReturn, setReturnPayload] = useReturnPayload();
  const [newpayload, setNewPayload] = useNewReturnPayload();
  const [, setGrouped] = useGroupedPayload();
  const [locationData] = useLocationData();
  const [, setPaginationObject] = UsePaginationData();
  const [callForFetch] = usefetchAgain();

  //sorting
  const [sortConfig, setSortConfig] = useState<{
    key: string;
    direction: 'asc' | 'desc';
  } | null>(null);

  const handleSort = (key: string) => {
    setSortConfig((prev: any) => {
      if (prev?.key === key && prev.direction === 'asc') {
        return { key, direction: 'desc' };
      }
      return { key, direction: 'asc' };
    });
  };

  const sortedData = useMemo(() => {
    if (!returnData || !sortConfig) return returnData;

    const { key, direction } = sortConfig;
    return [...returnData].sort((a, b) => {
      const valueA = a[key];
      const valueB = b[key];

      if (typeof valueA === 'number' && typeof valueB === 'number') {
        return direction === 'asc' ? valueA - valueB : valueB - valueA;
      }
      if (typeof valueA === 'string' && typeof valueB === 'string') {
        return direction === 'asc'
          ? valueA.localeCompare(valueB)
          : valueB.localeCompare(valueA);
      }
      return 0;
    });
  }, [returnData, sortConfig]);

  const renderSortIcon = (columnKey: string) => {
    if (!sortConfig || sortConfig.key !== columnKey) {
      return <SortIcon />;
    }
    return sortConfig.direction === 'asc' ? (
      <CaretDownFilledIcon />
    ) : (
      <CaretDownFilledIcon />
    );
  };

  const OpenDropDown = (index: number) => {
    setPrintToggle(prevIndex => (prevIndex === index ? null : index));
  };
  // Close dropdown outside click
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  const handleClickOutside = (event: MouseEvent) => {
    if (
      dropdownRef.current &&
      !dropdownRef.current.contains(event.target as Node)
    ) {
      setPrintToggle(null);
    }
  };

  const {
    data: fetchedOrderData,
    loading: returnDataLoad,
    paginationData,
    setShouldPerformAction,
  } = useApiHook<ApiResponse>({
    endpoint: '/v1/return/product/pending/',
    method: 'GET',
    filters: filters,
    pagination: pagination,
    performAction: false,
  });

  useEffect(() => {
    setLoading(returnDataLoad);
    if (fetchedOrderData && fetchedOrderData?.data) {
      setReturnData(fetchedOrderData?.data);
      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',
          });
        }
      } else {
        notification.error({
          message: 'Error',
          description: 'Pagination data is null or undefined',
        });
      }
    }
  }, [fetchedOrderData, returnDataLoad]);

  useEffect(() => {
    setLoading(returnDataLoad);
    setShouldPerformAction(true);
    if (fetchedOrderData && fetchedOrderData?.data && locationData) {
      const updatedReturnData = fetchedOrderData.data.map(returnItem => {
        const matchingLocation = locationData.find(
          (location: any) => location?.token === returnItem?.return_location
        );
        return {
          ...returnItem,
          new_location: matchingLocation
            ? matchingLocation?.location_name
            : null,
        };
      });

      setReturnData(updatedReturnData);
    }
    // setShouldPerformAction(false);
  }, [fetchedOrderData, returnDataLoad, locationData, state, callForFetch]);

  const handleSelectAll = (e: any) => {
    const isChecked = e.target.checked;
    setSelectAll(isChecked);

    if (isChecked) {
      const filteredData = returnData?.filter(
        (loc: any) => loc?.product_return_action === 'RTS'
      );
      const selectedOrders = filteredData.map((loc: any) => ({
        id: loc.id,
        return_locations: loc?.return_location_name,
        return_location: loc?.return_location,
        products: loc?.legacy_product_id,
        product_return_action: loc?.product_return_action,
        return_location_token: loc?.return_location,
      }));
      const newPayload = filteredData.map((loc: any) => ({
        id: loc.id,
        account_number: createReturn?.account_number,
        customer_id: +createReturn?.customer_id,
        products: [loc?.legacy_product_id],
        return_action: loc?.product_return_action,
        return_location_token: loc?.return_location || null,
      }));

      setSelectedReturnOrder(selectedOrders);
      setNewPayload(newPayload);
    } else {
      setSelectedReturnOrder([]);
      setNewPayload([]);
      setGrouped([]);
    }
  };

  const handleSelectOrderReturn = (
    id: any,
    return_location: any,
    return_location_name: any,
    product_return_action: any,
    legacy_product_id: any
  ) => {
    setSelectedReturnOrder((prevSelectedLocations: any) => {
      const isSelected = prevSelectedLocations?.some(
        (loc: any) => loc.id === id
      );

      if (isSelected) {
        const updatedSelectedLocations = prevSelectedLocations.filter(
          (loc: any) => loc.id !== id
        );

        setReturnPayload(prevState => ({
          ...prevState,
          products: legacy_product_id,
          return_action: product_return_action || null,
          return_location_token: return_location || null,
          // new_location: new_location,
        }));

        setNewPayload((prevPayload: any) =>
          prevPayload.filter((item: any) => item.id !== id)
        );

        setSelectAll(false); // Ensure "select all" is false if one is deselected
        return updatedSelectedLocations;
      } else {
        const newReturnPayload = {
          id,
          account_number: createReturn?.account_number,
          customer_id: +createReturn?.customer_id,
          products: [legacy_product_id],
          return_action: product_return_action || null,
          return_location_token: return_location || null,
        };

        setNewPayload((prevPayload: any) => [...prevPayload, newReturnPayload]);

        const updatedSelectedLocations = [
          ...prevSelectedLocations,
          {
            id,
            return_location,
            return_location_name,
            product_return_action,
          },
        ];
        setSelectAll(
          updatedSelectedLocations?.length ===
            returnData?.filter(
              (loc: any) => loc?.product_return_action === 'RTS'
            )?.length
        );
        return updatedSelectedLocations;
      }
    });
  };

  useEffect(() => {
    if (newpayload?.length === 0) return;

    const groupedPayload = newpayload?.reduce((acc: any, item: any) => {
      const { return_location_token } = item;

      if (!return_location_token) {
        acc.push(item);
      } else {
        if (!acc[return_location_token]) {
          acc[return_location_token] = {
            ...item,
            products: [],
            return_action: [],
          };
        }

        acc[return_location_token].products = [
          ...acc[return_location_token].products,
          ...item.products,
        ];

        acc[return_location_token].return_action = [
          ...acc[return_location_token].return_action,
          ...item.return_action,
        ];
      }

      return acc;
    }, []);
    const mergedPayload = Object.values(groupedPayload);
    setGrouped(mergedPayload);
  }, [newpayload]);

  return (
    <>
      <StyledTableWrapper className="fortables">
        <StyledTable>
          <thead>
            <tr>
              {/* <th className="emailInvoiceCheckbox">
                <Checkbox checked={selectAll} onChange={handleSelectAll} />
              </th> */}
              {returnData?.some(
                (item: any) => item?.product_return_action === 'RTS'
              ) ? (
                <th className="emailInvoiceCheckbox">
                  <Checkbox checked={selectAll} onChange={handleSelectAll} />
                </th>
              ) : (
                <th></th>
              )}
              <th onClick={() => handleSort('location')}>
                <div className="sortIconClass">
                  Product Location {renderSortIcon('location')}
                </div>
              </th>
              <th onClick={() => handleSort('return_location_name')}>
                <div className="sortIconClass">
                  Return Location {renderSortIcon('return_location_name')}
                </div>
              </th>
              <th onClick={() => handleSort('recipient_name')}>
                <div className="sortIconClass">
                  Recipient {renderSortIcon('recipient_name')}
                </div>
              </th>
              <th>Return Action</th>
              <th>Code</th>
              <th>Description</th>
              <th>Part</th>
              <th onClick={() => handleSort('weight')}>
                <div className="sortIconClass">
                  Weight {renderSortIcon('weight')}
                </div>
              </th>
              <th>CBM</th>
              <th onClick={() => handleSort('return_reason')}>
                <div className="sortIconClass">
                  Return Reason {renderSortIcon('return_reason')}
                </div>
              </th>
              <th>Collected</th>
              <th onClick={() => handleSort('collection_reason')}>
                <div className="sortIconClass">
                  Collection Reason {renderSortIcon('collection_reason')}
                </div>
              </th>
              <th className="emailInvoiceShare">Labels</th>
            </tr>
          </thead>
          <tbody>
            {load ? (
              <tr>
                <td colSpan={14}>
                  <Skeleton active />
                </td>
              </tr>
            ) : sortedData?.length === 0 ? (
              <tr>
                <td colSpan={14}>
                  <EmptyDataContainer>
                    <Empty />
                  </EmptyDataContainer>
                </td>
              </tr>
            ) : (
              sortedData?.map((item: any, index: any) => (
                <tr key={item.id}>
                  <td>
                    {item?.product_return_action === 'RTS' ? (
                      <Checkbox
                        className="custom-check"
                        checked={selectedReturnOrder.some(
                          (selectedInvoice: any) =>
                            selectedInvoice?.id === item?.id
                        )}
                        onChange={() =>
                          handleSelectOrderReturn(
                            item?.id,
                            item?.return_location,
                            item?.return_location_name,
                            item?.product_return_action,
                            item?.legacy_product_id
                          )
                        }
                      />
                    ) : null}
                  </td>

                  <td>
                    {item?.location !== null && item?.location !== undefined ? (
                      item?.location
                    ) : (
                      <div className="awaiting">Awaiting</div>
                    )}
                  </td>
                  <td> {displayValueOrNA(item?.return_location_name)}</td>
                  <td>
                    <ul style={{ listStyleType: 'none', padding: 0 }}>
                      <li
                        style={{
                          color: '#0099ff',
                          fontWeight: 600,
                          paddingLeft: 0,
                        }}
                      >
                        <NavLink to={`/orders/view/${item?.order_id}`}>
                          {displayValueOrNA(item?.recipient_name)}
                        </NavLink>
                      </li>
                      <li style={{ color: '#888075' }}>
                        {displayValueOrNA(item?.postcode)}
                      </li>
                    </ul>
                  </td>
                  <td>{displayValueOrNA(item?.product_return_action)}</td>
                  <td>{displayValueOrNA(item?.code)}</td>
                  <td>{displayValueOrNA(item?.description)}</td>
                  <td>{displayValueOrNA(item?.part)}</td>
                  <td>
                    {displayValueOrNA(item?.weight)}{' '}
                    {item?.weight && item?.weight !== null ? 'KG' : ''}
                  </td>
                  <td>{displayValueOrNA(item?.cube)}</td>
                  <td>{displayValueOrNA(item?.return_reason)}</td>
                  <td>
                    {item?.collected_at
                      ? format(new Date(item?.collected_at), 'dd/MM/yyyy')
                      : 'UNKNOWN'}
                  </td>

                  <td>{displayValueOrNA(item?.collection_reason)}</td>
                  <td>
                    <ul className="actionbox">
                      <CustomDrop
                        ref={dropdownRefParent}
                        className={printToogle === index ? 'active' : ''}
                      >
                        <li
                          className="shareIconContainer"
                          onClick={() => OpenDropDown(index)}
                        >
                          <PrinterIcon />
                          <DownIcon />
                          {printToogle === index && (
                            <div ref={dropdownRef}>
                              <PrintDropDownReturn
                                legacyURL={item?.return_order_product_label}
                                legacyProductID={item?.legacy_product_id}
                              />
                            </div>
                          )}
                        </li>
                      </CustomDrop>
                    </ul>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </StyledTable>
      </StyledTableWrapper>
    </>
  );
};

export default ReturnOrderTable;
