import { Empty, notification, Select } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Skeleton } from 'antd';
// import { useSelectedOrders } from '../../../store';
import { useOrderId, useReturnAfterOrderData } from '../../../order-view/store';
import { EmptyDataContainer } from '../../table/table-data/styles';
import PrinterIcon from '../../../../assets/icons/PrinterIcon';
import DownIcon from '../../../../assets/icons/DownIcon';
import {
  StyledTable,
  StyledTableWrapper,
  CustomDrop,
} from '../../return-order-table/return-orders-filters/returnstyles';
import { useLoading, usePrintOptionTOggle } from '../../store/store';
import { NavLink } from 'react-router-dom';
import { displayValueOrNA, formatDate } from '../../shared/utlis';
import PrintDropDown from '../../shared/elements/PrintDropDown';
import {
  useAssignData,
  useAssignPayload,
  useCallApiAgain,
} from '../../../store';
import styled from 'styled-components';
import { useApiHook } from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../../common/interface';
import CaretDownFilledIcon from '../../../../common/CaretDownFilledIcon';
import SortIcon from '../../../../common/SortIcon';

const OrderTable = () => {
  // const [, setSelectedReturnOrder] = useSelectedOrders();
  // const [selectAll, setSelectAll] = useState(false);
  const dropdownRefParent = useRef<HTMLDivElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [printToogle, setPrintToggle] = usePrintOptionTOggle();
  const [assignData] = useAssignData();
  const [, setOrderId] = useOrderId();
  const [returnAfterOrder] = useReturnAfterOrderData();
  const [assignPayload, setAssignPayload] = useAssignPayload();
  const [, setAssign] = useState<boolean>(false);
  const [, setCallAPi] = useCallApiAgain();
  const [loading] = useLoading();

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

    const { key, direction } = sortConfig;
    return [...returnAfterOrder].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;
    });
  }, [returnAfterOrder, 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 handleSelectAll = (e: any) => {
  //   setSelectAll(e.target.checked);
  //   if (e.target.checked) {
  //     setSelectedReturnOrder(
  //       returnAfterOrder.map((e: any) => ({
  //         id: e.id,
  //         status_id: 3,
  //       }))
  //     );
  //   } else {
  //     setSelectedReturnOrder([]);
  //   }
  // };

  // const handleSelectInvoice = (id: any) => {
  //   setSelectedReturnOrder((prevSelectedInvoices: any) => {
  //     const isSelected = prevSelectedInvoices?.some(
  //       (item: any) => item.id === id
  //     );

  //     if (isSelected) {
  //       return prevSelectedInvoices.filter((items: any) => items.id !== id);
  //     } else {
  //       return [...prevSelectedInvoices, { id, status_id: 3 }];
  //     }
  //   });
  // };

  const getStatusClass = (status: string) => {
    switch (status) {
      case 'Cancelled':
        return { color: '#E95252', background: 'rgba(233, 82, 82, 0.15)' };
      case 'On Hold':
        return { color: '#F4A503', background: '#FFF1D6' };
      case 'Sub-Contracted':
        return { color: '#F4A503', background: '#FFF1D6' };
      case 'Awaiting route':
        return { color: '#845ADF', background: 'rgba(132, 90, 223, 0.15)' };
      case 'Awaiting':
        return { color: '#845ADF', background: 'rgba(132, 90, 223, 0.15)' };
      case 'Completed':
        return {
          color: '#1F9254',
          background: 'rgba(41, 204, 106, 0.15)',
        };
      case 'Outstanding':
        return { color: '#FF9900', background: 'rgba(255, 153, 0, 0.15)' };
      case 'Routed':
        return { color: '#6396E5', background: 'rgba(99, 150, 229, 0.15)' };
      default:
        return { color: '#000', background: '#fff' };
    }
  };

  // API for Assign
  const {
    data: actionResponse,
    setShouldPerformAction: setAssignAction,
    error: apiError,
  } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `return_orders/update/assign/`,
    method: 'PUT',
    body: [assignPayload],
    performAction: false,
  });

  //client options
  const assignOptions = assignData?.map((option: any) => ({
    label: option?.type?.charAt(0)?.toUpperCase() + option?.type?.slice(1),
    value: option?.bjs_delivery,
  }));

  const handleAssignPayload = (Id: number, value: boolean) => {
    setCallAPi(false);
    setAssign(value);
    setAssignPayload({
      ...assignPayload,
      return_order_id: Id,
      bjs_delivery: value,
    });
    setAssignAction(true);
  };

  useEffect(() => {
    //@ts-ignore
    if (actionResponse?.code === 200) {
      setCallAPi(true);
      notification.success({
        message: 'Success',
        // @ts-ignore
        description: `${actionResponse?.message}`,
      });
      // @ts-ignore
    } else if (apiError?.detail) {
      notification.error({
        message: 'Failure',
        // @ts-ignore
        description: `${apiError?.detail[0]?.msg}`,
      });
    }
  }, [actionResponse, apiError]);

  return (
    <>
      <StyledTableWrapper className="fortables">
        <StyledTable>
          <thead>
            <tr>
              {/* <th className="emailInvoiceCheckbox">
                <Checkbox checked={false} />
              </th> */}
              <th onClick={() => handleSort('created_at')}>
                <div className="sortIconClass">
                  Created {renderSortIcon('created_at')}
                </div>
              </th>
              <th onClick={() => handleSort('return_location_name')}>
                <div className="sortIconClass">
                  Return Location {renderSortIcon('return_location_name')}
                </div>
              </th>
              <th>Pick Up Location</th>
              <th onClick={() => handleSort('recipient_name')}>
                <div className="sortIconClass">
                  Recipient {renderSortIcon('recipient_name')}
                </div>
              </th>
              <th> Client</th>
              <th>Consignment</th>
              <th>Return Order No</th>
              <th> Total Parts</th>
              <th onClick={() => handleSort('weight')}>
                <div className="sortIconClass">
                  Total Weight {renderSortIcon('weight')}
                </div>
              </th>
              <th onClick={() => handleSort('cube')}>
                <div className="sortIconClass">
                  Total CBM {renderSortIcon('cube')}
                </div>
              </th>
              <th>Assign</th>
              <th>Status</th>
              <th className="emailInvoiceShare">Labels</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={16}>
                  <Skeleton active />
                </td>
                <td colSpan={16}></td>
              </tr>
            ) : sortedData?.length === 0 ? (
              <tr>
                <td colSpan={16}>
                  <EmptyDataContainer>
                    <Empty />
                  </EmptyDataContainer>
                </td>
              </tr>
            ) : (
              sortedData?.map((item: any, index: any) => {
                const statusMapping: any = {
                  cancelled: 'Cancelled',
                  'on hold': 'On Hold',
                  SC: 'Sub-Contracted',
                  'awaiting route': 'Awaiting',
                  'awaiting confirmation': 'Awaiting',
                  complete: 'Completed',
                  outstanding: 'Outstanding',
                  routed: 'Routed',
                  failed: 'Failed',
                };
                const status = statusMapping[item?.status_value] || 'Unknown';
                const statusClass = getStatusClass(status);

                return (
                  <tr key={item.id}>
                    {/* <td>
                      <Checkbox
                        checked={false}
                        // onChange={() => handleSelectInvoice(item.id)}
                      />
                    </td> */}
                    <td>{formatDate(new Date(item?.created_at))}</td>
                    <td>{displayValueOrNA(item?.return_location_name)}</td>

                    <td>
                      {item?.locations?.length
                        ? item?.locations.join(', ')
                        : 'N/A'}
                    </td>

                    <td onClick={() => setOrderId(item.id)}>
                      <ul style={{ listStyleType: 'none', padding: 0 }}>
                        <li
                          style={{
                            color: '#0099ff',
                            fontWeight: 600,
                            paddingLeft: 0,
                          }}
                        >
                          <NavLink to={`../${item.id}`}>
                            {displayValueOrNA(item?.recipient_name)}
                          </NavLink>
                        </li>
                        <li style={{ color: '#888075' }}>
                          {displayValueOrNA(item?.postcode)}
                        </li>
                      </ul>
                    </td>

                    <td>{displayValueOrNA(item?.customer_name)}</td>

                    <td>{displayValueOrNA(item?.consignment)}</td>
                    <td>{displayValueOrNA(item?.order_number)}</td>

                    <td>{displayValueOrNA(item?.total_products)}</td>
                    <td>
                      {displayValueOrNA(item?.weight)}{' '}
                      {item?.weight && item?.weight > 0 ? 'KG' : ''}
                    </td>

                    <td>{displayValueOrNA(item?.cube)}</td>

                    <td key={item.id}>
                      <StyledAntSelect
                        options={assignOptions}
                        placeholder="Select"
                        onChange={(value: any) =>
                          handleAssignPayload(item?.id, value)
                        }
                        style={{ width: '150px' }}
                        value={item?.bjs_delivery}
                      />
                    </td>

                    <td>
                      <ul
                        className="statuscontainer"
                        style={{
                          listStyleType: 'none',
                          background: statusClass.background,
                        }}
                      >
                        <li
                          className="statustext"
                          style={{ color: statusClass.color }}
                        >
                          {status}
                        </li>
                      </ul>
                    </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}>
                                <PrintDropDown legacyProductId={item} />
                              </div>
                            )}
                          </li>
                        </CustomDrop>
                      </ul>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </StyledTable>
      </StyledTableWrapper>
    </>
  );
};

const StyledAntSelect = styled(Select)`
  .ant-select-selector {
    /* width: 22vw; */
    border-radius: 22px;
  }
  .ant-select-clear {
    top: 40% !important;
    font-size: 18px !important;
  }
`;

export default OrderTable;
