import {
  Checkbox,
  displayValueOrNA,
  useAxios,
} 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 { NavLink, useParams } from 'react-router-dom';
import dayjs from 'dayjs';
import { filtersReducerAtom } from '../order-daily-overview/header-filters/filterStore';
import {
  useClientOutstandingReturnData,
  useClientPortal,
  useEndDate,
  useLocationData,
  useSearchText,
  useSelectedClientPortOrders,
  useStartDate,
} from '../store';
import { usefetchAgain } from '../order-view/store';
import {
  useLoading,
  UsePaginationData,
  usePrintOptionTOggle,
} from '../order-daily-overview/store/store';
import SortIcon from '../../common/SortIcon';
import CaretDownFilledIcon from '../../common/CaretDownFilledIcon';
import { ApiResponse } from '../types';
import {
  CustomDrop,
  EmptyDataContainer,
  StyledTable,
  StyledTableWrapper,
} from '../order-daily-overview/return-order-table/return-orders-filters/returnstyles';
import PrinterIcon from '../../assets/icons/PrinterIcon';
import DownIcon from '../../assets/icons/DownIcon';
import PrintDropDownReturn from '../order-view/details-filters/left-side-filters/dropdowns/PrintDropDownReturn';

const OutstandingTable = () => {
  const [state] = useAtom(filtersReducerAtom);
  const { 'x-pagination': pagination } = state;
  const [
    outstandingReturnData,
    setOutstandingReturnData,
  ] = useClientOutstandingReturnData();
  const [load, setLoading] = useLoading();
  const dropdownRefParent = useRef<HTMLDivElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [printToogle, setPrintToggle] = usePrintOptionTOggle();
  const [locationData] = useLocationData();
  const [, setPaginationObject] = UsePaginationData();
  const [callForFetch] = usefetchAgain();
  const [clientPortal] = useClientPortal();
  const { status } = useParams();
  const [selectedOrderIds, setSelectedOrderIds] = useSelectedClientPortOrders();
  const [selectClientAll, setSelectClientAll] = useState(false);
  const [debouncedSearchText] = useSearchText();

  //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 (!outstandingReturnData || !sortConfig) return outstandingReturnData;

    const { key, direction } = sortConfig;
    return [...outstandingReturnData].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;
    });
  }, [outstandingReturnData, 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);
    }
  };

  //CP
  const [startDate] = useStartDate();
  const [endDate] = useEndDate();

  const filters = useMemo(() => {
    if (!clientPortal) return [];

    const stored = JSON.parse(localStorage.getItem('returnDate') || '{}');

    const sDate = startDate?.isValid?.() ? startDate : dayjs(stored?.startDate);
    const eDate = endDate?.isValid?.()
      ? endDate
      : stored?.endDate
      ? dayjs(stored?.endDate)
      : null;

    if (!sDate?.isValid?.()) return [];

    let dateFilters: any[] = [];

    if (eDate && eDate.isValid()) {
      dateFilters = [
        { field: 'created_at', op: '>=', value: sDate.format('YYYY-MM-DD') },
        {
          field: 'created_at',
          op: '<=',
          value: eDate.add(1, 'day').format('YYYY-MM-DD'),
        },
      ];
    } else {
      dateFilters = [
        {
          field: 'created_at',
          op: '=',
          value: sDate.format('YYYY-MM-DD'),
        },
      ];
    }

    const baseFilters: any[] =
      status === 'outstanding_return'
        ? [
            { field: 'isdeleted', op: '=', value: 0 },
            { field: 'product_return_action_id', op: '=', value: 'RTS' },
          ]
        : [];

    return [...baseFilters, ...dateFilters];
  }, [startDate, endDate, status]);

  const {
    data: fetchedOrderData,
    loading: returnDataLoad,
    paginationData,
    fetchData,
  } = useAxios<ApiResponse>({
    endpoint: '/v1/return/product/pending/',
    method: 'GET',
    filters: filters,
    pagination: pagination,
  });
  console.log(filters, 'outstanding filters');
  const hasFetchedRef = useRef(false);

  useEffect(() => {
    const shouldFetch =
      clientPortal &&
      debouncedSearchText === '' &&
      filters?.length > 0 &&
      !hasFetchedRef.current;

    if (shouldFetch) {
      fetchData();
      hasFetchedRef.current = true;
    }
  }, [debouncedSearchText, filters, clientPortal]);
  useEffect(() => {
    hasFetchedRef.current = false;
  }, [debouncedSearchText, filters]);

  useEffect(() => {
    setLoading(returnDataLoad);
    if (fetchedOrderData && fetchedOrderData?.data) {
      setOutstandingReturnData(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]);

  // console.log(modifiedFilters, 'modifiedFilters');
  useEffect(() => {
    setLoading(returnDataLoad);
    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,
        };
      });

      setOutstandingReturnData(updatedReturnData);
    }
  }, [fetchedOrderData, returnDataLoad, locationData, state, callForFetch]);

  //Client Portal
  const handleSelectOrderId = (id: string | number) => {
    setSelectedOrderIds(prev =>
      prev.includes(id) ? prev.filter(orderId => orderId !== id) : [...prev, id]
    );
  };

  const handleClientSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    const isChecked = e.target.checked;
    setSelectClientAll(isChecked);

    if (isChecked) {
      setSelectedOrderIds(
        outstandingReturnData?.map((item: any) => item?.order_id) || []
      );
    } else {
      setSelectedOrderIds([]);
    }
  };
  return (
    <>
      <StyledTableWrapper className="fortables">
        <StyledTable>
          <thead>
            <tr>
              {/* <th className="emailInvoiceCheckbox">
                <Checkbox checked={selectAll} onChange={handleSelectAll} />
              </th> */}
              <th className="emailInvoiceCheckbox">
                <Checkbox
                  checked={selectClientAll}
                  onChange={handleClientSelectAll}
                />
              </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>
                    <Checkbox
                      checked={selectedOrderIds.includes(item?.order_id)}
                      onChange={() => handleSelectOrderId(item?.order_id)}
                    />
                  </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 OutstandingTable;
