import React, { useEffect, useState } from 'react';
import {
  ApplyButton,
  FilterColumn,
  FilterRow,
  Label,
  LeftColumn,
  RightColumn,
  Wrapper,
} from './Styledfilters';
import { atom, useAtom } from 'jotai';
import {
  useActionTypeOptions,
  useClearState,
  useCustomerData,
  useReturnPayload,
} from '../../store';
import { filtersReducerAtom } from './filterStore';
import {
  useSelectedAction,
  useSelectedClient,
  useSelectedLocation,
  useLoading,
} from '../store/store';
import styled from 'styled-components';
import { Select } from 'antd';
import { useLocationOptions } from '../../order-view/store';
import { useNavigate, useSearchParams } from 'react-router-dom';

export const clickedState = atom<boolean>(false);

function SelectionFilter() {
  const [customers] = useCustomerData();
  const [selectedFilterValue, setSelectedFilterValue] = useSelectedAction();
  const [, dispatch] = useAtom(filtersReducerAtom);
  const [
    selectedLocationValue,
    setSelectedLocationValue,
  ] = useSelectedLocation();
  const [selectedClient, setSelectedClient] = useSelectedClient();
  const [isButtonEnabled, setIsButtonEnabled] = useState(false);
  const [, setReturnPayload] = useReturnPayload();
  const [load] = useLoading();
  const [clearState, setClear] = useClearState();
  const [actionTypeOptions, setActionTypeOptions] = useActionTypeOptions();
  const [locationOptions, setLocationOptions] = useLocationOptions();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  //new codee
  const urlCustomerId = searchParams.get('customerId');
  const urlActiontype = searchParams.get('type');

  const selectedCustomer = customers?.find(
    (customer: any) => customer?.customer_id?.toString() === urlCustomerId
  );

  const accountNumber = selectedCustomer?.account_number;

  //customer name
  const clientOptions = customers
    ?.filter(
      (option: any) => 'customer_id' in option && option.customer_id != null
    )
    .map((option: any) => ({
      label:
        option?.customer_name?.charAt(0)?.toUpperCase() +
        option?.customer_name?.slice(1),
      value: option?.customer_id,
      actions: option?.actions,
      return_locations: option?.return_locations,
      account_number: option?.account_number,
    }));

  //client change
  const handleClientChange = (value: any, option: any) => {
    setSelectedClient(value);

    const filteredClient = clientOptions?.find(
      (client: any) => client?.value == value
    );

    if (filteredClient) {
      const mappedActions = Array.isArray(filteredClient?.actions)
        ? filteredClient?.actions?.map((action: any) => ({
            label: action,
            value: action,
          }))
        : [];

      setActionTypeOptions(mappedActions);

      const mappedLocations = Array.isArray(filteredClient?.return_locations)
        ? filteredClient?.return_locations?.map((location: any) => ({
            label: location?.location_name,
            value: location?.token,
          }))
        : [];

      setLocationOptions(mappedLocations);
    }

    //set payload
    setReturnPayload((prevState: any) => ({
      ...prevState,
      account_number: option?.account_number,
      customer_id: +value,
    }));
  };

  useEffect(() => {
    if (urlCustomerId && accountNumber) {
      setReturnPayload((prevState: any) => ({
        ...prevState,
        account_number: accountNumber,
        customer_id: +urlCustomerId,
      }));
    }
  }, [accountNumber, urlCustomerId]);

  useEffect(() => {
    if (urlCustomerId) {
      const filteredClient = clientOptions?.find(
        (client: any) => client?.value == urlCustomerId
      );

      if (filteredClient) {
        const mappedActions = Array.isArray(filteredClient?.actions)
          ? filteredClient?.actions?.map((action: any) => ({
              label: action,
              value: action,
            }))
          : [];

        setActionTypeOptions(mappedActions);

        const mappedLocations = Array.isArray(filteredClient?.return_locations)
          ? filteredClient?.return_locations?.map((location: any) => ({
              label: location?.location_name,
              value: location?.token,
            }))
          : [];

        setLocationOptions(mappedLocations);
      }
    }
  }, [load]);

  //location change
  const handleLocationChange = (value: any) => {
    setSelectedLocationValue(value);
  };

  //action type
  const handleActionClick = (value: any) => {
    setSelectedFilterValue(value);
  };

  //Apply filters
  const applyFilters = () => {
    if (selectedClient) {
      const queryParams = new URLSearchParams({
        customerId: selectedClient?.toString(),
      });
      const currentSearch = window.location.search;
      console.log(currentSearch, 'currentSearch');

      if (!currentSearch.includes('filter')) {
        console.log('inside include');
        // for dev
        //navigate(`filter?${queryParams.toString()}`);
        navigate(`/orders/view/return/filter?${queryParams.toString()}`);

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

    const selectedClientValue = clientOptions?.find(
      (client: any) => client?.value === selectedClient
    );

    const clientActions = selectedClientValue?.actions || [];
    const clientLocations = selectedClientValue?.return_locations || [];

    setActionTypeOptions(
      Array.isArray(clientActions)
        ? clientActions?.map(action => ({
            label: action,
            value: action,
          }))
        : []
    );

    setLocationOptions(
      Array.isArray(clientLocations)
        ? clientLocations?.map(location => ({
            label: location?.location_name,
            value: location?.token,
          }))
        : []
    );

    //client value
    if (urlCustomerId) {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: urlCustomerId,
      });
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    } else {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: [],
      });
    }
    //action value
    if (selectedFilterValue) {
      dispatch({
        type: 'SET_ACTIONS_FILTER',
        payload: selectedFilterValue,
      });
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    }
    //location value
    if (selectedLocationValue && selectedLocationValue?.length > 0) {
      dispatch({
        type: 'SET_LOCATION_FILTER',
        payload: selectedLocationValue,
      });
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    }
  };

  useEffect(() => {
    if (selectedClient || selectedFilterValue || selectedLocationValue) {
      setIsButtonEnabled(true);
    } else {
      setIsButtonEnabled(false);
    }
  }, [selectedClient, selectedFilterValue, selectedLocationValue]);

  useEffect(() => {}, [location.pathname]);

  useEffect(() => {
    if (!selectedFilterValue || selectedFilterValue === null) {
      dispatch({ type: 'CLEAR_ACTION' });
    }
    if (
      !selectedLocationValue ||
      (Array.isArray(selectedLocationValue) &&
        selectedLocationValue.length === 0)
    ) {
      dispatch({ type: 'CLEAR_LOC' });
    }
  }, [selectedFilterValue, selectedLocationValue]);

  const handleClear = () => {
    setClear(false);
    dispatch({ type: 'CLEAR_CLIENT' });
    setClear(true);
  };

  useEffect(() => {
    if (clearState) {
      dispatch({ type: 'CLEAR_CLIENT' });
      window.location.href = '/orders/view/return/';
    }
  }, [clearState]);

  useEffect(() => {
    if (urlCustomerId && urlActiontype) {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: urlCustomerId,
      });
      setSelectedClient(+urlCustomerId);

      dispatch({
        type: 'SET_ACTIONS_FILTER',
        payload: urlActiontype,
      });
      setSelectedFilterValue(urlActiontype);

      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    } else if (urlCustomerId) {
      dispatch({
        type: 'SET_CLIENT_FILTER',
        payload: urlCustomerId,
      });
      setSelectedClient(+urlCustomerId);
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    }
  }, [urlCustomerId]);

  const handleClearAction = () => {
    dispatch({ type: 'CLEAR_ACTION' });

    const searchParams = new URLSearchParams(window.location.search);
    searchParams.delete('type');

    navigate(`?${searchParams.toString()}`, { replace: true });
  };

  return (
    <>
      <Wrapper>
        <FilterRow>
          <LeftColumn>
            <FilterColumn>
              <Label>Clients</Label>
              <StyledAntSelect
                options={clientOptions}
                placeholder="Select Client Name"
                onChange={handleClientChange}
                style={{ minWidth: '150px' }}
                value={selectedClient}
                allowClear
                onClear={handleClear}
                filterOption={(input: any, option: any) =>
                  (option?.label ?? '')
                    .toLowerCase()
                    .includes(input.toLowerCase())
                }
                showSearch
              />
            </FilterColumn>
            {selectedClient && (
              <>
                <FilterColumn>
                  <Label>Action Type</Label>
                  <StyledAntSelect
                    options={actionTypeOptions}
                    placeholder="Select Action Type"
                    value={selectedFilterValue}
                    onChange={handleActionClick}
                    style={{ minWidth: '150px' }}
                    allowClear
                    onClear={handleClearAction}
                  />
                </FilterColumn>

                <FilterColumn>
                  <Label>Location </Label>
                  <StyledAntSelect
                    options={locationOptions}
                    value={selectedLocationValue}
                    placeholder="Select Location"
                    onChange={handleLocationChange}
                    style={{ minWidth: '150px' }}
                    allowClear
                    mode="multiple"
                  />
                </FilterColumn>
              </>
            )}
          </LeftColumn>
          <RightColumn>
            <ApplyButton onClick={applyFilters} disabled={!isButtonEnabled}>
              Apply
            </ApplyButton>
          </RightColumn>
        </FilterRow>
      </Wrapper>
    </>
  );
}

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

export default SelectionFilter;
