import {
  Box,
  Typography,
  Paper,
  Button,
  Chip,
  Alert,
  CircularProgress,
  Divider,
} from '@mui/material';
import { ArrowBack, Edit as EditIcon, Send as SendIcon } from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { usePermissionContext } from '../contexts/PermissionContext';
import { useAuth } from '../contexts/AuthContext';
import { useNotification } from '../contexts/NotificationContext';
import { scheduledMessagesApi } from '../services/scheduledMessages';
import type { MessageType } 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 TRIGGER_LABELS: Record<string, string> = {
  day_of_week: 'Wochentag + Uhrzeit',
  days_before_month_start: 'Tage vor Monatsbeginn',
  event: 'Ereignis',
};

const WEEKDAY_LABELS = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];

const WINDOW_LABELS: Record<string, string> = {
  rolling: 'Rollierend',
  calendar_month: 'Nächster Kalendermonat',
};

export default function GeplanteMachrichtenDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { hasPermission } = usePermissionContext();
  const { user } = useAuth();
  const { showSuccess, showError } = useNotification();
  const canEdit = hasPermission('scheduled_messages:edit');
  const canSubscribe = hasPermission('scheduled_messages:subscribe');

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

  const rule = data?.data;

  const triggerMutation = useMutation({
    mutationFn: () => scheduledMessagesApi.trigger(id!),
    onSuccess: () => showSuccess('Nachricht wurde gesendet'),
    onError: (err: unknown) => {
      const msg = err instanceof Error ? err.message : 'Fehler beim Senden';
      showError(msg);
    },
  });

  const canUserSubscribe =
    canSubscribe &&
    rule?.subscribable &&
    (rule.allowed_groups.length === 0 ||
      rule.allowed_groups.some((g) => user?.groups?.includes(g)));

  const handleSubscribe = async () => {
    if (!id) return;
    try {
      const roomResult = await scheduledMessagesApi.getMyBotRoom();
      await scheduledMessagesApi.subscribe(id, roomResult.data.room_token);
      queryClient.invalidateQueries({ queryKey: ['scheduled-messages', id] });
    } catch {
      showError('Abonnieren fehlgeschlagen. Bitte Nextcloud-Konto in den Einstellungen verbinden.');
    }
  };

  const handleUnsubscribe = async () => {
    if (!id) return;
    await scheduledMessagesApi.unsubscribe(id);
    queryClient.invalidateQueries({ queryKey: ['scheduled-messages', id] });
  };

  const formatDate = (iso: string | null) => {
    if (!iso) return 'Noch nie gesendet';
    return new Date(iso).toLocaleString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <DashboardLayout>
      <Box sx={{ p: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Button startIcon={<ArrowBack />} onClick={() => navigate('/geplante-nachrichten')}>
            Zurück
          </Button>
          {canEdit && rule && (
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button
                variant="outlined"
                startIcon={triggerMutation.isPending ? <CircularProgress size={16} /> : <SendIcon />}
                onClick={() => triggerMutation.mutate()}
                disabled={triggerMutation.isPending}
              >
                Jetzt senden
              </Button>
              <Button
                variant="outlined"
                startIcon={<EditIcon />}
                onClick={() => navigate(`/geplante-nachrichten/${id}/bearbeiten`)}
              >
                Bearbeiten
              </Button>
            </Box>
          )}
        </Box>

        {isError && (
          <Alert severity="error">Fehler beim Laden der Regel.</Alert>
        )}

        {isLoading && (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
            <CircularProgress />
          </Box>
        )}

        {rule && (
          <Paper sx={{ p: 3 }}>
            <Typography variant="h5" gutterBottom>{rule.name}</Typography>
            <Divider sx={{ mb: 2 }} />

            <Box sx={{ display: 'grid', gridTemplateColumns: '200px 1fr', gap: 1.5, mb: 2 }}>
              <Typography color="text.secondary">Typ</Typography>
              <Chip
                label={MESSAGE_TYPE_LABELS[rule.message_type] ?? rule.message_type}
                size="small"
                variant="outlined"
              />

              <Typography color="text.secondary">Aktiv</Typography>
              <Chip
                label={rule.active ? 'Ja' : 'Nein'}
                size="small"
                color={rule.active ? 'success' : 'default'}
              />

              <Typography color="text.secondary">Trigger</Typography>
              <Typography>{TRIGGER_LABELS[rule.trigger_mode] ?? rule.trigger_mode}</Typography>

              {rule.trigger_mode === 'day_of_week' && (
                <>
                  <Typography color="text.secondary">Wochentag</Typography>
                  <Typography>
                    {rule.day_of_week != null ? WEEKDAY_LABELS[rule.day_of_week] : '-'}
                  </Typography>
                  <Typography color="text.secondary">Uhrzeit</Typography>
                  <Typography>{rule.send_time ?? '-'}</Typography>
                </>
              )}

              {rule.trigger_mode === 'days_before_month_start' && (
                <>
                  <Typography color="text.secondary">Tage vor Monatsbeginn</Typography>
                  <Typography>{rule.days_before_month_start ?? '-'}</Typography>
                </>
              )}

              {rule.trigger_mode !== 'event' && (
                <>
                  <Typography color="text.secondary">Zeitfenster</Typography>
                  <Typography>
                    {rule.window_mode ? WINDOW_LABELS[rule.window_mode] ?? rule.window_mode : '-'}
                    {rule.window_mode === 'rolling' && rule.window_days != null
                      ? ` (${rule.window_days} Tage)`
                      : ''}
                  </Typography>
                </>
              )}

              <Typography color="text.secondary">Zielraum</Typography>
              <Typography>{rule.target_room_name ?? rule.target_room_token}</Typography>

              <Typography color="text.secondary">Abonnierbar</Typography>
              <Typography>{rule.subscribable ? 'Ja' : 'Nein'}</Typography>

              {rule.allowed_groups.length > 0 && (
                <>
                  <Typography color="text.secondary">Gruppen</Typography>
                  <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
                    {rule.allowed_groups.map((g) => (
                      <Chip key={g} label={g} size="small" variant="outlined" />
                    ))}
                  </Box>
                </>
              )}

              <Typography color="text.secondary">Zuletzt gesendet</Typography>
              <Typography>{formatDate(rule.last_sent_at)}</Typography>

              {canEdit && rule.subscriber_count != null && (
                <>
                  <Typography color="text.secondary">Abonnenten</Typography>
                  <Typography>{rule.subscriber_count}</Typography>
                </>
              )}
            </Box>

            <Divider sx={{ my: 2 }} />
            <Typography color="text.secondary" gutterBottom>Vorlage</Typography>
            <Box
              component="pre"
              sx={{
                p: 2,
                bgcolor: 'grey.100',
                borderRadius: 1,
                overflow: 'auto',
                fontSize: '0.875rem',
                whiteSpace: 'pre-wrap',
              }}
            >
              {rule.template}
            </Box>

            {canUserSubscribe && (
              <Box sx={{ mt: 3 }}>
                {rule.is_subscribed ? (
                  <Button variant="outlined" color="error" onClick={handleUnsubscribe}>
                    Abbestellen
                  </Button>
                ) : (
                  <Button variant="contained" onClick={handleSubscribe}>
                    Abonnieren
                  </Button>
                )}
              </Box>
            )}
          </Paper>
        )}
      </Box>
    </DashboardLayout>
  );
}
