import React, { forwardRef, useImperativeHandle, useState } from 'react';
import InputAutoComplete from '@/components/form/InputAutoComplete';
import { getConfiguration } from '@/app/configuration/service';
import type { ListMeta } from '@/interfaces/common';
interface options {
    value: number | string
    label: string
}
interface ConfigurationDropdownProps {
    onSelect?: (value: number | string) => void
    onChange?: (
        value: number | string,
        item: { value: number | string; label: string } | Array<{ value: number | string; label: string }>
    ) => void
    onClear?: () => void
    name?: string
    label?: string
    placeholder?: string
    filter?: {
        project_id?: number | string
        status?: string
    }
    useLabelInValue?: boolean
    [key: string]: any
}
interface MasterConfigurationProps extends ConfigurationDropdownProps {
    // Add a ref parameter
    forwardRef?: React.Ref<{
        reload: (filter: any) => void
        filterOptions: (filterOptions: (options: options[]) => options[]) => void
     }>
}
const MasterConfigurations: React.FC<MasterConfigurationProps> = forwardRef(
  (
    {
      onSelect,
      onChange,
      name = 'configuration_id',
      label,
      placeholder = 'Please Select Configuration',
      onClear,
      forwardRef,
      filter = [],
      useLabelInValue = false,
      ...rest
    },
  ) => {
    const [configurationOptions, setConfigurationOptions] = useState<
            Array<{ value: number | string; label: string }>
        >([]);

    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState<string>('');
    const [meta, setMeta] = useState<ListMeta>({
      total: 0,
      count: 0,
      per_page: 0,
      current_page: 1,
      total_pages: 1,
    });
    const fetchConfigurations = (search?: string, page: number = 1): void => {
      setSearchQuery(search ?? '');
      getConfiguration({ ...filter, search, page, status: 'active', sortColumn: 'name', sortOrder: 'asc'  })
        .then((res: any) => {
          setLoading(false);
          const formatData = res?.data.data.map((config: any) => ({
            value: useLabelInValue ? config.name : config.id,
            label: config.name,
          })); // formatData
          setMeta(res?.data.meta);
          if (page === 1) {
            setConfigurationOptions(formatData);
          } else {
            setConfigurationOptions((data) => [...data, ...formatData]);
          }
        })
        .catch((error: any) => {
          console.log('error: ', error);
        });
    };

    const fetchMoreConfigurations = (): void => {
      if (meta.current_page !== meta.total_pages && !loading) {
        fetchConfigurations(searchQuery, meta.current_page + 1);
      }
    };

    // Expose the reload method using useImperativeHandle
    useImperativeHandle(
      forwardRef,
      () => ({
        reload: async() => {

          await fetchConfigurations();
        },
        filterOptions: async(filterOptions: (options: options[]) => options[]) => {
          await setConfigurationOptions(filterOptions);
        },
      }),
      []
    );

    return (
      <InputAutoComplete
        loading={loading}
        name={name}
        label={label}
        placeholder={placeholder}
        options={configurationOptions}
        onChange={(value, item) => {
          if (onChange) {
            onChange(value, item);
          }
        }}
        onSelect={(value) => {
          if (onSelect) {
            onSelect(value);
          }
        }}
        isSearchable={true}
        onSearch={fetchConfigurations}
        onClear={() => {
          fetchConfigurations('');
          if (onClear !== undefined) {
            onClear();
          }
        }}
        onPopupScroll={fetchMoreConfigurations}
        {...rest}
      />
    );
  }
);

MasterConfigurations.displayName = 'MasterConfigurations';
export default MasterConfigurations;
