import React, { useEffect, useState } from 'react';
import { notification } from 'antd';
import InputSelect from '@/components/form/InputSelect';
import { getLaunchProjects } from '@/app/launches/service';

interface Option { value: number, label: string }

interface Props {
  launchId?: number | string
  // Projects already tied to the lead - always offered so a saved value renders its name.
  associatedProjects?: { project_id: number, project_name: string }[]
  // Saved project (e.g. a booking's project_id) that may sit outside the first page of results.
  extraOptions?: Option[]
  name?: string
  label?: string
}

// Same launch-scoped project list (and paging/search) that ActionForm uses for the booking's Project field.
const LaunchProjectSelect: React.FC<Props> = ({ launchId, associatedProjects, extraOptions, name = 'project_id', label = 'Project' }) => {
  const [options, setOptions] = useState<Option[]>([]);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [searchInput, setSearchInput] = useState('');
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);

  const load = (nextPage = 1, term = '', append = false) => {
    if (!launchId) return;
    setLoading(true);
    getLaunchProjects(launchId, { page: nextPage, pageSize: 10, search: term })
      .then((res: any) => {
        const fetched: Option[] = (res.data || []).map((i: any) => ({ value: i.project_id, label: i.project_name }));
        setOptions((prev) => {
          const seeded: Option[] = [
            ...(associatedProjects || []).map((p) => ({ value: p.project_id, label: p.project_name })),
            ...(extraOptions || []),
          ];
          const merged = append ? [...prev, ...fetched] : [...seeded, ...fetched];
          return merged.filter((o, idx, arr) => arr.findIndex((x) => x.value === o.value) === idx);
        });
        setPage(nextPage);
        setHasMore((res.data || []).length === 10);
      })
      .catch((error: any) => {
        notification.error({ message: 'Error', description: error?.response?.data?.message || 'Failed to fetch projects' });
      })
      .finally(() => setLoading(false));
  };

  useEffect(() => { load(); }, [launchId]);

  return (
    <InputSelect
      name={name}
      label={label}
      options={options}
      loading={loading}
      placeholder="Select project"
      showSearch
      filterOption={false}
      onSearch={setSearchInput}
      searchValue={searchInput}
      onInputKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') {
          e.preventDefault();
          setSearch(searchInput);
          load(1, searchInput, false);
        }
      }}
      onPopupScroll={(event: React.UIEvent<HTMLDivElement>) => {
        const t = event.currentTarget;
        if (t.scrollTop + t.clientHeight >= t.scrollHeight - 10 && hasMore && !loading) {
          load(page + 1, search, true);
        }
      }}
    />
  );
};

export default LaunchProjectSelect;
