import { FC } from 'react';

import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import TextField from '@material-hu/mui/TextField';
import Typography from '@material-hu/mui/Typography';
import { DesktopDatePicker } from '@material-hu/mui/x-date-pickers/DesktopDatePicker';

import HuSwitcher from '@material-hu/components/design-system/Switcher';

import { POLL_EDIT_DEADLINE_MENU_ITEM_Z_INDEX } from 'src/pages/dashboard/feed/components/PollEditDeadlineMenuItem';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { createDefaultPollDeadline } from 'src/utils/poll';

export type PollDeadlineFormProps = {
  deadlineEnabled: boolean;
  endsAt: Date | null;
  onDeadlineEnabledChange: (enabled: boolean) => void;
  onEndsAtChange: (date: Date | null) => void;
  disabled?: boolean;
};

const PollDeadlineForm: FC<PollDeadlineFormProps> = ({
  deadlineEnabled,
  endsAt,
  onDeadlineEnabledChange,
  onEndsAtChange,
  disabled = false,
}) => {
  const { t } = useTranslation('post');
  const theme = useTheme();

  const handleDateChange = (date: Date | null) => {
    if (date) {
      const newDate = new Date(date);
      if (endsAt) {
        // If there's an existing time, keep it
        newDate.setHours(endsAt.getHours(), endsAt.getMinutes());
      } else {
        // If no existing time, set to current time + 1 day
        const oneDayFromNow = createDefaultPollDeadline();
        newDate.setHours(oneDayFromNow.getHours(), oneDayFromNow.getMinutes());
      }
      onEndsAtChange(newDate);
    } else {
      onEndsAtChange(null);
    }
  };

  const handleTimeChange = (timeValue: string) => {
    if (timeValue && endsAt) {
      const [hours, minutes] = timeValue.split(':').map(Number);
      const currentDate = new Date(endsAt);
      const newDate = new Date(currentDate);
      newDate.setHours(hours, minutes);
      onEndsAtChange(newDate);
    }
  };

  const handleSwitcherChange = (enabled: boolean) => {
    if (!enabled) {
      // When disabling, remove the deadline
      onEndsAtChange(null);
    } else if (!endsAt) {
      // When enabling and no date is set, set default to current time + 1 day
      const oneDayFromNow = createDefaultPollDeadline();
      onEndsAtChange(oneDayFromNow);
    }
    onDeadlineEnabledChange(enabled);
  };

  // Show the switcher and conditional inputs (for both create and edit modes)
  return (
    <Stack
      sx={{
        p: 2,
        backgroundColor: theme => theme.palette.new.background.layout.default,
        borderRadius: theme => theme.shape.borderRadiusL,
      }}
    >
      <Stack
        direction="row"
        alignItems="center"
      >
        <HuSwitcher
          title={t('set_end_time')}
          description={t('set_end_time_description')}
          value={deadlineEnabled}
          onChange={() => handleSwitcherChange(!deadlineEnabled)}
          disabled={disabled}
        />
      </Stack>

      {deadlineEnabled && (
        <Stack sx={{ mt: 2, gap: 2 }}>
          {endsAt && endsAt <= new Date() && (
            <Typography
              variant="globalS"
              color="error"
            >
              {t('poll_deadline_past_error')}
            </Typography>
          )}
          <Stack
            direction="row"
            gap={1}
          >
            <DesktopDatePicker
              value={endsAt}
              onChange={handleDateChange}
              minDate={new Date()}
              disabled={disabled}
              label={t('post:date')}
              slotProps={{
                popper: {
                  sx: {
                    zIndex: POLL_EDIT_DEADLINE_MENU_ITEM_Z_INDEX + 1,
                  },
                },
                textField: {
                  size: 'small',
                  fullWidth: true,
                  inputProps: {
                    placeholder: 'dd/mm/yyyy',
                  },
                },
              }}
            />
            <TextField
              label={t('post:time')}
              type="time"
              value={
                endsAt
                  ? `${String(endsAt.getHours()).padStart(2, '0')}:${String(endsAt.getMinutes()).padStart(2, '0')}`
                  : (() => {
                      const oneDayFromNow = createDefaultPollDeadline();
                      return `${String(oneDayFromNow.getHours()).padStart(2, '0')}:00`;
                    })()
              }
              onChange={e => handleTimeChange(e.target.value)}
              disabled={disabled || !endsAt}
              fullWidth
              size="small"
              InputLabelProps={{ shrink: true }}
              inputProps={{
                step: 300, // 5 minute intervals
              }}
              sx={{
                '& input[type="time"]': {
                  colorScheme: theme.palette.mode,
                },
              }}
            />
          </Stack>
        </Stack>
      )}
    </Stack>
  );
};

export default PollDeadlineForm;
