import React, { useEffect, useState } from 'react';
import InputAutoComplete from '@/components/form/InputAutoComplete';
import { getLocalitiesByCityId } from '@/app/cities/service';
import { notification } from 'antd';

interface LocalityDropdownProps {
  onSelect?: (value: number | string) => void;
  onChange?: (
      value: string | number,
      item:
          | { value: number | string; label: React.ReactNode }
          | Array<{ value: number | string; label: React.ReactNode }>
  ) => void
  filter?: {
    status?: string;
  };
  name?: string;
  label?: string;
  mode?: 'multiple' | undefined;
  placeholder?: string;
  onClear?: () => void;
  [key: string]: unknown;
  city_id: number;
}

const MasterLocalities: React.FC<LocalityDropdownProps> = ({
  onSelect,
  onClear,
  name = 'locality_name',
  label,
  mode,
  placeholder = 'Locality',
  onChange,
  city_id,
  ...rest
}) => {
  const [localityOptions, setLocalityOptions] = useState<
    Array<{ value: number | string; label: string }>
  >([]);

  const [loading, setLoading] = useState(true);
  useEffect(() => {
    fetchLocalities();
  }, [city_id]);

  const fetchLocalities = (search?: string): void => {
    getLocalitiesByCityId(city_id | 0, { search })
      .then((res) => {
        setLoading(false);
        const formatData = res?.data?.data?.map(
          (locality: { name: string }) => ({
            value: locality?.name,
            label: locality?.name,
          }),
        );
        setLocalityOptions(formatData);
      })
      .catch((error) => {
        notification.error({
          message: error?.message,
          description: error?.response?.data?.message,
        });
      });
  };

  return (
    <InputAutoComplete
      loading={loading}
      name={name}
      label={label}
      mode={mode}
      placeholder={placeholder}
      onChange={(value, item) => {
        if (onChange) {
          onChange(value, item);
        }
      }}
      options={localityOptions}
      onSelect={(value) => {
        if (onSelect) {
          onSelect(value);
        }
      }}
      isSearchable={true}
      onSearch={fetchLocalities}
      onClear={() => {
        fetchLocalities();
        if (onClear !== undefined) {
          onClear();
        }
      }}
      {...rest}
    />
  );
};

export default MasterLocalities;
