import { useMemo, useState } from 'react';
import { useController, useFormContext } from 'react-hook-form';
import { useQuery } from 'react-query';

import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import UserAvatar from '@material-hu/components/composed-components/UserAvatar';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete/form';
import FormDatePicker from '@material-hu/components/design-system/Inputs/DatePicker/form';
import FormCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox/form';
import { Drawer } from '@material-hu/components/layers/Drawers';

import { profileKeys } from 'src/pages/dashboard/profile/queries';
import { getPublicUsers } from 'src/services/users';
import { type User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import { type AssignTemplateFormData } from '../../../hooks/useAssignTemplateDrawer';
import TemplateSection from './TemplateSection';

type UserOption = {
  label: string;
  value: number;
  userInfo: User;
};

type Props = {
  onSubmit: () => void;
  onCancel: () => void;
  isSubmitting: boolean;
  isSubmitEnabled: boolean;
};

const GREY_CARD_SX = {
  border: 'unset',
  overflow: 'visible',
} as const;

const AssignTemplateDrawerContent = ({
  onSubmit,
  onCancel,
  isSubmitting,
  isSubmitEnabled,
}: Props) => {
  const { t } = useLokaliseTranslation(['shifts', 'general']);
  const { palette } = useTheme();
  const greyBg = palette.new.background.elements.grey;
  const [search, setSearch] = useState('');

  const { data: users, isLoading: isLoadingUsers } = useQuery({
    queryKey: profileKeys.userList(search),
    queryFn: () => getPublicUsers({ page: 1, limit: 30, search }),
    select: data => data.data.items,
    staleTime: 1000 * 60 * 2,
  });

  const collaboratorsOptions = useMemo<UserOption[]>(() => {
    const userList = users || [];
    return userList.reduce(
      (acc: UserOption[], currentUser: User) =>
        acc.find(u => u.value === currentUser.id)
          ? acc
          : [
              ...acc,
              {
                label: getFullName(currentUser),
                value: currentUser.id,
                userInfo: currentUser,
              },
            ],
      [],
    );
  }, [users]);

  const { control } = useFormContext<AssignTemplateFormData>();
  const { field: repeatField } = useController({
    control,
    name: 'repeatTemplate',
  });
  const { field: holidaysField } = useController({
    control,
    name: 'includeHolidays',
  });

  return (
    <>
      <Drawer.Header
        title={t('templates.assign')}
        onClose={onCancel}
      />
      <Drawer.Body>
        <Stack sx={{ gap: 2 }}>
          {/* Colaboradores */}
          <CardContainer
            fullWidth
            sx={{ ...GREY_CARD_SX, backgroundColor: greyBg }}
          >
            <Stack sx={{ gap: 1 }}>
              <FormAutocomplete
                name="collaborators"
                options={collaboratorsOptions}
                autocompleteProps={{
                  multiple: true,
                  placeholder: t('general:search'),
                  label: t('general:collaborators'),
                  noOptionsMessage: {
                    title: t('general:no_collaborators_found'),
                  },
                  limitTags: 2,
                  isOptionEqualToValue: (option, value) =>
                    option.value === value.value,
                  onInputChange: (_, value) => setSearch(value),
                  renderOption: (props, option) => (
                    <li {...props}>
                      <UserAvatar
                        user={option.userInfo}
                        sx={{ width: '100%' }}
                        profileProps={{ showEmployeeInternalId: true }}
                      />
                    </li>
                  ),
                  loading: isLoadingUsers,
                }}
              />
            </Stack>
          </CardContainer>

          {/* Fecha de inicio */}
          <CardContainer
            fullWidth
            sx={{ ...GREY_CARD_SX, backgroundColor: greyBg }}
          >
            <FormDatePicker
              name="startDate"
              inputProps={{
                label: t('general:from_date'),
              }}
            />
          </CardContainer>

          {/* Plantilla */}
          <CardContainer
            fullWidth
            sx={{ ...GREY_CARD_SX, backgroundColor: greyBg }}
          >
            <Stack sx={{ gap: 1 }}>
              <Typography
                variant="globalS"
                sx={{ fontWeight: 'fontWeightSemiBold' }}
              >
                {t('templates.template')}
              </Typography>
              <TemplateSection />
            </Stack>
          </CardContainer>

          {/* Recurrencia */}
          <CardContainer
            fullWidth
            sx={{ ...GREY_CARD_SX, backgroundColor: greyBg }}
          >
            <Stack sx={{ gap: 1 }}>
              <Typography
                variant="globalS"
                sx={{ fontWeight: 'fontWeightSemiBold' }}
              >
                {t('templates.recurrence')}
              </Typography>
              <Stack sx={{ gap: 0.5 }}>
                <FormCheckbox
                  name="repeatTemplate"
                  checkBoxProps={{
                    label: t('templates.repeat_template'),
                    checked: repeatField.value,
                    onChange: (_, v) => repeatField.onChange(v),
                    disabled: true,
                  }}
                />
                <Typography
                  variant="globalXS"
                  sx={{ color: palette.new.text.neutral.lighter, pl: 3.5 }}
                >
                  {t('templates.repeat_template_description')}
                </Typography>
              </Stack>
            </Stack>
          </CardContainer>

          {/* Días festivos */}
          <CardContainer
            fullWidth
            sx={{ ...GREY_CARD_SX, backgroundColor: greyBg }}
          >
            <Stack sx={{ gap: 1 }}>
              <Typography
                variant="globalS"
                sx={{ fontWeight: 'fontWeightSemiBold' }}
              >
                {t('templates.holidays')}
              </Typography>
              <Stack sx={{ gap: 0.5 }}>
                <FormCheckbox
                  name="includeHolidays"
                  checkBoxProps={{
                    label: t('templates.include_holidays'),
                    checked: holidaysField.value,
                    onChange: (_, v) => holidaysField.onChange(v),
                  }}
                />
                <Typography
                  variant="globalXS"
                  sx={{ color: palette.new.text.neutral.lighter, pl: 3.5 }}
                >
                  {t('templates.include_holidays_description')}
                </Typography>
              </Stack>
            </Stack>
          </CardContainer>
        </Stack>
      </Drawer.Body>
      <Drawer.Actions
        primaryButtonProps={{
          children: t('templates.assign'),
          fullWidth: true,
          loading: isSubmitting,
          disabled: !isSubmitEnabled,
          onClick: onSubmit,
        }}
      />
    </>
  );
};

export default AssignTemplateDrawerContent;
