import { useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import useSelectedCollaboratorsDrawer from '@composed-components/audience/hooks/useSelectedCollaboratorsDrawer';
import { type DefaultItemType } from '@composed-components/ConditionLine/types';
import Alert from '@design-system/Alert';
import Button from '@design-system/Buttons/Button';
import Skeleton from '@design-system/Skeleton';
import Title from '@design-system/Title';
import { Stack } from '@mui/material';

import CriteriaSelector from './components/CriteriaSelector';
import CriteriaSummary from './components/CriteriaSummary';
import { type AudienceFormValues, type AudienceProps } from './types';

const Audience = <
  FieldItemType extends DefaultItemType = DefaultItemType,
  ValueItemType extends DefaultItemType = DefaultItemType,
>({
  title,
  description,
  segmentationDrawerProps,
  individualDrawerProps,
  selectedCollaboratorsDrawerProps,
  getSegmentationDescription,
  getIndividualDescription,
  useCount,
  onBeforeDelete,
  showAllSelectedAlert = true,
  availableCriteriaTypes,
  showCriteriaInfo = true,
  slotProps,
  sx,
}: AudienceProps<FieldItemType, ValueItemType>) => {
  const { t } = useTranslation('material_hu_only');
  const { watch } =
    useFormContext<AudienceFormValues<FieldItemType, ValueItemType>>();

  const formValues = watch() as AudienceFormValues<
    FieldItemType,
    ValueItemType
  >;
  const criterias = formValues.criterias ?? [];
  const hasCriterias = criterias.length > 0;

  const { count, loading: countLoading } = useCount(formValues);

  const displayTitle = title ?? t('audience.audience_title');
  const displayDescription = description ?? t('audience.audience_description');

  const { selectedCollaboratorsDrawer, showSelectedCollaboratorsDrawer } =
    useSelectedCollaboratorsDrawer();

  const handleTotalCollaboratorsClick = () => {
    showSelectedCollaboratorsDrawer({
      ...selectedCollaboratorsDrawerProps,
      totalCount: count,
    });
  };

  return (
    <Stack sx={{ gap: 3, ...sx }}>
      {selectedCollaboratorsDrawer}
      <Stack
        sx={{
          gap: 3,
          flexDirection: 'row',
          alignItems: 'flex-start',
          justifyContent: 'space-between',
        }}
      >
        <Title
          {...slotProps?.title}
          title={displayTitle}
          description={displayDescription}
        />
        {hasCriterias &&
          (countLoading ? (
            <Skeleton
              variant="rounded"
              width={180}
              height={40}
            />
          ) : (
            <Button
              variant="secondary"
              onClick={handleTotalCollaboratorsClick}
            >
              {t('audience.total_collaborators', { count })}
            </Button>
          ))}
      </Stack>
      {slotProps?.alert && <Alert {...slotProps.alert} />}
      {hasCriterias ? (
        <CriteriaSummary
          segmentationDrawerProps={segmentationDrawerProps}
          individualDrawerProps={individualDrawerProps}
          getSegmentationDescription={getSegmentationDescription}
          getIndividualDescription={getIndividualDescription}
          onBeforeDelete={onBeforeDelete}
          showAllSelectedAlert={showAllSelectedAlert}
          availableCriteriaTypes={availableCriteriaTypes}
        />
      ) : (
        <CriteriaSelector
          segmentationDrawerProps={segmentationDrawerProps}
          individualDrawerProps={individualDrawerProps}
          availableCriteriaTypes={availableCriteriaTypes}
          showCriteriaInfo={showCriteriaInfo}
        />
      )}
    </Stack>
  );
};

export default Audience;
