import { type FC, useState } from 'react';
import { useFormContext } from 'react-hook-form';

import { IconUsers, IconUsersGroup } from '@material-hu/icons/tabler';

import HuAlert from '@material-hu/components/design-system/Alert';
import HuTitle from '@material-hu/components/design-system/Title';

import { useLokaliseTranslation } from 'src/utils/i18n';

import ContainerLayout from '../../../components/ContainerLayout';
import InfoCard from './InfoCard';
import NavTitleCard from '../../../components/NavTitleCard';
import useAgentGroupHydration from '../../../hooks/useAgentGroupHydration';
import useUserHydration from '../../../hooks/useUserHydration';
import { type AgentGroup, Step } from '../../../types';
import { getSelectedAgentsListText } from '../../../utils';
import { newServiceItemFields } from '../../forms';

import AssignAgentGroupDrawer from './AssignAgentGroupDrawer';
import SpecificAgentsDrawer from './SpecificAgentsDrawer';

const agentsFormName = newServiceItemFields.assignment.agents();
const agentGroupFormName = newServiceItemFields.assignment.agentGroup();

type Props = {
  showError: boolean;
};

const Assignment: FC<Props> = ({ showError }) => {
  const { t } = useLokaliseTranslation('service_management');

  const [agentGroupsDrawerOpen, setAgentGroupsDrawerOpen] = useState(false);
  const [userSelectionDrawerOpen, setUserSelectionDrawerOpen] = useState(false);
  const [previousSelectedAgents, setPreviousSelectedAgents] = useState([]);
  const [previousSelectedAgentGroup, setPreviousSelectedAgentGroup] = useState<
    AgentGroup | AgentGroup['id'] | null
  >(null);

  const { watch, setValue } = useFormContext();

  const selectedAgents = watch(agentsFormName);
  const selectedAgentGroup = watch(agentGroupFormName);

  const { hydratedUsers, isLoading: isLoadingUsersHydration } =
    useUserHydration({
      users: selectedAgents,
      onSuccess: users => {
        setValue(agentsFormName, users);
      },
    });

  const { agentGroupHydrated, isLoading: isLoadingAgentGroupHydration } =
    useAgentGroupHydration({
      agentGroup: selectedAgentGroup,
      onSuccess: agentGroup => {
        setValue(agentGroupFormName, agentGroup);
      },
    });

  const handleOpenAgentGroupsDrawer = () => {
    setPreviousSelectedAgentGroup(selectedAgentGroup);
    setAgentGroupsDrawerOpen(true);
  };

  const handleCloseAgentGroupsDrawer = () => {
    setAgentGroupsDrawerOpen(false);
    setValue(agentGroupFormName, previousSelectedAgentGroup);
  };

  const handleConfirmAgentGroupSelection = () => {
    setAgentGroupsDrawerOpen(false);
  };

  const handleClose = () => {
    setUserSelectionDrawerOpen(false);
    setValue(agentsFormName, previousSelectedAgents);
  };

  const handleSelect = () => {
    setUserSelectionDrawerOpen(false);
    setPreviousSelectedAgents([]);
  };

  const handleOpenUserSelectionDrawer = () => {
    setPreviousSelectedAgents(selectedAgents);
    setUserSelectionDrawerOpen(true);
  };

  const handleDeleteSpecificAgents = () => setValue(agentsFormName, []);
  const handleDeleteAgentGroup = () => setValue(agentGroupFormName, null);

  const noSelection = selectedAgents.length === 0 && !selectedAgentGroup;
  const hasSelectedSpecificAgents = selectedAgents.length > 0;
  const hasSelectedAgentGroup = !!selectedAgentGroup;

  return (
    <ContainerLayout sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <SpecificAgentsDrawer
        open={userSelectionDrawerOpen}
        onClose={handleClose}
        onCancel={handleClose}
        onSelect={handleSelect}
        loading={isLoadingUsersHydration}
      />
      <AssignAgentGroupDrawer
        open={agentGroupsDrawerOpen}
        onClose={handleCloseAgentGroupsDrawer}
        onApply={handleConfirmAgentGroupSelection}
        onCancel={handleCloseAgentGroupsDrawer}
      />
      <HuTitle
        variant="L"
        title={t(`${Step.ASSIGNMENT}`)}
        description={t('assignment_description')}
      />
      {showError && (
        <HuAlert
          severity="error"
          title={t('no_assignment_selected_error_title')}
          description={t('no_assignment_selected_error_description')}
        />
      )}
      {noSelection && (
        <>
          <NavTitleCard
            title={t('specific_agents')}
            description={t('specific_collaborators_assignment_helper_text')}
            Icon={IconUsers}
            avatarColor="default"
            onClick={handleOpenUserSelectionDrawer}
          />
          <NavTitleCard
            title={t('agent_groups')}
            description={t('agent_groups_description')}
            Icon={IconUsersGroup}
            avatarColor="default"
            onClick={handleOpenAgentGroupsDrawer}
          />
        </>
      )}
      {hasSelectedSpecificAgents && (
        <InfoCard
          title={t('specific_agents')}
          description={getSelectedAgentsListText(hydratedUsers, t)}
          loadingDescription={isLoadingUsersHydration}
          Icon={IconUsers}
          avatarColor="default"
          onEdit={handleOpenUserSelectionDrawer}
          onDelete={handleDeleteSpecificAgents}
        />
      )}
      {hasSelectedAgentGroup && (
        <InfoCard
          title={t('agent_groups')}
          description={agentGroupHydrated?.name || ''}
          loadingDescription={isLoadingAgentGroupHydration}
          Icon={IconUsersGroup}
          avatarColor="default"
          onEdit={handleOpenAgentGroupsDrawer}
          onDelete={handleDeleteAgentGroup}
        />
      )}
    </ContainerLayout>
  );
};

export default Assignment;
