import { useState, useEffect, useRef } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Select,
  MenuItem,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  Switch,
  Chip,
  Paper,
  Alert,
  CircularProgress,
  Autocomplete,
} from '@mui/material';
import { useQuery, useMutation } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { useNotification } from '../contexts/NotificationContext';
import { scheduledMessagesApi } from '../services/scheduledMessages';
import type { MessageType, TriggerMode, WindowMode } from '../types/scheduledMessages.types';

const MESSAGE_TYPE_LABELS: Record<MessageType, string> = {
  event_summary: 'Terminübersicht',
  birthday_list: 'Geburtstagsliste',
  dienstjubilaeen: 'Dienstjubiläen',
  fahrzeug_status: 'Fahrzeugstatus',
  fahrzeug_event: 'Fahrzeug außer Dienst',
  bestellungen: 'Offene Bestellungen',
};

const MESSAGE_TYPE_OPTIONS: MessageType[] = [
  'event_summary',
  'birthday_list',
  'dienstjubilaeen',
  'fahrzeug_status',
  'fahrzeug_event',
  'bestellungen',
];

const WEEKDAY_OPTIONS = [
  { value: 0, label: 'Sonntag' },
  { value: 1, label: 'Montag' },
  { value: 2, label: 'Dienstag' },
  { value: 3, label: 'Mittwoch' },
  { value: 4, label: 'Donnerstag' },
  { value: 5, label: 'Freitag' },
  { value: 6, label: 'Samstag' },
];

const PLACEHOLDER_MAP: Record<MessageType, string[]> = {
  event_summary: ['{{items}}', '{{count}}', '{{date_range}}'],
  birthday_list: ['{{items}}', '{{count}}'],
  dienstjubilaeen: ['{{items}}', '{{count}}'],
  fahrzeug_status: ['{{items}}', '{{count}}'],
  fahrzeug_event: ['{{vehicle}}', '{{event}}', '{{date}}'],
  bestellungen: ['{{items}}', '{{count}}'],
};

interface GeplanteMachrichtenFormProps {
  ruleId?: string;
}

export default function GeplanteMachrichtenForm({ ruleId }: GeplanteMachrichtenFormProps) {
  const navigate = useNavigate();
  const { showSuccess, showError } = useNotification();

  const [name, setName] = useState('');
  const [messageType, setMessageType] = useState<MessageType>('event_summary');
  const [triggerMode, setTriggerMode] = useState<TriggerMode>('day_of_week');
  const [dayOfWeek, setDayOfWeek] = useState<number>(1);
  const [sendTime, setSendTime] = useState('08:00');
  const [daysBeforeMonthStart, setDaysBeforeMonthStart] = useState<number>(3);
  const [windowMode, setWindowMode] = useState<WindowMode>('rolling');
  const [windowDays, setWindowDays] = useState<number>(7);
  const [targetRoomToken, setTargetRoomToken] = useState('');
  const [template, setTemplate] = useState('');
  const [minDaysOverdue, setMinDaysOverdue] = useState<number>(14);
  const [subscribable, setSubscribable] = useState(false);
  const [allowedGroups, setAllowedGroups] = useState<string[]>([]);
  const [active, setActive] = useState(true);

  const templateRef = useRef<HTMLDivElement>(null);

  const { data: existingRule, isLoading: ruleLoading } = useQuery({
    queryKey: ['scheduled-messages', ruleId],
    queryFn: () => scheduledMessagesApi.getById(ruleId!),
    enabled: !!ruleId,
  });

  const { data: roomsData, isLoading: roomsLoading } = useQuery({
    queryKey: ['scheduled-messages-rooms'],
    queryFn: scheduledMessagesApi.getRooms,
  });

  useEffect(() => {
    if (existingRule?.data) {
      const r = existingRule.data;
      setName(r.name);
      setMessageType(r.message_type);
      setTriggerMode(r.trigger_mode);
      setDayOfWeek(r.day_of_week ?? 1);
      setSendTime(r.send_time ?? '08:00');
      setDaysBeforeMonthStart(r.days_before_month_start ?? 3);
      setWindowMode(r.window_mode ?? 'rolling');
      setWindowDays(r.window_days ?? 7);
      setTargetRoomToken(r.target_room_token);
      setTemplate(r.template);
      setMinDaysOverdue((r.extra_config?.min_days_overdue as number) ?? 14);
      setSubscribable(r.subscribable);
      setAllowedGroups(r.allowed_groups);
      setActive(r.active);
    }
  }, [existingRule]);

  const insertPlaceholder = (placeholder: string) => {
    const el = templateRef.current?.querySelector('textarea') as HTMLTextAreaElement | null;
    if (!el) return;
    const start = el.selectionStart ?? template.length;
    const end = el.selectionEnd ?? template.length;
    const newVal = template.slice(0, start) + placeholder + template.slice(end);
    setTemplate(newVal);
    setTimeout(() => {
      el.setSelectionRange(start + placeholder.length, start + placeholder.length);
      el.focus();
    }, 0);
  };

  const saveMutation = useMutation({
    mutationFn: () => {
      const payload: Record<string, unknown> = {
        name,
        message_type: messageType,
        trigger_mode: messageType === 'fahrzeug_event' ? 'event' : triggerMode,
        day_of_week: triggerMode === 'day_of_week' && messageType !== 'fahrzeug_event' ? dayOfWeek : null,
        send_time: triggerMode === 'day_of_week' && messageType !== 'fahrzeug_event' ? sendTime : null,
        days_before_month_start:
          triggerMode === 'days_before_month_start' && messageType !== 'fahrzeug_event'
            ? daysBeforeMonthStart
            : null,
        window_mode: messageType === 'fahrzeug_event' ? null : windowMode,
        window_days: messageType === 'fahrzeug_event' ? null : windowMode === 'rolling' ? windowDays : null,
        target_room_token: targetRoomToken,
        template,
        extra_config: messageType === 'bestellungen' ? { min_days_overdue: minDaysOverdue } : null,
        subscribable,
        allowed_groups: allowedGroups,
        active,
      };
      if (ruleId) {
        return scheduledMessagesApi.update(ruleId, payload);
      }
      return scheduledMessagesApi.create(payload);
    },
    onSuccess: (result) => {
      showSuccess(ruleId ? 'Regel aktualisiert' : 'Regel erstellt');
      navigate(`/geplante-nachrichten/${result.data.id}`);
    },
    onError: () => showError('Fehler beim Speichern'),
  });

  const isEventType = messageType === 'fahrzeug_event';
  const rooms = roomsData?.data ?? [];
  const roomsConfigured = roomsData?.configured ?? false;
  const roomsError = roomsData?.error;

  if (ruleId && ruleLoading) {
    return (
      <DashboardLayout>
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout>
      <Box sx={{ p: 3, maxWidth: 800 }}>
        <Typography variant="h5" gutterBottom>
          {ruleId ? 'Regel bearbeiten' : 'Neue Regel'}
        </Typography>

        <Paper sx={{ p: 3 }}>
          {/* Name */}
          <Box sx={{ mb: 3 }}>
            <TextField
              label="Name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              fullWidth
              size="small"
              required
            />
          </Box>

          {/* Message Type */}
          <Box sx={{ mb: 3 }}>
            <FormControl fullWidth size="small">
              <FormLabel sx={{ mb: 0.5 }}>Nachrichtentyp</FormLabel>
              <Select
                value={messageType}
                onChange={(e) => setMessageType(e.target.value as MessageType)}
              >
                {MESSAGE_TYPE_OPTIONS.map((t) => (
                  <MenuItem key={t} value={t}>{MESSAGE_TYPE_LABELS[t]}</MenuItem>
                ))}
              </Select>
            </FormControl>
          </Box>

          {/* Trigger */}
          {isEventType ? (
            <Alert severity="info" sx={{ mb: 3 }}>
              Dieser Nachrichtentyp wird automatisch bei Ereignissen ausgelöst.
            </Alert>
          ) : (
            <Box sx={{ mb: 3 }}>
              <FormControl>
                <FormLabel>Auslöser</FormLabel>
                <RadioGroup
                  row
                  value={triggerMode}
                  onChange={(e) => setTriggerMode(e.target.value as TriggerMode)}
                >
                  <FormControlLabel value="day_of_week" control={<Radio />} label="Wochentag + Uhrzeit" />
                  <FormControlLabel value="days_before_month_start" control={<Radio />} label="Tage vor Monatsbeginn" />
                </RadioGroup>
              </FormControl>

              {triggerMode === 'day_of_week' && (
                <Box sx={{ display: 'flex', gap: 2, mt: 1 }}>
                  <FormControl size="small" sx={{ minWidth: 160 }}>
                    <Select
                      value={dayOfWeek}
                      onChange={(e) => setDayOfWeek(Number(e.target.value))}
                    >
                      {WEEKDAY_OPTIONS.map((w) => (
                        <MenuItem key={w.value} value={w.value}>{w.label}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                  <TextField
                    label="Uhrzeit"
                    type="time"
                    value={sendTime}
                    onChange={(e) => setSendTime(e.target.value)}
                    size="small"
                    InputLabelProps={{ shrink: true }}
                  />
                </Box>
              )}

              {triggerMode === 'days_before_month_start' && (
                <Box sx={{ mt: 1 }}>
                  <TextField
                    label="Tage vor Monatsbeginn"
                    type="number"
                    value={daysBeforeMonthStart}
                    onChange={(e) => setDaysBeforeMonthStart(Number(e.target.value))}
                    size="small"
                    sx={{ minWidth: 220 }}
                    inputProps={{ min: 0, max: 28 }}
                  />
                </Box>
              )}
            </Box>
          )}

          {/* Window */}
          {!isEventType && (
            <Box sx={{ mb: 3 }}>
              <FormControl>
                <FormLabel>Zeitfenster</FormLabel>
                <RadioGroup
                  row
                  value={windowMode}
                  onChange={(e) => setWindowMode(e.target.value as WindowMode)}
                >
                  <FormControlLabel value="rolling" control={<Radio />} label="Rollierend (N Tage)" />
                  <FormControlLabel value="calendar_month" control={<Radio />} label="Nächster Kalendermonat" />
                </RadioGroup>
              </FormControl>

              {windowMode === 'rolling' && (
                <Box sx={{ mt: 1 }}>
                  <TextField
                    label="Tage"
                    type="number"
                    value={windowDays}
                    onChange={(e) => setWindowDays(Number(e.target.value))}
                    size="small"
                    inputProps={{ min: 1, max: 365 }}
                  />
                </Box>
              )}
            </Box>
          )}

          {/* Target Room */}
          <Box sx={{ mb: 3 }}>
            <FormControl fullWidth size="small">
              <FormLabel sx={{ mb: 0.5 }}>Zielraum</FormLabel>
              {roomsLoading ? (
                <CircularProgress size={20} />
              ) : !roomsConfigured ? (
                <Alert severity="warning" sx={{ mt: 1 }}>
                  Bot-Konto nicht konfiguriert. Bitte in den Admin-Einstellungen unter Nextcloud konfigurieren.
                </Alert>
              ) : roomsError ? (
                <Alert severity="error" sx={{ mt: 1 }}>
                  Nextcloud nicht erreichbar — Raumliste kann nicht geladen werden.
                </Alert>
              ) : (
                <Select
                  value={targetRoomToken}
                  onChange={(e) => setTargetRoomToken(e.target.value)}
                  displayEmpty
                >
                  <MenuItem value="" disabled>Raum auswählen...</MenuItem>
                  {rooms.map((room) => (
                    <MenuItem key={room.token} value={room.token}>
                      {room.displayName}
                    </MenuItem>
                  ))}
                </Select>
              )}
            </FormControl>
          </Box>

          {/* Template */}
          <Box sx={{ mb: 3 }}>
            <FormLabel sx={{ mb: 0.5, display: 'block' }}>Vorlage</FormLabel>
            <TextField
              ref={templateRef}
              value={template}
              onChange={(e) => setTemplate(e.target.value)}
              multiline
              minRows={4}
              maxRows={12}
              fullWidth
              size="small"
            />
            <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mt: 1 }}>
              {(PLACEHOLDER_MAP[messageType] ?? []).map((ph) => (
                <Chip
                  key={ph}
                  label={ph}
                  size="small"
                  variant="outlined"
                  onClick={() => insertPlaceholder(ph)}
                  sx={{ cursor: 'pointer' }}
                />
              ))}
            </Box>
          </Box>

          {/* Min days overdue (bestellungen only) */}
          {messageType === 'bestellungen' && (
            <Box sx={{ mb: 3 }}>
              <TextField
                label="Mindest-Alter (Tage überfällig)"
                type="number"
                value={minDaysOverdue}
                onChange={(e) => setMinDaysOverdue(Number(e.target.value))}
                size="small"
                inputProps={{ min: 0 }}
              />
            </Box>
          )}

          {/* Subscribable */}
          <Box sx={{ mb: 3 }}>
            <FormControlLabel
              control={
                <Switch checked={subscribable} onChange={(e) => setSubscribable(e.target.checked)} />
              }
              label="Abonnierbar"
            />
            {subscribable && (
              <Box sx={{ mt: 1 }}>
                <FormLabel sx={{ mb: 0.5, display: 'block' }}>Erlaubte Gruppen (leer = alle)</FormLabel>
                <Autocomplete
                  multiple
                  freeSolo
                  options={[]}
                  value={allowedGroups}
                  onChange={(_e, val) => setAllowedGroups(val)}
                  renderTags={(value, getTagProps) =>
                    value.map((option, index) => {
                      const { key, ...tagProps } = getTagProps({ index });
                      return <Chip key={key} label={option} size="small" {...tagProps} />;
                    })
                  }
                  renderInput={(params) => (
                    <TextField {...params} size="small" placeholder="Gruppe eingeben + Enter" />
                  )}
                />
              </Box>
            )}
          </Box>

          {/* Active */}
          <Box sx={{ mb: 3 }}>
            <FormControlLabel
              control={<Switch checked={active} onChange={(e) => setActive(e.target.checked)} />}
              label="Aktiv"
            />
          </Box>

          {/* Actions */}
          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button
              variant="contained"
              onClick={() => saveMutation.mutate()}
              disabled={saveMutation.isPending || !name || (!isEventType && !targetRoomToken)}
            >
              {saveMutation.isPending ? <CircularProgress size={20} sx={{ mr: 1 }} /> : null}
              {ruleId ? 'Speichern' : 'Erstellen'}
            </Button>
            <Button onClick={() => navigate('/geplante-nachrichten')}>
              Abbrechen
            </Button>
          </Box>
        </Paper>
      </Box>
    </DashboardLayout>
  );
}
