import React, { useEffect, useState } from 'react';
import {
  LeftSideConatiner,
  StyledFIlterELements,
  StyledFiter,
} from '../../filters/FilterStyle';
import TableFilters from './TableFilters';
import FilterIcon from '../../../../assets/icons/FilterIcon';
import DateIcon from '../../../../assets/icons/DateIcon';
// import StatusIcon from '../../../../assets/icons/StatusIcon';
import ClientIcon from '../../../../assets/icons/ClientIcon';
// import AssigneIcon from '../../../../assets/icons/AssigneIcon';
import { DatePicker, Select } from 'antd';
import { useAtom } from '../../../order-view/store';
import styled from 'styled-components';
import dayjs from 'dayjs';
import {
  useAssignData,
  // useCustomerData,
  useStatusOrderData,
} from '../../../store';
import StatusIcon from '../../../../assets/icons/StatusIcon';
import AssigneIcon from '../../../../assets/icons/AssigneIcon';
import {
  ClearAll,
  StyledFilterBtnIcon,
  StyledFilterBtnLabel,
} from '../../table/table-data/styles';
import { filtersReducerReturnAtom } from './ReturnFilterStore';
import { useAxios } from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../../common/interface';

const ReturnOrderFilter = () => {
  const [, dispatch] = useAtom(filtersReducerReturnAtom);
  // const [customers] = useCustomerData();
  const [selectedDate, setSelectedDate] = useState<any | null>();
  const [statusOfOrder] = useStatusOrderData();
  const [selectedClient, setSelectedClient] = useState<any | null>();
  const [statusOrder, setStatusOfOrder] = useState<any | null>();
  const [selectedAssignee, setSelectedAssignee] = useState<any | null>();
  const [assignData] = useAssignData();

  //API for client data
  const { data: fetchedCustomerData, fetchData } = useAxios<ApiResponse>({
    endpoint: `/v1/return/order/customers/`,
    method: 'GET',
    //@ts-ignore
    pagination: { is_pagination: false },
  });

  useEffect(() => {
    fetchData();
  }, []);

  // date change here
  const handleDateChange = (date: any | null) => {
    setSelectedDate(date ? date?.$d : null);
  };
  useEffect(() => {
    if (selectedDate) {
      dispatch({
        type: 'SET_DATE_FILTER',
        payload: selectedDate,
      });
      // Reset to the first page
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    }
  }, [selectedDate]);
  //client options
  const clientOptions = fetchedCustomerData?.data?.map((option: any) => ({
    label:
      option?.customer_name?.charAt(0)?.toUpperCase() +
      option?.customer_name?.slice(1),
    value: option?.customer_id,
  }));
  //status of order
  const orderOptions = statusOfOrder?.map((option: any) => ({
    label:
      option?.status_type?.charAt(0)?.toUpperCase() +
      option?.status_type?.slice(1),
    value: option?.type,
  }));
  const handleClientChange = (value: any) => {
    if (value === selectedClient) return;
    setSelectedClient(value);
    dispatch({
      type: 'SET_CLIENT_FILTER',
      payload: value,
    });
    // Reset to the first page
    dispatch({
      type: 'SET_PAGE',
      payload: 1,
    });
  };
  const handleStatusOfOrder = (value: any) => {
    if (value === statusOfOrder) return;
    setStatusOfOrder(value);
    dispatch({
      type: 'SET_STATUS_ORDER_FILTER',
      payload: value,
    });
    // Reset to the first page
    dispatch({
      type: 'SET_PAGE',
      payload: 1,
    });
  };

  const assigneeOptions = assignData?.map(client => ({
    label: client.type,
    value: client.id,
  }));

  const handleAssigneeChange = (value: any) => {
    const bjsDeliveryValue = assignData.find(client => client.id === value)
      ?.bjs_delivery;
    if (bjsDeliveryValue === undefined) return;
    setSelectedAssignee(value);
    dispatch({
      type: 'SET_ASSIGNEE_FILTER',
      payload: bjsDeliveryValue,
    });
    dispatch({
      type: 'SET_PAGE',
      payload: 1,
    });
  };

  const handleClearAssignee = () => {
    setSelectedAssignee(null);
    dispatch({
      type: 'SET_ASSIGNEE_FILTER',
      payload: null,
    });
    dispatch({
      type: 'SET_PAGE',
      payload: 1,
    });
  };

  const handleClearAll = () => {
    setSelectedDate(null);
    setSelectedClient(null);
    setStatusOfOrder(null);
    setSelectedAssignee(null);
    dispatch({ type: 'CLEAR_ALL_FILTER' });
  };

  const handleClear = () => {
    dispatch({
      type: 'CLEAR_STATUS_ORDER_FILTER',
    });

    setStatusOfOrder(null);
  };

  const handleClearClient = () => {
    dispatch({
      type: 'CLEAR_CLIENT_FILTER',
    });
    setSelectedClient(null);
  };
  //clearing filters
  useEffect(() => {
    if (selectedDate === null) {
      dispatch({ type: 'CLEAR_DATE' });
    }
  }, [selectedDate]);

  return (
    <>
      <StyledFiter>
        <StyledFIlterELements>
          <LeftSideConatiner>
            <div className="filtercontainer">
              <div className="filtericon">
                <FilterIcon />
              </div>
              <div className="textcont">Filters</div>
            </div>
            <div className="datefilter">
              <div className="dateiconcontainer">
                <DateIcon />
              </div>
              <StyledDatePicker>
                <DatePicker
                  className="custom-datepicker"
                  onChange={handleDateChange}
                  style={{ width: '100px' }}
                  value={selectedDate ? dayjs(selectedDate) : null}
                  format="DD/MM/YY"
                  placeholder="Date"
                  needConfirm
                  allowClear
                />
              </StyledDatePicker>
            </div>
            <div className="datefilter">
              <div className="dateiconcontainer">
                <StatusIcon />
              </div>
              <StyledAntSelect>
                <Select
                  options={orderOptions}
                  className="custom-select"
                  placeholder="Status of Order"
                  onChange={handleStatusOfOrder}
                  style={{ minWidth: '250px', maxWidth: '300px' }}
                  value={statusOrder}
                  onClear={handleClear}
                  allowClear
                />
              </StyledAntSelect>
            </div>
            <div className="datefilter">
              <div className="dateiconcontainer">
                <ClientIcon />
              </div>
              <StyledAntSelect>
                <Select
                  options={clientOptions}
                  className="custom-select"
                  placeholder="Clients"
                  onChange={handleClientChange}
                  value={selectedClient}
                  style={{
                    minWidth: '150px',
                    width: 'auto',
                    cursor: 'pointer',
                  }}
                  allowClear
                  onClear={handleClearClient}
                  filterOption={(input: any, option: any) =>
                    (option?.label ?? '')
                      .toLowerCase()
                      .includes(input.toLowerCase())
                  }
                  showSearch
                />
              </StyledAntSelect>
            </div>

            <div className="datefilter">
              <div className="dateiconcontainer">
                <AssigneIcon />
              </div>
              <StyledAntSelect>
                <Select
                  options={assigneeOptions}
                  className="custom-select"
                  placeholder="Assignee"
                  onChange={handleAssigneeChange}
                  value={selectedAssignee}
                  style={{ minWidth: '140px' }}
                  allowClear
                  onClear={handleClearAssignee}
                />
              </StyledAntSelect>
            </div>

            {selectedDate ||
            statusOrder ||
            selectedClient ||
            selectedAssignee ? (
              <>
                <ClearAll onClick={handleClearAll}>
                  <StyledFilterBtnIcon>
                    <i className="cross"></i>
                  </StyledFilterBtnIcon>
                  <StyledFilterBtnLabel>Clear all</StyledFilterBtnLabel>
                </ClearAll>
              </>
            ) : null}
          </LeftSideConatiner>
        </StyledFIlterELements>
        <TableFilters />
      </StyledFiter>
    </>
  );
};
const StyledDatePicker = styled.div`
  .custom-datepicker {
    border: none;
  }
`;
// const DropdownContainer = styled.div``;
export const StyledAntSelect = styled.div`
  .custom-select {
    border: none;
    width: 80px;
  }
  .ant-select-selector {
    border: 1px solid #ffffff !important;
  }
  :where(.css-dev-only-do-not-override-m4timi).ant-select-single:not(.ant-select-customize-input)
    .ant-select-selector {
    padding: 0 5px;
  }
  :where(.css-dev-only-do-not-override-m4timi).ant-select-outlined:not(.ant-select-customize-input)
    .ant-select-selector {
    border: none;
  }
  .roundbox {
    display: flex;
    width: 18px;
    height: 18px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 18px;
    background: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.1);
    left: 359px;
    position: absolute;
    border-radius: 18px;
    background: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.1);
    top: 16px;
  }
  .ant-select-clear {
    top: 40% !important;
    font-size: 18px !important;
  }
`;
export default ReturnOrderFilter;
