import { useState, useEffect } from 'react';
import axios from 'axios';
import { useSelector } from 'react-redux';

import { useGetSpecialistsQuery, useGetSpecialistQuery } from '../api/apiSpecialist';
import { useGetKodopersQuery } from '../api/apiKodoper';
import { useGetFilialsQuery } from '../api/apiFilial';
import { useGetDepartmentsQuery } from '../api/apiDepartment';
import { selectRegions } from '../store/slice/regionSlice';

export function useSpecialist(id) {
  const { data: specialist, isLoading, error } = useGetSpecialistQuery(id);
  const [kodoperDetails, setKodoperDetails] = useState([]);
  const filialsQuery = useGetFilialsQuery();
  const filials = filialsQuery.data ?? [];

  const departmentsQuery = useGetDepartmentsQuery();
  const departments = departmentsQuery.data ?? [];
  const regions                = useSelector(selectRegions);

  useEffect(() => {
    if (!specialist?.kodoper?.length) {
      setKodoperDetails([]);
      return;
    }
    let canceled = false;

    Promise.all(
      specialist.kodoper.map(code =>
        axios.get(`https://api.sovamed.ru/pricelist/list?search=${code}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
        .then(res => {
          return (res.data.data || []).find(item => String(item.kodoper) === String(code)) || null;
        })
      )
    ).then(results => {
      if (!canceled) {
        setKodoperDetails(results.filter(Boolean));
      }
    }).catch(() => {
      if (!canceled) {
        setKodoperDetails([]);
      }
    });
    return () => { canceled = true };
  }, [specialist]);

  return {
    isLoading,
    error,
    specialist: specialist ?? null,
    filials,
    departments,
    regions,
    kodoperDetails,
  };
}