import { useState } from 'react';
import { useController, useFormContext } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

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

import HuSelectionCard from '@material-hu/components/composed-components/SelectionCard';
import Button from '@material-hu/components/design-system/Buttons/Button';
import Search from '@material-hu/components/design-system/Inputs/Search';
import HuSkeleton from '@material-hu/components/design-system/Skeleton';

import { useDebounce } from 'src/hooks/useDebounce';
import { type ShiftRotation } from 'src/types/shifts';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { displayHoursAndMinutes } from 'src/utils/timeTracking';

import { useGetShiftRotations } from '../../../hooks/useGetShiftRotations';
import { shiftsRoutes } from '../../../routes';
import { type AssignTemplateFormData } from '../../../hooks/useAssignTemplateDrawer';

const TemplateSection = () => {
  const { t } = useLokaliseTranslation(['shifts', 'general']);
  const { palette } = useTheme();
  const navigate = useNavigate();
  const [search, setSearch] = useState('');
  const { debouncedValue: debouncedSearch } = useDebounce(search, 300);

  const { registers, isLoading } = useGetShiftRotations({
    search: debouncedSearch,
  });

  const { control, setValue } = useFormContext<AssignTemplateFormData>();
  const { field } = useController({ control, name: 'templateId' });

  const handleSelect = (rotation: ShiftRotation) => {
    field.onChange(rotation.id);
    setValue('templateName', rotation.name);
  };

  return (
    <Stack sx={{ gap: 1.5 }}>
      <Search
        value={search}
        placeholder={t('general:search')}
        onChange={setSearch}
      />
      <Stack
        sx={{
          gap: 1,
          maxHeight: 264,
          overflowY: 'auto',
          '& > *': { flexShrink: 0 },
        }}
      >
        {isLoading && (
          <>
            <HuSkeleton height={72} />
            <HuSkeleton height={72} />
            <HuSkeleton height={72} />
          </>
        )}
        {!isLoading && registers.length === 0 && (
          <Typography
            variant="globalS"
            sx={{ color: palette.new.text.neutral.lighter }}
          >
            {t('templates.empty_templates')}
          </Typography>
        )}
        {registers.map((rotation: ShiftRotation) => {
          const isSelected = field.value === rotation.id;
          return (
            <HuSelectionCard
              key={rotation.id}
              checked={isSelected}
              onClick={() => handleSelect(rotation)}
              fullWidth
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: 1,
                }}
              >
                <Stack sx={{ gap: 0 }}>
                  <Typography
                    variant="globalXS"
                    sx={{ color: palette.new.text.neutral.lighter }}
                  >
                    {[
                      rotation.workDaysCount > 0 &&
                        t('templates.shifts_count', {
                          count: rotation.workDaysCount,
                        }),
                      rotation.restDaysCount > 0 &&
                        t('templates.rest_days_count', {
                          count: rotation.restDaysCount,
                        }),
                    ]
                      .filter(Boolean)
                      .join(', ')}
                  </Typography>
                  <Typography
                    variant="globalS"
                    sx={{ fontWeight: 'fontWeightSemiBold' }}
                  >
                    {rotation.name}
                  </Typography>
                  {rotation.description && (
                    <Typography
                      variant="globalXS"
                      sx={{ color: palette.new.text.neutral.lighter }}
                    >
                      {rotation.description}
                    </Typography>
                  )}
                </Stack>
                <Typography
                  variant="globalS"
                  sx={{
                    whiteSpace: 'nowrap',
                    color: palette.new.text.neutral.lighter,
                  }}
                >
                  {t('templates.total_hours_count', {
                    hours: displayHoursAndMinutes(rotation.totalHours),
                  })}
                </Typography>
              </Stack>
            </HuSelectionCard>
          );
        })}
      </Stack>
      <Button
        variant="secondary"
        startIcon={<IconPlus size={16} />}
        fullWidth
        onClick={() => navigate(shiftsRoutes.createTemplate())}
      >
        {t('templates.create')}
      </Button>
    </Stack>
  );
};

export default TemplateSection;
