import React, { useEffect, useRef, useState } from 'react';
import { Form, Card } from 'antd';
import InputSearch from '@/components/form/InputSearch';

import MasterCities from '@/components/masterDropdowns/MasterCities';
import MasterRoles from '@/components/masterDropdowns/MasterRoles';
import MasterDesignations from '@/components/masterDropdowns/MasterDesignations';
import InputSelect from '@/components/form/InputSelect';
import { useRoles } from '@/hooks/useRoles';
interface FilterPopupProps {
    onSearch: (filter: any) => void
    defaultFilter: {
        cities:
        | Array<{
            city_name: string
            city_id: number
        }>
        | undefined
    }
}

const FilterPopup: React.FC<FilterPopupProps> = ({ onSearch, defaultFilter }) => {
  const inputSearchRef = useRef<any>(null);
  const { getRoleByName } = useRoles();
  const cityOptions = defaultFilter.cities?.map((city) => ({
    value: city.city_id,
    label: city.city_name,
  }));

  const [form] = Form.useForm();
  const [filter, setFilter] = useState({
    page: 1,
    city_id: cityOptions?.map((city) => city.value).join(','),
  });

  const statusOptions = [
    { value: 'active', label: 'Active' },
    { value: 'inactive', label: 'Inactive' },
    { value: 'blocked', label: 'Blocked' },
  ];

  const handleSearch = (filter: any): void => {
    onSearch(filter);
  };

  const handleSearchChange = (updatedFilter: any): void => {
    const newFilter = {
      ...filter,
      ...updatedFilter,
    };
    setFilter(newFilter);
    handleSearch(newFilter);
  };
  /* This will trigger onSearch('') for the input search without any enter */
  useEffect(() => {
    inputSearchRef.current?.clear();
  }, []);
  return (
    <Card size="small" className="mb-3">
      <Form form={form} layout="inline" className="custom-filter-horizontal">
        <div className="custom-filter-horizontal-label">
          <Form.Item label="Filter:"></Form.Item>
        </div>
        <div className="custom-filter-horizontal-content">
          <InputSearch
            forwardRef={inputSearchRef}
            onSearch={(search) => {
              const param = {
                ...filter,
                search: search,
              };
              setFilter(param);
              onSearch(param);
            }}
            className="ml-0"
          />
          <MasterDesignations
            style={{ width: '150px' }}
            onSelect={(value) => {
              const param = {
                ...filter,
                designation_id: value,
              };
              setFilter(param);
              onSearch(param);
            }}
            onClear={() => {
              handleSearchChange({ designation_id: null });
            }}
          />
          <MasterRoles
            style={{ width: '150px' }}
            onSelect={(value) => {
              const param = {
                ...filter,
                role_id: value,
              };
              setFilter(param);
              onSearch(param);
            }}
            filter={{
              exclude_id: getRoleByName('super_admin')?.id,
            }}
            onClear={() => {
              handleSearchChange({ role_id: null });
            }}
          />
          {cityOptions && cityOptions?.length > 0 ? (
            <InputSelect
              name="city"
              placeholder="City"
              options={cityOptions}
              style={{ width: 150 }}
              onSelect={(value) => {
                const param = {
                  ...filter,
                  city_id: value || cityOptions?.map((city) => city.value).join(','),
                };
                setFilter(param);
                onSearch(param);
              }}
              onClear={() => { }}
            />
          ) : (
            <MasterCities
              style={{ width: '150px' }}
              onSelect={(value) => {
                const param: any = {
                  ...filter,
                  city_id: value,
                };
                setFilter(param);
                onSearch(param);
              }}
              onClear={() => {
                handleSearchChange({ city_id: null });
              }}
            />
          )}
          <InputSelect
            name="status"
            style={{ width: '100px' }}
            placeholder="Status"
            options={statusOptions}
            onSelect={(value) => {
              // "Blocked" is stored as the existing users.is_blocked flag,
              // independent of the active/inactive status column.
              const isBlockedSelected = value === 'blocked';
              form.setFieldsValue({ status: value });
              handleSearchChange({
                status: isBlockedSelected ? undefined : value,
                is_blocked: isBlockedSelected ? true : undefined,
              });
            }}
          />
        </div>
      </Form>
    </Card>
  );
};

export default FilterPopup;
