import { useState, useRef, useEffect, useCallback } from 'react';
import {
  Accordion, AccordionDetails, AccordionSummary,
  Box, Button, Card, CardContent, Checkbox, Chip, Typography,
  CircularProgress, FormControlLabel,
  IconButton, Tooltip,
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import SyncIcon from '@mui/icons-material/Sync';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminApi } from '../../services/admin';
import { useNotification } from '../../contexts/NotificationContext';

export default function DebugTab() {
  const queryClient = useQueryClient();
  const { showSuccess, showError } = useNotification();

  // ── FDISK Sync ──
  const logBoxRef = useRef<HTMLDivElement>(null);
  const [force, setForce] = useState(false);

  const { data: syncData, isLoading: syncLoading, isError: syncError } = useQuery({
    queryKey: ['admin', 'fdisk-sync', 'logs'],
    queryFn: adminApi.fdiskSyncLogs,
    refetchInterval: 5000,
  });

  useEffect(() => {
    if (logBoxRef.current) {
      logBoxRef.current.scrollTop = logBoxRef.current.scrollHeight;
    }
  }, [syncData?.logs.length]);

  const triggerMutation = useMutation({
    mutationFn: (forceSync: boolean) => adminApi.fdiskSyncTrigger(forceSync),
    onSuccess: () => {
      showSuccess('Sync gestartet');
      queryClient.invalidateQueries({ queryKey: ['admin', 'fdisk-sync', 'logs'] });
    },
    onError: (err: unknown) => {
      const msg = (err as { response?: { status?: number } })?.response?.status === 409
        ? 'Sync läuft bereits'
        : 'Sync konnte nicht gestartet werden';
      showError(msg);
    },
  });

  const running = syncData?.running ?? false;

  const copyLogs = useCallback(() => {
    const text = (syncData?.logs ?? []).map((e) => e.line).join('\n');
    navigator.clipboard.writeText(text).then(
      () => showSuccess('Logs kopiert'),
      () => showError('Kopieren fehlgeschlagen'),
    );
  }, [syncData?.logs, showSuccess, showError]);

  return (
    <Box>
      <Typography variant="h6" sx={{ mb: 1 }}>Debug-Werkzeuge</Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
        Werkzeuge fuer Fehlersuche und Datenbereinigung.
      </Typography>

      {/* FDISK Sync */}
      <Accordion defaultExpanded={false}>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle1" fontWeight={600}>FDISK Synchronisation</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Card variant="outlined">
            <CardContent sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
              <Box sx={{ flex: 1 }}>
                <Typography variant="body2" color="text.secondary">
                  Synchronisiert Mitgliederdaten und Ausbildungen aus FDISK in die Datenbank.
                  Läuft automatisch täglich um Mitternacht.
                </Typography>
              </Box>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                <Chip
                  label={running ? 'Läuft…' : 'Bereit'}
                  color={running ? 'warning' : 'success'}
                  size="small"
                  icon={running ? <CircularProgress size={12} color="inherit" /> : undefined}
                />
                <Button
                  variant="contained"
                  startIcon={<SyncIcon />}
                  onClick={() => triggerMutation.mutate(force)}
                  disabled={running || triggerMutation.isPending}
                >
                  Jetzt synchronisieren
                </Button>
              </Box>
              <FormControlLabel
                control={<Checkbox checked={force} onChange={(e) => setForce(e.target.checked)} />}
                label="Alle Mitglieder erzwungen synchronisieren"
              />
            </CardContent>
          </Card>

          <Card variant="outlined" sx={{ mt: 2 }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
                <Typography variant="subtitle2">Protokoll (letzte 500 Zeilen)</Typography>
                <Tooltip title="Logs kopieren">
                  <span>
                    <IconButton
                      size="small"
                      onClick={copyLogs}
                      disabled={!syncData?.logs?.length}
                    >
                      <ContentCopyIcon fontSize="small" />
                    </IconButton>
                  </span>
                </Tooltip>
              </Box>
              {syncLoading && (
                <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
                  <CircularProgress size={28} />
                </Box>
              )}
              {syncError && (
                <Typography color="error" variant="body2">
                  Sync-Dienst nicht erreichbar. Läuft der fdisk-sync Container?
                </Typography>
              )}
              {!syncLoading && !syncError && (
                <Box
                  ref={logBoxRef}
                  sx={{
                    fontFamily: 'monospace',
                    fontSize: '0.75rem',
                    bgcolor: 'grey.900',
                    color: 'grey.100',
                    borderRadius: 1,
                    p: 1.5,
                    maxHeight: 500,
                    overflowY: 'auto',
                    whiteSpace: 'pre-wrap',
                    wordBreak: 'break-all',
                  }}
                >
                  {(syncData?.logs ?? []).length === 0 ? (
                    <Typography variant="caption" color="grey.500">Noch keine Logs vorhanden.</Typography>
                  ) : (
                    (syncData?.logs ?? []).map((entry, i) => (
                      <Box
                        key={i}
                        component="span"
                        sx={{
                          display: 'block',
                          color: entry.line.includes('ERROR') || entry.line.includes('WARN')
                            ? (entry.line.includes('ERROR') ? 'error.light' : 'warning.light')
                            : 'inherit',
                        }}
                      >
                        {entry.line}
                      </Box>
                    ))
                  )}
                </Box>
              )}
            </CardContent>
          </Card>
        </AccordionDetails>
      </Accordion>
    </Box>
  );
}
