import React, { useEffect, useMemo, useState } from 'react';
import { useAtom, useClientData } from '../../order-view/store';
import { useStatsLoading } from '../store/store';
import {
  ColumStyle,
  EmptyDataContainer,
  GreyBox,
  StyledTable,
  StyledTableWrapper,
} from './table-data/styles';
import { Empty, Skeleton } from 'antd';
import { useNavigate } from 'react-router-dom';
import { filtersReducerAtom } from '../header-filters/filterStore';
import { useCustomerData } from '../../store';
import SortIcon from '../../../common/SortIcon';
import CaretDownFilledIcon from '../../../common/CaretDownFilledIcon';

const ReturnTable: React.FC = () => {
  const [clientData] = useClientData();
  const [updatedData, setUpdatedData] = useState<any>([]);
  const [statsLoading] = useStatsLoading();
  const [, dispatch] = useAtom(filtersReducerAtom);
  const navigate = useNavigate();
  const [customers] = useCustomerData();
  // const [searchParams] = useSearchParams();

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

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

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

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

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

  //updated client data
  useEffect(() => {
    const updatedClientData = clientData?.map(client => {
      const matchingCustomer = customers?.find(
        (customer: any) => customer?.customer_id === client?.customer_id
      );
      return {
        ...client,
        account_number: matchingCustomer
          ? matchingCustomer?.account_number
          : null,
      };
    });
    setUpdatedData(updatedClientData);
  }, [customers, clientData]);

  //handle Redirect
  const handleRedirect = (customerId: number) => {
    if (customerId) {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: customerId,
      });
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    } else {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: [],
      });
    }

    const queryParams = new URLSearchParams({
      customerId: customerId?.toString(),
    });
    //for dev
    //navigate(`filter?${queryParams.toString()}`);
    navigate(`/orders/view/return/filter?${queryParams.toString()}`);

    //for local
    //navigate(`/filter?${queryParams.toString()}`);
  };

  //for RTS
  const handleRedirectRTS = (customerId: number, RTS: string) => {
    if (customerId) {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: customerId,
      });
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    } else {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: [],
      });
    }

    const queryParams = new URLSearchParams({
      customerId: customerId?.toString(),
      type: RTS,
    });
    //for dev
    //navigate(`filter?${queryParams.toString()}`);
    navigate(`/orders/view/return/filter?${queryParams.toString()}`);

    //for local
    //navigate(`/filter?${queryParams.toString()}`);
  };

  return (
    <>
      <StyledTableWrapper>
        <StyledTable>
          <thead>
            <tr>
              {[
                { label: 'Trading Name', key: 'trading_as' },
                { label: 'Client', key: 'customer_name' },
                { label: 'Orders', key: 'orders' },
                { label: 'Products', key: 'return_order_products' },
                { label: 'RTS', key: 'RTS' },
                { label: 'Pending', key: 'PENDING' },
                { label: 'Dispose', key: 'DISPOSE' },
                { label: 'Re-allocate', key: 'RE-ALLOCATE' },
                { label: 'Re-Del', key: 'RE-DEL' },
                { label: 'Recycle', key: 'RECYCLE' },
                { label: 'Unknown', key: 'UNKNOWN' },
              ].map(({ label, key }) => (
                <th key={key} onClick={() => handleSort(key)}>
                  <div style={{ display: 'flex', cursor: 'pointer' }}>
                    {label} <span>{renderSortIcon(key)}</span>
                  </div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {statsLoading ? (
              <tr>
                <td colSpan={11}>
                  <Skeleton active />
                </td>
              </tr>
            ) : sortedData?.length === 0 ? (
              <tr>
                <td colSpan={11}>
                  <EmptyDataContainer>
                    <Empty />
                  </EmptyDataContainer>
                </td>
              </tr>
            ) : (
              sortedData?.map((key: any, index: number) => {
                return (
                  <tr key={index}>
                    <td>{key?.trading_as}</td>

                    <td
                      onClick={() => handleRedirect(key?.customer_id)}
                      style={{
                        color: '#0099ff',
                        fontWeight: 600,
                        cursor: 'pointer',
                      }}
                    >
                      <span>{key?.customer_name}</span>
                    </td>

                    <td>
                      <ColumStyle>
                        <GreyBox>
                          {key?.orders}
                          {/* </div> */}
                        </GreyBox>
                      </ColumStyle>
                    </td>

                    <td>
                      <ColumStyle>
                        <GreyBox>{key?.return_order_products}</GreyBox>
                      </ColumStyle>
                    </td>
                    <td
                      style={{
                        color: key?.RTS > 0 ? '#0099ff' : 'inherit',
                        fontWeight: key?.RTS > 0 ? 600 : 'normal',
                        cursor: key?.RTS > 0 ? 'pointer' : 'default',
                      }}
                      onClick={
                        key?.RTS > 0
                          ? () => handleRedirectRTS(key?.customer_id, 'RTS')
                          : undefined
                      }
                    >
                      <ColumStyle>
                        <GreyBox
                          style={{
                            backgroundColor:
                              key?.RTS > 0
                                ? 'rgba(99, 150, 229, 0.1)'
                                : 'rgba(153, 153, 153, 0.1)',
                          }}
                        >
                          {key?.RTS}
                        </GreyBox>
                      </ColumStyle>
                    </td>

                    <td>
                      <ColumStyle>
                        <GreyBox>{key?.PENDING}</GreyBox>
                      </ColumStyle>
                    </td>
                    <td>
                      <ColumStyle>
                        <GreyBox>{key?.DISPOSE}</GreyBox>
                      </ColumStyle>
                    </td>
                    <td>
                      <ColumStyle>
                        <GreyBox>{key?.['RE-ALLOCATE']}</GreyBox>{' '}
                      </ColumStyle>
                    </td>
                    <td>
                      <ColumStyle>
                        <GreyBox>{key?.['RE-DEL']}</GreyBox>
                      </ColumStyle>
                    </td>
                    <td>
                      <ColumStyle>
                        <GreyBox>{key?.RECYCLE}</GreyBox>
                      </ColumStyle>
                    </td>
                    <td>
                      <ColumStyle>
                        <GreyBox>{key?.UNKNOWN}</GreyBox>
                      </ColumStyle>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </StyledTable>
      </StyledTableWrapper>
    </>
  );
};

export default ReturnTable;
