import React from 'react';
import { useCancelOrderProducts, useOrderStaticData } from '../../../store';
import { useLoading } from '../../../../order-daily-overview/store/store';
import { Empty, Select, Skeleton } from 'antd';
// import { AntSelect } from '@bjsdistribution/dms-component-library';
import { CancelOrderProductsType } from '../../../types';
import OrderActionsDropdown from '../../Dropdown';
import styled from 'styled-components';
import DeliverProductIcon from '../../../../../assets/icons/DeliverProductIcon';
import ReturnProductIcon from '../../../../../assets/icons/ReturnProductIcon';
import { EmptyDataContainer } from '../charge-log';

const deliverTypeOptions = [
  {
    label: 'Deliver',
    value: 'deliver',
    icon: <DeliverProductIcon />,
  },
  {
    label: 'Return',
    value: 'return',
    icon: <ReturnProductIcon />,
  },
];

const collectTypeOptions = [
  {
    label: 'Return',
    value: 'return',
    icon: <ReturnProductIcon />,
  },
];

const CancelOrderTable = () => {
  const [
    cancelOrderProducts,
    setCancelOrderProducts,
  ] = useCancelOrderProducts();

  const [loading] = useLoading();
  const [orderStaticData] = useOrderStaticData();

  if (!cancelOrderProducts?.length) {
    return null;
  }

  const returnReasonsOptions = orderStaticData?.return_reasons?.map(
    (option: any) => ({
      label: option?.reason,
      value: option?.reason,
    })
  );

  const returnActionOptions = orderStaticData?.order_product_return_action?.map(
    (option: any) => ({
      label: option?.value,
      value: option?.value,
    })
  );

  const onChange = (
    selectedVal: string,
    id: number,
    type: keyof CancelOrderProductsType
  ) => {
    console.log(selectedVal, id, type);
    const updatedList = cancelOrderProducts?.map(
      (item: CancelOrderProductsType) => {
        const newItem =
          item.order_product_id === id
            ? {
                ...item,
                [type]: selectedVal,
              }
            : item;
        return newItem;
      }
    );
    setCancelOrderProducts(updatedList);
  };

  return (
    <div>
      <StyledTableWrapper>
        <StyledTable className="scrollClass">
          <thead>
            <tr>
              <th>Status</th>
              <th>Code</th>
              <th>Description</th>
              <th>SKU</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={4}>
                  <Skeleton active />
                </td>
              </tr>
            ) : cancelOrderProducts?.length === 0 ? (
              <tr>
                <td className="emptyTd" colSpan={4}>
                  <EmptyDataContainer>
                    <Empty />
                  </EmptyDataContainer>
                </td>
              </tr>
            ) : (
              cancelOrderProducts?.map((product: CancelOrderProductsType) => {
                const dropdownOptions =
                  product?.product_type === 'deliver'
                    ? deliverTypeOptions
                    : collectTypeOptions;

                const isReturn = product?.action === 'return';

                return (
                  <tr
                    key={product?.order_product_id}
                    style={{
                      boxShadow: '0px 1px 3px 0px rgba(16, 24, 40, 0.1)',
                    }}
                  >
                    <td colSpan={4}>
                      <table style={{ width: '100%' }}>
                        <tbody>
                          <tr>
                            <td style={{ width: '25%' }}>
                              <CustomSelectDropdown
                                options={dropdownOptions}
                                placeholder="Select"
                                onChange={(val: any) =>
                                  onChange(
                                    val,
                                    product?.order_product_id!,
                                    'action'
                                  )
                                }
                                prefix={
                                  product?.action === 'deliver' ? (
                                    <DeliverProductIcon />
                                  ) : product?.action === 'return' ? (
                                    <ReturnProductIcon />
                                  ) : (
                                    <></>
                                  )
                                }
                                style={{ width: '100%' }}
                                value={dropdownOptions?.filter(
                                  (item: any) => item?.value === product?.action
                                )}
                                optionRender={(option: any) => (
                                  <div
                                    style={{
                                      display: 'flex',
                                      gap: '8px',
                                      alignItems: 'center',
                                    }}
                                  >
                                    <span
                                      style={{ display: 'flex' }}
                                      aria-label={option.data.label}
                                    >
                                      {option.data.icon}
                                    </span>
                                    <span style={{ color: '#8D8F90' }}>
                                      {option.data.label}
                                    </span>
                                  </div>
                                )}
                              />
                            </td>
                            <td style={{ width: '25%' }}>{product?.code}</td>
                            <td style={{ width: '25%' }}>
                              {product?.description}
                            </td>
                            <td style={{ width: '25%' }}>{product?.sku}</td>
                          </tr>

                          {isReturn && (
                            <tr>
                              <td colSpan={4}>
                                <ReturnRowWrapper>
                                  <StyledDropdown
                                    label="Return Action"
                                    required
                                    placeholder="Select action"
                                    options={returnActionOptions}
                                    onSelect={(val: any) =>
                                      onChange(
                                        val,
                                        product?.order_product_id!,
                                        'return_action'
                                      )
                                    }
                                    value={returnActionOptions?.filter(
                                      (option: any) =>
                                        option.value === product?.return_action
                                    )}
                                  />
                                  <StyledDropdown
                                    label="Return Reason"
                                    required
                                    placeholder="Select reason"
                                    options={returnReasonsOptions}
                                    onSelect={(val: any) =>
                                      onChange(
                                        val,
                                        product?.order_product_id!,
                                        'return_reason'
                                      )
                                    }
                                    value={returnReasonsOptions?.filter(
                                      (option: any) =>
                                        option.value === product?.return_reason
                                    )}
                                  />
                                </ReturnRowWrapper>
                              </td>
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </StyledTable>
      </StyledTableWrapper>
    </div>
  );
};

const CustomSelectDropdown: any = styled(Select)`
  .ant-select-selector {
    border-radius: 25px !important;
    /* border: none !important; */
    min-width: 100px;
    padding: 0 10px;
    display: flex;
    gap: 10px;
    align-items: center;

    .ant-select-prefix {
      margin-top: 3px;
    }
  }
  .ant-select-selection-item {
    font-weight: 400;
    font-size: 13px;
  }
`;

export const StyledTableWrapper = styled.div`
  width: 100%;
  overflow-x: auto;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px;
`;

const StyledDropdown = styled(OrderActionsDropdown)`
  flex: 1;
`;

export const StyledTable = styled.table`
  width: 100%;
  font-size: 14px;
  color: #333;
  border-spacing: 0 10px;

  th,
  td {
    padding: 12px 16px;
    background: #fff;
  }

  th {
    background: #f0f2f2;

    &:first-child {
      border-top-left-radius: 40px;
      border-bottom-left-radius: 40px;
    }

    &:last-child {
      border-top-right-radius: 40px;
      border-bottom-right-radius: 40px;
    }
  }

  // This affects ONLY top-level rows
  > tbody > tr {
    background: #fff;
    border-radius: 40px;
    box-shadow: 0px 1px 3px rgba(16, 24, 40, 0.1);
  }

  // Round the outer row's corners only on first/last td
  > tbody > tr > td:first-child {
    border-top-left-radius: 40px;
    border-bottom-left-radius: 40px;
  }

  > tbody > tr > td:last-child {
    border-top-right-radius: 40px;
    border-bottom-right-radius: 40px;
  }

  .scrollClass {
    overflow-x: auto;
  }

  .emptyTd {
    text-align: center;
    padding: 40px 0;
    color: #999;
    background: transparent;
    box-shadow: none;
  }

  td table {
    border-spacing: 0;
    width: 100%;
  }

  td table td {
    background: transparent;
    padding: 8px 12px;
  }
`;

const ReturnRowWrapper = styled.div`
  display: flex;
  flex-direction: row;
  gap: 12px;
  padding: 0 12px;
  width: 100%;
`;

export default CancelOrderTable;
