import React, { useEffect, useState } from 'react';
import {
  StyledTable,
  StyledTableWrapper,
} from '../../../order-daily-overview/return-order-table/return-orders-filters/returnstyles';
import {
  Checkbox,
  displayValueOrNA,
  useApiHook,
} from '@bjsdistribution/dms-component-library';
import ActionIcon from '../../../../assets/icons/ActionIcon';
import { useOrderId, useProductDetails } from '../../store';
import { ApiResponse } from '../../types';
import { notification } from 'antd';
import { useNewReturnOrderData, useSelectedProducts } from '../../../store';
import styled from 'styled-components';
import { NavLink } from 'react-router-dom';

const ReturnProductTable = () => {
  const [selectedProducts, setSelectedProducts] = useSelectedProducts();
  const [selectAll, setSelectAll] = useState(false);
  const [productData, setProductData] = useProductDetails();
  const [selectedRowId, setSelectedRowId] = useState<number | null>(null);
  const [orderId] = useOrderId();
  const [returnOrderData] = useNewReturnOrderData();

  const handleActionClick = (id: number) => {
    setSelectedRowId(id);
  };

  const { data: isresponse, setShouldPerformAction: setAction } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `order/order_products/delete/`,
    method: 'DELETE',
    body: [{ id: selectedRowId, order_id: orderId }],
    performAction: false,
  });

  useEffect(() => {
    if (isresponse && isresponse.data) {
      notification.success({
        message: 'Success',
        description: 'Successfully Delete Order Product.',
      });
      handleRemoveRow();
      setSelectedRowId(null);
    }
  }, [isresponse]);

  const handleRemoveRow = () => {
    if (selectedRowId !== null) {
      setProductData((prevData: any) =>
        prevData.filter((item: any) => item.id !== selectedRowId)
      );
    }
  };

  const onDeleteProducts = () => {
    setAction(true);
  };

  const handleSelectAll = () => {
    if (selectAll) {
      setSelectedProducts([]);
    } else {
      const allProductIds = productData?.map((product: any) => product.id);
      setSelectedProducts(allProductIds);
    }
    setSelectAll(!selectAll);
  };

  const handleSelectProduct = (id: number) => {
    setSelectedProducts((prevSelected: any) =>
      prevSelected.includes(id)
        ? prevSelected.filter((selectedId: any) => selectedId !== id)
        : [...prevSelected, id]
    );
  };

  const disableCheckbox =
    productData?.length == 0 || returnOrderData?.length == 0;

  return (
    <div>
      <StyledTableWrapper id="tableScrolling" className="orderProductTable">
        <StyledTable>
          <thead>
            <tr>
              <th className="emailproductsCheckbox">
                <StyleCheckbox
                  disabled={disableCheckbox}
                  checked={selectAll}
                  onChange={handleSelectAll}
                />
              </th>
              <th>Location</th>
              <th>Sender</th>
              <th>Code</th>
              <th>Description</th>
              <th>Return Reason</th>
              <th>Part</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            {productData && productData?.length > 0 ? (
              productData?.map((product: any) => (
                <tr key={product.id}>
                  <td>
                    <StyleCheckbox
                      checked={selectedProducts?.includes(product?.id)}
                      onChange={() => handleSelectProduct(product?.id)}
                      disabled={disableCheckbox}
                    />
                  </td>
                  <td>{product?.location || 'N/A'}</td>
                  <td>
                    <ul style={{ listStyleType: 'none', padding: 0 }}>
                      <li
                        style={{
                          color: '#0099ff',
                          fontWeight: 600,
                          paddingLeft: 0,
                        }}
                      >
                        <NavLink to={`/orders/view/${product?.order_id}`}>
                          {displayValueOrNA(product?.recipient_name)}
                        </NavLink>
                      </li>
                      <li style={{ color: '#888075' }}>
                        {displayValueOrNA(product?.postcode)}
                      </li>
                    </ul>
                  </td>
                  <td>{product?.code}</td>
                  <td>{product?.description}</td>
                  <td>{product?.return_reason}</td>
                  <td>{product?.part}</td>
                  <td>
                    <div
                      onClick={() => {
                        handleActionClick(product?.id);
                        onDeleteProducts();
                      }}
                      style={{ cursor: 'pointer' }}
                    >
                      <ActionIcon />
                    </div>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={8} style={{ textAlign: 'center' }}>
                  No records found
                </td>
              </tr>
            )}
          </tbody>
        </StyledTable>
      </StyledTableWrapper>
    </div>
  );
};

const StyleCheckbox = styled(Checkbox)`
  &:disabled {
    background-color: gray;
    cursor: not-allowed;
    opacity: -0.4;
  }
`;

export default ReturnProductTable;
