import React, { useState } from 'react';
import InputAutoComplete from '@/components/form/InputAutoComplete';
import { getAllRoles } from '@/app/role/service';
import { notification } from 'antd';
import type { ListMeta } from '@/interfaces/common';
import { useRoles } from '@/hooks/useRoles';

interface RoleDropdownProps {
    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?: {
        exclude_id?: number | string
        city_id?: number | string | null
    }
    name?: string
    label?: string
    placeholder?: string
    disabled?: boolean
    onClear?: () => void
    [key: string]: unknown,
    exclude?: number[],
    keyProp?: string;
}

const MasterRoles: React.FC<RoleDropdownProps> = ({
  filter = {},
  name = 'role_id',
  onClear,
  label,
  disabled,
  placeholder = 'Role',
  onSelect,
  onChange,
  exclude = [],
  keyProp = '',
  ...rest
}) => {
  const { getRoleByName } = useRoles();
  const [roleOptions, setRoleOptions] = useState<Array<{ value: number | string; label: string }>
    >([]);

  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [meta, setMeta] = useState<ListMeta>({
    total: 0,
    count: 0,
    per_page: 0,
    current_page: 1,
    total_pages: 1,
    // sortColumn: 'name',
    // sortOrder: 'asc'
  });

  const fetchRoles = (search?: string, page: number = 1): void => {
    if (loading) {
      return;
    }
    getAllRoles({ ...filter, search, page, sortColumn: 'sort_order', sortOrder: 'asc' })
      .then((res) => {
        setLoading(false);
        setSearchQuery(search ?? '');
        const formatData = res?.data?.data?.filter((item: { id: number; }) => !exclude.includes(item.id)).map((role: { id: number; label: string; }) => ({
          value: role?.id,
          label: role?.label,
        })); // formatData
        let filteredRoles = formatData;
        if (keyProp === 'lead-transfer') {
          // pre_sales, team_lead, field_sales — resolved dynamically from API roles
          const allowedRoleIds = [
            getRoleByName('pre_sales')?.id,
            getRoleByName('team_lead')?.id,
            getRoleByName('field_sales')?.id,
          ].filter((id): id is number => id !== undefined);
          filteredRoles = formatData?.filter((role: { value: number }) => allowedRoleIds.includes(role.value as number));
        }

        setMeta(res?.data?.meta);
        if (page === 1) {
          setRoleOptions(filteredRoles);
        } else {
          setRoleOptions((data) => [...data, ...filteredRoles]);
        }
      })
      .catch((error) => {
        notification.error({
          message: error?.message,
          description: error?.response?.data?.message,
        });
      });
  };

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

  return (
    <InputAutoComplete
      loading={loading}
      name={name}
      label={label}
      placeholder={placeholder}
      options={roleOptions}
      disabled={disabled}
      onSelect={(value) => {
        if (onSelect) {
          onSelect(value);
        }
        // form.setFieldsValue({ role_id: value });
      }}
      onChange={(value, item) => {
        if (onChange) {
          onChange(value, item);
        }
      }}
      isSearchable={true}
      // filterOption={true}
      onSearch={fetchRoles}
      onClear={() => {
        fetchRoles('');
        if (onClear) {
          onClear();
        }
      }}
      onPopupScroll={fetchMoreRoles}
      {...rest}
    />
  );
};

export default MasterRoles;
