import { Helmet } from 'react-helmet-async';
import {
  FormProvider,
  useForm,
  useFormContext,
  useWatch,
} from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import { IconArrowLeft } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import { useDialogLayer } from '@material-hu/components/layers/Dialogs';

import useUnsavedWarning from 'src/hooks/useUnsavedWarning';

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

import RotationDaysSection from './RotationDaysSection';
import RotationSummary from './RotationSummary';
import { parseRotationPayload } from './parseRotationPayload';
import {
  type ShiftRotationFormData,
  shiftRotationFormFields,
} from '../../../form';
import { useCreateShiftRotationMutation } from '../../../hooks/useCreateShiftRotationMutation';
import { useUpdateShiftRotationMutation } from '../../../hooks/useUpdateShiftRotationMutation';
import { shiftsRoutes } from '../../../routes';

const CONTENT_MAX_WIDTH = 1040;
const ROTATION_NAME_MAX_LENGTH = 60;
const NOTES_MAX_LENGTH = 250;

type SaveButtonProps = {
  onSubmit: (data: ShiftRotationFormData) => void;
  isLoading: boolean;
};

const SaveButton = ({ onSubmit, isLoading }: SaveButtonProps) => {
  const { t } = useLokaliseTranslation('shifts');
  const { handleSubmit } = useFormContext<ShiftRotationFormData>();
  const [name, days] = useWatch<ShiftRotationFormData, ['name', 'days']>({
    name: ['name', 'days'],
  });

  const canSubmit = !!name?.trim() && (days?.length ?? 0) > 0;

  return (
    <Button
      variant="primary"
      color="primary"
      disabled={!canSubmit || isLoading}
      loading={isLoading}
      onClick={handleSubmit(onSubmit)}
    >
      {t('templates.save')}
    </Button>
  );
};

type Props = {
  defaultValues: ShiftRotationFormData;
  rotationId?: string;
};

const CreateShiftRotationContent = ({ defaultValues, rotationId }: Props) => {
  const { t } = useLokaliseTranslation('shifts');
  const navigate = useNavigate();
  const isEdit = !!rotationId;

  const { openDialog, closeDialog } = useDialogLayer();

  const form = useForm<ShiftRotationFormData>({
    defaultValues,
    mode: 'onSubmit',
  });

  const { mutate: createRotation, isLoading: isCreating } =
    useCreateShiftRotationMutation();
  const { mutate: updateRotation, isLoading: isUpdating } =
    useUpdateShiftRotationMutation();

  const { modal: unsavedModal, disableUnsavedWarning } = useUnsavedWarning(
    undefined,
    !form.formState.isDirty,
  );

  const goBackToTemplates = () => {
    disableUnsavedWarning();
    // Defer navigate to the next tick so React commits the setDisabled(true)
    // state update inside useUnsavedWarning before useBlocker evaluates the
    // navigation — otherwise the blocker still sees the stale "dirty" state
    // and pops the modal.
    setTimeout(() => navigate(shiftsRoutes.templates()), 0);
  };

  const handleSubmit = (data: ShiftRotationFormData) => {
    const payload = parseRotationPayload(data);

    if (rotationId) {
      openDialog({
        title: t('templates.modal.edit_title'),
        textBody: t('templates.modal.edit_description'),
        onClose: () => closeDialog(),
        primaryButtonProps: {
          children: t('templates.save'),
          onClick: () => {
            closeDialog();
            updateRotation(
              { id: rotationId, data: payload },
              { onSuccess: goBackToTemplates },
            );
          },
        },
        secondaryButtonProps: {
          children: t('general:cancel'),
          onClick: () => closeDialog(),
        },
        dialogProps: { fullWidth: true, maxWidth: 'sm' },
      });
      return;
    }

    createRotation(payload, { onSuccess: goBackToTemplates });
  };

  const title = isEdit
    ? t('templates.edit_title')
    : t('templates.create_title');
  const isSaving = (isEdit && isUpdating) || (!isEdit && isCreating);

  return (
    <FormProvider {...form}>
      <Helmet>
        <title>{formatTitle(title)}</title>
      </Helmet>
      <Stack
        sx={{
          height: '100%',
          overflowY: 'auto',
          backgroundColor: ({ palette }) =>
            palette.new?.background?.layout?.default,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: ({ palette }) =>
              palette.new?.background?.layout?.tertiary,
            px: 2,
            py: 1.5,
            gap: 1,
            position: 'sticky',
            top: 0,
            left: 0,
            zIndex: 200,
          }}
        >
          <IconButton
            aria-label={t('general:back')}
            sx={{ p: 0 }}
            onClick={() => navigate(shiftsRoutes.templates())}
          >
            <IconArrowLeft />
          </IconButton>
          <Typography
            variant="globalL"
            sx={{ flex: 1, fontWeight: 'fontWeightSemiBold' }}
          >
            {title}
          </Typography>
        </Stack>

        <Stack
          sx={{
            alignItems: 'center',
            flexGrow: 1,
            px: 3,
            pt: 3,
            pb: 12,
          }}
        >
          <Stack
            sx={{
              width: '100%',
              maxWidth: CONTENT_MAX_WIDTH,
              flexDirection: 'row',
              gap: 3,
              alignItems: 'flex-start',
            }}
          >
            <Stack sx={{ flex: 2, gap: 2, minWidth: 0 }}>
              <CardContainer fullWidth>
                <FormInputClassic
                  name={shiftRotationFormFields.name}
                  inputProps={{
                    label: t('templates.form.name'),
                    placeholder: t('templates.form.name_placeholder'),
                    maxLength: ROTATION_NAME_MAX_LENGTH,
                    hasCounter: true,
                  }}
                />
              </CardContainer>

              <CardContainer fullWidth>
                <FormInputClassic
                  name={shiftRotationFormFields.description}
                  inputProps={{
                    label: t('general:description'),
                    placeholder: t('templates.form.description_placeholder'),
                    multiline: true,
                    minRows: 3,
                    maxRows: 6,
                    maxLength: NOTES_MAX_LENGTH,
                    hasCounter: true,
                  }}
                />
              </CardContainer>

              <RotationDaysSection />
            </Stack>

            <Stack
              sx={{
                flex: 1,
                minWidth: 0,
                position: 'sticky',
                top: '64px',
                alignSelf: 'flex-start',
              }}
            >
              <RotationSummary />
            </Stack>
          </Stack>
        </Stack>

        <Stack
          sx={{
            alignItems: 'center',
            backgroundColor: ({ palette }) =>
              palette.new?.background?.layout?.tertiary,
            borderTop: ({ palette }) =>
              `1px solid ${palette.new?.border?.neutral?.default}`,
            px: 3,
            py: 1.5,
            position: 'sticky',
            bottom: 0,
            left: 0,
            zIndex: 200,
          }}
        >
          <Stack
            sx={{
              width: '100%',
              maxWidth: CONTENT_MAX_WIDTH,
              flexDirection: 'row',
              justifyContent: 'flex-end',
              alignItems: 'center',
            }}
          >
            <SaveButton
              onSubmit={handleSubmit}
              isLoading={isSaving}
            />
          </Stack>
        </Stack>
      </Stack>
      {unsavedModal}
    </FormProvider>
  );
};

export default CreateShiftRotationContent;
