import React, { useEffect, useRef, useState } from 'react';
import { Select } from 'antd';
import useDebounce from '@/hooks/useDebounce';
import { getProjectOptions } from '../service';

export interface ProjectOption {
  id: number;
  name: string;
}

interface ProjectSelectProps {
  /* Projects are listed for this city only, the same way launches are. */
  cityId?: number;
  value?: number;
  /* Name for the saved project id, which may not be in the first page of results. */
  valueLabel?: string;
  disabled?: boolean;
  onChange: (project?: ProjectOption) => void;
}

const PAGE_SIZE = 20;

/*
  Single-select project picker, shown right after the launch dropdown. The
  chosen project is stored on the rotation's launch mapping and every lead that
  comes in through that rotation is saved against it. Projects load 20 at a
  time by scroll with server-side search, same pattern as LaunchMultiSelect.
 */
const ProjectSelect: React.FC<ProjectSelectProps> = ({ cityId, value, valueLabel, disabled, onChange }) => {
  const [projects, setProjects] = useState<ProjectOption[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const loadMoreLock = useRef(false);

  const debouncedSearch = useDebounce(searchQuery, 400);

  const fetchProjects = (search: string, nextPage: number): void => {
    if (!cityId) return;
    setLoading(true);
    getProjectOptions({ cityId, search, page: nextPage, pageSize: PAGE_SIZE })
      .then((list) => {
        setPage(nextPage);
        setHasMore(list.length === PAGE_SIZE);
        setProjects((prev) => (nextPage === 1 ? list : [...prev, ...list]));
      })
      .finally(() => {
        setLoading(false);
        loadMoreLock.current = false;
      });
  };

  // One effect for both cityId and the search text, so a city change doesn't double-fire the page-1 request.
  useEffect(() => {
    if (!cityId) {
      setProjects([]);
      return;
    }
    fetchProjects(debouncedSearch, 1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [cityId, debouncedSearch]);

  const handlePopupScroll = (e: React.UIEvent<HTMLDivElement>): void => {
    const { currentTarget } = e;
    const reachedBottom = currentTarget.scrollTop + currentTarget.clientHeight >= currentTarget.scrollHeight - 5;
    if (reachedBottom && hasMore && !loading && !loadMoreLock.current) {
      loadMoreLock.current = true;
      fetchProjects(searchQuery, page + 1);
    }
  };

  const options = projects.map((p) => ({ value: p.id, label: p.name }));
  if (value && !projects.some((p) => p.id === value)) {
    options.unshift({ value, label: valueLabel || `#${value}` });
  }

  return (
    <Select
      className="block mt-1"
      style={{ width: '100%' }}
      showSearch
      allowClear
      loading={loading}
      disabled={disabled || !cityId}
      placeholder={cityId ? 'Select project' : 'Select a city first'}
      value={value}
      filterOption={false}
      onSearch={setSearchQuery}
      onPopupScroll={handlePopupScroll}
      onChange={(selected) => {
        if (selected === undefined || selected === null) return onChange(undefined);
        const picked = projects.find((p) => p.id === selected);
        onChange({ id: selected as number, name: picked?.name || valueLabel || `#${selected}` });
      }}
      options={options}
    />
  );
};

export default ProjectSelect;
