/* eslint-disable @typescript-eslint/no-explicit-any */

import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Form } from 'antd';
import InputSearch from '@/components/form/InputSearch';
import InputSelect from '@/components/form/InputSelect';
import {
  fetchFilterBudgetList,
  fetchFilterConfiguration,
  fetchFilterProjectList,
  fetchFilterLocalityList,
  fetchLeadStatus,
} from '../slice';
import { useDispatch, useSelector } from 'react-redux';
import type { configList, filterI, projectListI } from '../interface';
import type { AppDispatch, RootState } from '@/store/store';
// import SelectDropdown from '@/components/form/SelectDropdown';
import { useWatch } from 'antd/es/form/Form';
import DateRangeFilter from './DateRangeFilter';
import InputSelectAndSearch from '@/components/form/InputSelectAndSearch';
import { NRIFilterOptions, inquiry_sourceOptions, LEAD_TAGS, TRANSFER_FILTER_OPTIONS } from '../constant';

interface FilterI {
    onSearch: (filter: any) => void
    filters: filterI
    setFilters: any
    forwardRef: React.Ref<{ clearFilter: (filter: any) => void }>
    selectedMenuItem: string
    showLeadsCalendar: boolean
    hideTagFilter?: boolean
    initialDateRange?: [string, string] | null
}

interface compFilterI {
    search: string
    which_configuration_you_are_looking_for_: string
    whats_your_tentative_budget_: string
    status_id: string
    project_id:string,
}

const FilterLeads: React.FC<FilterI> = forwardRef(
  ({ onSearch, setFilters, filters, forwardRef, selectedMenuItem, showLeadsCalendar, hideTagFilter, initialDateRange }) => {
    const dispatch: AppDispatch = useDispatch();
    const inputSearch = useRef<any>(null);
    const hasTriggeredInitialSearch = useRef(false);
    const [form] = Form.useForm();
    // const status_id = useWatch('status_id', form);
    // const project_id = useWatch('project_id', form);
    const configList = useSelector((state: RootState) => state?.allLeads?.configurationList);
    const leadStatus = useSelector((state: RootState) => state?.allLeads?.leadStatus);
    const filterProjectLList = useSelector((state: RootState) => state?.allLeads?.filterProjectLList);
    const projectListHasMore = useSelector((state: RootState) => state?.allLeads?.projectListHasMore);
    const filterLocalityLList = useSelector((state: RootState) => state?.allLeads?.filterLocalityLList);
    const localityListHasMore = useSelector((state: RootState) => state?.allLeads?.localityListHasMore);
    const { status } = useSelector((state: RootState) => state.allLeads);
    // const [projectPage, setProjectPage] = useState(1);
    const projectPageRef = useRef(1);
    const [projectSearch, setProjectSearch] = useState('');
    const localityPageRef = useRef(1);
    const [localitySearch, setLocalitySearch] = useState('');
    // const [projectListLoading, setProjectListLoading] = useState(false);

    const budgetListOptions = [
      {
        label: '10Lakh to 20Lakh',
        value: '1000000,2000000',
      },
      {
        label: '20Lakh to 30Lakh',
        value: '2000000,3000000',
      },
      {
        label: '30Lakh to 40Lakh',
        value: '3000000,4000000',
      },
      {
        label: '40Lakh to 50Lakh',
        value: '4000000,5000000',
      },
      {
        label: '50Lakh to 60Lakh',
        value: '5000000,6000000',
      },
      {
        label: '60Lakh to 70Lakh',
        value: '6000000,7000000',
      },
      {
        label: '70Lakh to 80Lakh',
        value: '7000000,8000000',
      },
      {
        label: '80Lakh to 90Lakh',
        value: '8000000,9000000',
      },
      {
        label: '90Lakh to 1Cr',
        value: '9000000,10000000',
      },
      {
        label: '1Cr to 1.2Cr',
        value: '10000000,12000000',
      },
      {
        label: '1.2Cr to 1.4Cr',
        value: '12000000,14000000',
      },
      {
        label: '1.4Cr to 1.6Cr',
        value: '14000000,16000000',
      },
      {
        label: '1.6Cr to 1.8Cr',
        value: '16000000,18000000',
      },
      {
        label: '1.8Cr to 2Cr',
        value: '18000000,20000000',
      },
      {
        label: '2Cr to 2.2Cr',
        value: '20000000,22000000',
      },
      {
        label: '2.2Cr to 2.4Cr',
        value: '22000000,24000000',
      },
      {
        label: '2.4Cr to 2.6Cr',
        value: '24000000,26000000',
      },
      {
        label: '2.6Cr to 2.8Cr',
        value: '26000000,28000000',
      },
      {
        label: '2.8Cr to 3Cr',
        value: '28000000,30000000',
      },
      {
        label: '3Cr to 3.2Cr',
        value: '30000000,32000000',
      },
      {
        label: '3.2Cr to 3.4Cr',
        value: '32000000,34000000',
      },
      {
        label: '3.4Cr to 3.6Cr',
        value: '34000000,36000000',
      },
      {
        label: '3.6Cr to 3.8Cr',
        value: '36000000,38000000',
      },
      {
        label: '3.8Cr to 4Cr',
        value: '38000000,40000000',
      },
      {
        label: '4Cr to 4.5Cr',
        value: '40000000,45000000',
      },
      {
        label: '4.5Cr to 5Cr',
        value: '45000000,50000000',
      },
      {
        label: '5Cr to 5.5Cr',
        value: '50000000,55000000',
      },
      {
        label: '5.5Cr to 6Cr',
        value: '55000000,60000000',
      },
      {
        label: '6Cr to 6.5Cr',
        value: '60000000,65000000',
      },
      {
        label: '6.5Cr to 7Cr',
        value: '65000000,70000000',
      },
      {
        label: '7Cr to 7.5Cr',
        value: '70000000,75000000',
      },
      {
        label: '7.5Cr to 8Cr',
        value: '75000000,80000000',
      },
      {
        label: '8Cr to 8.5Cr',
        value: '80000000,85000000',
      },
      {
        label: '8.5Cr to 9Cr',
        value: '85000000,90000000',
      },
      {
        label: '9Cr to 9.5Cr',
        value: '90000000,95000000',
      },
      {
        label: '9.5Cr to 10Cr',
        value: '95000000,100000000',
      },
      {
        label: '10Cr to 10.5Cr',
        value: '100000000,105000000',
      },
      {
        label: '10.5Cr to 11Cr',
        value: '105000000,110000000',
      },
      {
        label: '11Cr to 11.5Cr',
        value: '110000000,115000000',
      },
      {
        label: '11.5Cr to 12Cr',
        value: '115000000,120000000',
      },
      {
        label: '12Cr to 12.5Cr',
        value: '120000000,125000000',
      },
      {
        label: '12.5Cr to 13Cr',
        value: '125000000,130000000',
      },
      {
        label: '13Cr to 13.5Cr',
        value: '130000000,135000000',
      },
      {
        label: '13.5Cr to 14Cr',
        value: '135000000,140000000',
      },
      {
        label: '14Cr to 14.5Cr',
        value: '140000000,145000000',
      },
      {
        label: '14.5Cr to 15Cr',
        value: '145000000,150000000',
      },
      {
        label: '15Cr to 15.5Cr',
        value: '150000000,155000000',
      },
      {
        label: '15.5Cr to 16Cr',
        value: '155000000,160000000',
      },
      {
        label: '16Cr to 16.5Cr',
        value: '160000000,165000000',
      },
      {
        label: '16.5Cr to 17Cr',
        value: '165000000,170000000',
      },
      {
        label: '17Cr to 17.5Cr',
        value: '170000000,175000000',
      },
      {
        label: '17.5Cr to 18Cr',
        value: '175000000,180000000',
      },
      {
        label: '18Cr to 18.5Cr',
        value: '180000000,185000000',
      },
      {
        label: '18.5Cr to 19Cr',
        value: '185000000,190000000',
      },
      {
        label: '19Cr to 19.5Cr',
        value: '190000000,195000000',
      },
      {
        label: '19.5Cr to 20Cr',
        value: '195000000,200000000',
      },
      {
        label: '20Cr to 20.5Cr',
        value: '200000000,205000000',
      },
      {
        label: '20.5Cr to 21Cr',
        value: '205000000,210000000',
      },
      {
        label: '21Cr to 21.5Cr',
        value: '210000000,215000000',
      },
      {
        label: '21.5Cr to 22Cr',
        value: '215000000,220000000',
      },
      {
        label: '22Cr to 22.5Cr',
        value: '220000000,225000000',
      },
      {
        label: '22.5Cr to 23Cr',
        value: '225000000,230000000',
      },
      {
        label: '23Cr to 23.5Cr',
        value: '230000000,235000000',
      },
      {
        label: '23.5Cr to 24Cr',
        value: '235000000,240000000',
      },
      {
        label: '24Cr to 24.5Cr',
        value: '240000000,245000000',
      },
      {
        label: '24.5Cr to 25Cr',
        value: '245000000,250000000',
      },
      {
        label: '25Cr to 25.5Cr',
        value: '250000000,255000000',
      },
      {
        label: '25.5Cr to 26Cr',
        value: '255000000,260000000',
      },
      {
        label: '26Cr to 26.5Cr',
        value: '260000000,265000000',
      },
      {
        label: '26.5Cr to 27Cr',
        value: '265000000,270000000',
      },
      {
        label: '27Cr to 27.5Cr',
        value: '270000000,275000000',
      },
      {
        label: '27.5Cr to 28Cr',
        value: '275000000,280000000',
      },
      {
        label: '28Cr to 28.5Cr',
        value: '280000000,285000000',
      },
      {
        label: '28.5Cr to 29Cr',
        value: '285000000,290000000',
      },
      {
        label: '29Cr to 29.5Cr',
        value: '290000000,295000000',
      },
      {
        label: '29.5Cr to 30Cr',
        value: '295000000,300000000',
      },
      {
        label: '30Cr and Above',
        value: '300000000,999999999999999',
      },
    ];

    // Map lead status options from leadStatus array
    const leadStatusOptions = leadStatus?.map((status: projectListI) => ({
      value: status.id,
      label: status.name,
    }));

    // Memoize so the reference is stable across re-renders unrelated to data changes
    const launchProjectsOptions = useMemo(
      () => filterProjectLList?.map((project: projectListI) => ({
        value: project.id,
        label: project.name,
      })) ?? [],
      [filterProjectLList]
    );

    const localityOptions = useMemo(
      () => filterLocalityLList?.map((locality: projectListI) => ({
        value: locality.id,
        label: locality.name,
      })) ?? [],
      [filterLocalityLList]
    );

    // Map configuration options from configList array
    const configOptions = configList?.map((config: configList) => ({
      value: config.configuration_name,
      label: config.configuration_name,
    }));

    // Fetch initial data on component mount
    useEffect(() => {
      projectPageRef.current = 1;
      fetchProjectsList(1, '');
      localityPageRef.current = 1;
      fetchLocalityList(1, '');
      fetchConfigList();
      fetchProjectBudget();
      getLeadStatus();
    }, []);

    // Update form fields and search input on selected menu item change
    useEffect(() => {
      form.setFieldsValue({
        ...filters.filterTabs,
      });
      inputSearch.current?.setQuery(filters.search);
      // multi select for status drop down filter in all leads section
      form.setFieldValue('status_id', filters.status_id ? filters.status_id : []);
      form.setFieldValue('project_id', filters.project_id ? filters.project_id : []);
      form.setFieldValue('locality_id', filters.locality_id ? filters.locality_id : []);
      form.setFieldValue('status_history', (filters as any).status_history ? (filters as any).status_history : []);
    }, [selectedMenuItem]);

    // Function to fetch project list with pagination and search
    const fetchProjectsList = useCallback(async(page: number, search: string): Promise<void> => {
      await dispatch(fetchFilterProjectList({ page, pageSize: 10, search }));
    }, [dispatch]);

    const handleProjectLoadMore = useCallback((): void => {
      if (projectListHasMore && status !== 'loading') {
        const nextPage = projectPageRef.current + 1;
        projectPageRef.current = nextPage;

        fetchProjectsList(nextPage, projectSearch);
      }
    }, [projectListHasMore, status, projectSearch, fetchProjectsList]);

    // const handleProjectSearch = useCallback((search: string): void => {
    //   setProjectSearch(search);
    //   setProjectPage(1);
    //   fetchProjectsList(1, search);
    // }, [fetchProjectsList]);

    const handleProjectSearch = useCallback((search: string): void => {
      setProjectSearch(search);

      // Reset page ref instead of state
      projectPageRef.current = 1;

      fetchProjectsList(1, search);
    }, [fetchProjectsList]);

    // Function to fetch locality list with pagination and search
    const fetchLocalityList = useCallback(async(page: number, search: string): Promise<void> => {
      await dispatch(fetchFilterLocalityList({ page, pageSize: 10, search }));
    }, [dispatch]);

    const handleLocalityLoadMore = useCallback((): void => {
      if (localityListHasMore && status !== 'loading') {
        const nextPage = localityPageRef.current + 1;
        localityPageRef.current = nextPage;

        fetchLocalityList(nextPage, localitySearch);
      }
    }, [localityListHasMore, status, localitySearch, fetchLocalityList]);

    const handleLocalitySearch = useCallback((search: string): void => {
      setLocalitySearch(search);

      // Reset page ref instead of state
      localityPageRef.current = 1;

      fetchLocalityList(1, search);
    }, [fetchLocalityList]);

    // Function to fetch configuration list
    const fetchConfigList = (): void => {
      dispatch(fetchFilterConfiguration());
    };

    // Function to fetch project budget list
    const fetchProjectBudget = (): void => {
      dispatch(fetchFilterBudgetList());
    };

    // Function to fetch lead status
    const getLeadStatus = (): void => {
      dispatch(fetchLeadStatus());
    };

    // Expose clearFilter function using useImperativeHandle for parent component
    useImperativeHandle(
      forwardRef,
      () => ({
        clearFilter: async(filterVal: any) => {
          form.setFieldsValue({ ...filterVal });
          inputSearch.current?.setQuery('');
        },
      }),
      []
    );

    const handleFilterChange = (key: string, value: any) => {
      const fiData = { ...filters };
       if (key === 'status_id' && Array.isArray(value) && value.length === 0) {
           fiData[key as keyof compFilterI] = null as any;
       } else if (key === 'status_history') {
        (fiData as any).status_history = value && Array.isArray(value) && value.length > 0 ? value : null;
       } else if (key === 'project_id') {
        fiData.project_id = value && Array.isArray(value) && value.length > 0 ? value : '';
       } else if (key === 'locality_id') {
        fiData.locality_id = value && Array.isArray(value) && value.length > 0 ? value : '';
       } else {
           fiData[key as keyof compFilterI] = value;
       }
       Object.keys(fiData.filterTabs).forEach((tabKey) => {
           fiData.filterTabs[tabKey as keyof typeof fiData.filterTabs] = {
               ...fiData.filterTabs[tabKey as keyof typeof fiData.filterTabs],
               page: 1,
           };
      });
      const newFilters: filterI = { ...fiData };
      setFilters(newFilters);
      onSearch(newFilters);
    };

    // This function is called whenever the date range changes
    const handleDateChange = (range: string | null) => {
      const newFilters: filterI = { ...filters };

      if (range) {
        // Remove all single quotes and split the string by ' AND '
        const [startDate, endDate] = range.replace(/'/g, '').split(' AND ');
        newFilters.start_date = startDate;
        newFilters.end_date = endDate;
      } else {
        newFilters.start_date = '';
        newFilters.end_date = '';
      }

      setFilters(newFilters);
      onSearch(newFilters);
    };

    // this calls onSearch('') internally when user lands to the all leads table
    useEffect(() => {
      if (!hasTriggeredInitialSearch.current && inputSearch.current) {
        inputSearch.current.clear();
        hasTriggeredInitialSearch.current = true;
      }
    }, []);

    return (
      <Form name="myForm" layout="inline" form={form} className="custom-filter-horizontal flex-1">
        {!showLeadsCalendar && (
          <>
            <div className="custom-filter-horizontal-content">
              <InputSearch
                forwardRef={inputSearch}
                name="search"
                label="search"
                placeholder='Name/Contact/Remark'
                onSearch={(search) => {
                  handleFilterChange('search', search || '');
                }}
                className="ml-0"
                disabled={status === 'loading'}
              />
              <InputSelect
                name="which_configuration_you_are_looking_for_"
                placeholder="Config"
                label=""
                style={{ width: '190px' }}
                className="w-12	"
                isSearchable={true}
                options={configOptions}
                onSelect={(value) => {
                  handleFilterChange(
                    'which_configuration_you_are_looking_for_',
                    value
                  );
                }}
                disabled={status === 'loading'}
              />

              <InputSelect
                mode="multiple"
                isSearchable={true}
                name="source"
                options={inquiry_sourceOptions}
                style={{ width: '160px' }}
                placeholder="Source"
                className="w-12	"
                label=""
                onSelect={(value) => {
                  handleFilterChange('source', value);
                }}
                disabled={status === 'loading'}
              />

              <InputSelect
                name="whats_your_tentative_budget_"
                placeholder="Budget"
                label=""
                style={{ width: '200px' }}
                isSearchable={true}
                className="w-12	"
                options={budgetListOptions}
                onSelect={(value) => {
                  handleFilterChange('whats_your_tentative_budget_', value);
                }}
                disabled={status === 'loading'}
              />

              {/* {!(selectedMenuItem === 'scheduled') && (
                <Form.Item name={'status_id'} >
                  <InputSelect
                    mode="multiple"
                    isSearchable={false}
                    name="status_id"
                    placeholder="Status"
                    value={status_id}
                    label=""
                    style={{ width: '160px' }}
                    options={leadStatusOptions}
                    onChange={(value) => {
                      handleFilterChange('status_id', value);
                    }}
                    disabled={status === 'loading'}
                  />
                </Form.Item>

              )} */}
              {!(selectedMenuItem === 'scheduled') && (
                <InputSelect
                  mode="multiple"
                  isSearchable={false}
                  name="status_id"
                  placeholder="Status"
                  // value={status_id}
                  label=""
                  style={{ width: '160px' }}
                  options={leadStatusOptions}
                  onSelect={(value) => {
                    handleFilterChange('status_id', value);
                  }}
                  disabled={status === 'loading'}
                />
              )}

              <Form.Item name={'project_id'}>
                <InputSelectAndSearch
                  mode="multiple"
                  label=""
                  name="project_id"
                  placeholder="Project"
                  options={launchProjectsOptions}
                  style={{ width: '200px', marginRight: '0px' }}
                  onChange={(value) => {
                    handleFilterChange('project_id', value);
                  }}
                  disabled={status === 'loading'}
                  loading={status === 'loading'}
                  onSearchServer={handleProjectSearch}
                  handleLoadMore={handleProjectLoadMore}
                  hideSelectAll
                />
              </Form.Item>

               <Form.Item name={'locality_id'}>
                <InputSelectAndSearch
                  mode="multiple"
                  label=""
                  name="locality_id"
                  placeholder="Locality"
                  options={localityOptions}
                  style={{ width: '200px', marginRight: '0px' }}
                  onChange={(value) => {
                    handleFilterChange('locality_id', value);
                  }}
                  disabled={status === 'loading'}
                  loading={status === 'loading'}
                  onSearchServer={handleLocalitySearch}
                  handleLoadMore={handleLocalityLoadMore}
                  hideSelectAll
                />
              </Form.Item>

              <InputSelect
                isSearchable={false}
                name="isNRI"
                placeholder="NRI Filter"
                label=""
                style={{ width: '120px' }}
                options={NRIFilterOptions}
                onChange={(value) => {
                  handleFilterChange('isNRI', value);
                }}
                disabled={status === 'loading'}
              />

              {!hideTagFilter && (
                <InputSelect
                  isSearchable={true}
                  name="tag"
                  placeholder="Tag"
                  label=""
                  style={{ width: '120px' }}
                  options={LEAD_TAGS}
                  onChange={(value) => {
                    handleFilterChange('tag', value);
                  }}
                  disabled={status === 'loading'}
                />
              )}

              <InputSelect
                isSearchable={false}
                name="is_transferred"
                placeholder="Transfer Status"
                label=""
                style={{ width: '160px' }}
                options={TRANSFER_FILTER_OPTIONS}
                onChange={(value) => {
                  handleFilterChange('is_transferred', value);
                }}
                disabled={status === 'loading'}
              />

              {selectedMenuItem === 'overdue' && (
                <InputSelect
                  mode="multiple"
                  isSearchable={false}
                  name="status_history"
                  placeholder="History Visits"
                  label=""
                  style={{ width: '180px' }}
                  options={[
                    { value: 14, label: 'Site Visit Done' },
                    { value: 15, label: 'VC Done' },
                    { value: 16, label: 'OBM Done' },
                  ]}
                  onSelect={(value) => {
                    handleFilterChange('status_history', value && value.length > 0 ? value : null);
                  }}
                  disabled={status === 'loading'}
                />
              )}

              <div>{(selectedMenuItem === 'visited' || selectedMenuItem === 'token_done' || selectedMenuItem === 'booked'|| selectedMenuItem === 'all_leads' || selectedMenuItem === 'dead') && (<DateRangeFilter onDateChange={handleDateChange} initialRange={initialDateRange} />)}</div>
            </div>
          </>
        )}
      </Form>
    );
  }
);

FilterLeads.displayName = 'FilterLeads';
export default FilterLeads;
