import React, { useEffect, useState } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Checkbox from '@mui/material/Checkbox';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import Divider from '@mui/material/Divider';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import { t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { ShiftCascadePreview, ShiftCascadeRange, ShiftCascadeScope } from '../../types/shift';

interface ShiftCascadeScopeDialogProps {
  open: boolean;
  preview: ShiftCascadePreview;
  onConfirm: (choice: { scope: ShiftCascadeScope; range?: ShiftCascadeRange; reprice?: boolean }) => void;
  onCancel: () => void;
}

const todayIso = () => new Date().toISOString().slice(0, 10);

const ShiftCascadeScopeDialog: React.FC<ShiftCascadeScopeDialogProps> = ({
  open,
  preview,
  onConfirm,
  onCancel,
}) => {
  const { i18n } = useLingui();
  const [scope, setScope] = useState<ShiftCascadeScope>('future_unassigned');
  const [rangeFrom, setRangeFrom] = useState<string>(todayIso());
  const [rangeTo, setRangeTo] = useState<string>('');
  const [reprice, setReprice] = useState<boolean>(false);

  const canReprice = preview.repriceable_sessions_count > 0;

  useEffect(() => {
    if (!open) return;
    setScope(preview.future_unassigned_count > 0 ? 'future_unassigned'
      : preview.future_all_count > 0 ? 'future_all'
      : (preview.past_correctable_count > 0 || preview.repriceable_sessions_count > 0) ? 'range' : 'none');
    setRangeFrom(preview.default_range?.from || todayIso());
    setRangeTo(preview.default_range?.to || '');
    setReprice(false);
  }, [open, preview]);

  const skipped = preview.skipped_manual_count + preview.skipped_protected_count;
  const rangeInvalid = scope === 'range' && (!rangeFrom || !rangeTo || rangeTo < rangeFrom);
  const rangeEnabled = preview.future_all_count > 0 || preview.past_correctable_count > 0 || canReprice;

  const handleConfirm = () => {
    onConfirm({
      scope,
      ...(scope === 'range' ? { range: { from: rangeFrom, to: rangeTo } } : {}),
      ...(scope !== 'none' && canReprice ? { reprice } : {}),
    });
  };

  const unassignedLabel = i18n._(t`Nur zukünftige Schichten ohne zugewiesene Mitarbeiter (${preview.future_unassigned_count} Schichten)`);
  const allLabel = preview.future_assigned_count > 0
    ? i18n._(t`Alle zukünftigen Schichten (${preview.future_all_count} Schichten — ${preview.future_assigned_count} mit zugewiesenen Mitarbeitern)`)
    : i18n._(t`Alle zukünftigen Schichten (${preview.future_all_count} Schichten)`);

  return (
    <Dialog open={open} onClose={onCancel} maxWidth="sm" fullWidth>
      <DialogTitle>{i18n._(t`Änderungen auf bestehende Schichten anwenden?`)}</DialogTitle>
      <DialogContent>
        <RadioGroup value={scope} onChange={(e) => setScope(e.target.value as ShiftCascadeScope)}>
          <FormControlLabel
            value="future_unassigned"
            control={<Radio />}
            disabled={preview.future_unassigned_count === 0}
            label={unassignedLabel}
          />
          <FormControlLabel
            value="future_all"
            control={<Radio />}
            disabled={preview.future_all_count === 0}
            label={allLabel}
          />
          <FormControlLabel
            value="range"
            control={<Radio />}
            disabled={!rangeEnabled}
            label={
              preview.past_correctable_count > 0
                ? i18n._(t`Bestimmter Zeitraum — auch rückwirkend (${preview.past_correctable_count} vergangene Schichten korrigierbar)`)
                : i18n._(t`Bestimmter Zeitraum`)
            }
          />
          {scope === 'range' && (
            <Box sx={{ display: 'flex', gap: 2, pl: 4, py: 1 }}>
              <TextField
                label={i18n._(t`Von`)}
                type="date"
                size="small"
                value={rangeFrom}
                onChange={(e) => setRangeFrom(e.target.value)}
                InputLabelProps={{ shrink: true }}
              />
              <TextField
                label={i18n._(t`Bis`)}
                type="date"
                size="small"
                value={rangeTo}
                onChange={(e) => setRangeTo(e.target.value)}
                InputLabelProps={{ shrink: true }}
                inputProps={{ min: rangeFrom || undefined }}
              />
            </Box>
          )}
          <FormControlLabel
            value="none"
            control={<Radio />}
            label={i18n._(t`Keine bestehenden Schichten ändern (nur Vorlage speichern)`)}
          />
        </RadioGroup>

        {canReprice && scope !== 'none' && (
          <>
            <Divider sx={{ my: 1.5 }} />
            <FormControlLabel
              control={<Checkbox checked={reprice} onChange={(e) => setReprice(e.target.checked)} />}
              label={i18n._(t`Auch erfasste Arbeitssitzungen neu bewerten (Soll-Zeiten anpassen) — ${preview.repriceable_sessions_count} Sitzungen`)}
            />
            {reprice && (
              <Typography variant="caption" color="warning.main" sx={{ display: 'block', pl: 4 }}>
                {i18n._(t`Achtung: Dies ändert bereits erfasste, bezahlte Arbeitszeit rückwirkend und berechnet die Überstunden neu.`)}
              </Typography>
            )}
          </>
        )}

        {skipped > 0 && (
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            {i18n._(t`${preview.skipped_manual_count} manuell angepasste und ${preview.skipped_protected_count} geschützte Schichten werden nicht verändert.`)}
          </Typography>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onCancel}>{i18n._(t`Abbrechen`)}</Button>
        <Button onClick={handleConfirm} variant="contained" color="primary" disabled={rangeInvalid}>
          {i18n._(t`Speichern`)}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default ShiftCascadeScopeDialog;
