import { useMemo, useState } from 'react';

import { useQueryState } from 'nuqs';

import { type AutocompleteOption } from '@material-hu/components/design-system/Inputs/Autocomplete/types';

import useAgent from '../../hooks/useAgent';

export const useHelpDeskSelector = () => {
  const { agent } = useAgent();
  const [helpDeskMenuOpen, setHelpDeskMenuOpen] = useState(false);

  const [helpDeskId, setHelpDeskId] = useQueryState('hd', {
    defaultValue: '',
  });

  const selectedHelpDesk = useMemo((): AutocompleteOption | null => {
    if (helpDeskId && agent?.helpDesks) {
      const foundHelpDesk = agent.helpDesks.find(hd => hd.id === helpDeskId);
      if (foundHelpDesk) {
        return { label: foundHelpDesk.name, value: foundHelpDesk.id };
      }
    }
    const firstHelpDesk = agent?.helpDesks?.[0];
    if (firstHelpDesk && !helpDeskId) {
      setHelpDeskId(firstHelpDesk.id);
      return { label: firstHelpDesk.name, value: firstHelpDesk.id };
    }
    return firstHelpDesk
      ? { label: firstHelpDesk.name, value: firstHelpDesk.id }
      : null;
  }, [helpDeskId, agent?.helpDesks, setHelpDeskId]);

  const helpDeskOptions = useMemo(
    () =>
      agent?.helpDesks?.map(helpDesk => ({
        label: helpDesk.name,
        value: helpDesk.id,
      })) ?? [],
    [agent],
  );

  const showHelpDeskSelector = agent?.helpDesks && agent.helpDesks.length > 1;

  const handleHelpDeskChange = (newValue: AutocompleteOption | null) => {
    setHelpDeskMenuOpen(false);
    setHelpDeskId((newValue?.value as string) || '');
  };

  return {
    selectedHelpDesk,
    helpDeskOptions,
    helpDeskMenuOpen,
    setHelpDeskMenuOpen,
    showHelpDeskSelector,
    handleHelpDeskChange,
  };
};
