import { dadataApi } from '@/app/api';
import { DadataOrgRequisitesSuggestion, DadataSuggestionsType } from '@/shared';
import { useCallback, useState } from 'react';
import { FieldTextPrimitive } from '../FieldTextPrimitive/FieldTextPrimitive';
import { RequisitesSuggestions } from '../RequisitesSuggestions/RequisitesSuggestions';
import styled from 'styled-components';

const useDebouncedCallback = (callback: Function, delay: number) => {
  const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null);

  return useCallback(
    (...args: any[]) => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }

      const newTimeoutId = setTimeout(() => {
        callback(...args);
      }, delay);

      setTimeoutId(newTimeoutId);
    },
    [callback, delay, timeoutId]
  );
};

const FieldWrapper = styled.div`
  position: relative;
  width: 100%;
`;

const SuggestionsWrapper = styled.div`
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;

  background: var(--background-white-0);
  border: 1px solid var(--graphite-graphite-120);
  border-radius: var(--border-radius-element);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

  max-height: 320px;
  overflow: hidden;
`;

interface Props {
  value: string;
  onChange: (value: string) => void;
  onOrganizationSelect?: (organization: DadataOrgRequisitesSuggestion) => void;
  placeholder?: string;
  disabled?: boolean;
}

export const OrganizationAutocompleteField = ({
  value,
  onChange,
  onOrganizationSelect,
  placeholder = 'Введите название организации, ИНН или ОГРН',
  disabled,
}: Props) => {
  const [suggestions, setSuggestions] = useState<DadataOrgRequisitesSuggestion[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [loading, setLoading] = useState(false);

  const searchOrganizations = useCallback(
    async (query: string) => {
      if (query.length < 3) {
        setSuggestions([]);
        setShowSuggestions(false);
        return;
      }

      setLoading(true);
      try {
        const response = await dadataApi.getOrgRequisites(query);
        setSuggestions(response || []);
        setShowSuggestions(true);
      } catch (error) {
        console.error('Ошибка поиска организаций:', error);
        setSuggestions([]);
        setShowSuggestions(false);
      } finally {
        setLoading(false);
      }
    },
    []
  );

  const debouncedSearch = useDebouncedCallback(searchOrganizations, 300);

  const handleInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
      const newValue = e.target.value;
      onChange(newValue);
      debouncedSearch(newValue);
    },
    [onChange, debouncedSearch]
  );

  const handleOrganizationSelect = useCallback(
    (organization: DadataOrgRequisitesSuggestion) => {
      // Заполняем поле названием организации
      onChange(organization.value || '');

      // Вызываем колбек с полной информацией об организации
      onOrganizationSelect?.(organization);

      setShowSuggestions(false);
      setSuggestions([]);
    },
    [onChange, onOrganizationSelect]
  );

  const getSelectOrgRequisitesSuggestionHandler = useCallback(
    (suggestion: DadataOrgRequisitesSuggestion) => () => handleOrganizationSelect(suggestion),
    [handleOrganizationSelect]
  );

  return (
    <FieldWrapper>
      <FieldTextPrimitive
        value={value}
        onChange={handleInputChange}
        placeholder={placeholder}
        readonly={disabled}
        loading={loading}
        disableAutocomplete
      />

      {showSuggestions && suggestions.length > 0 && (
        <SuggestionsWrapper>
          <RequisitesSuggestions
            suggestionsType={DadataSuggestionsType.ORG_REQUISITES}
            suggestions={suggestions}
            getSelectOrgRequisitesSuggestionHandler={getSelectOrgRequisitesSuggestionHandler}
          />
        </SuggestionsWrapper>
      )}
    </FieldWrapper>
  );
};
