import React, { useState } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  Collapse,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  IconButton,
  Typography,
  CircularProgress,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import AddIcon from '@mui/icons-material/Add';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminApi } from '../../services/admin';
import { useNotification } from '../../contexts/NotificationContext';
import type { PingResult, PingHistoryEntry } from '../../types/admin.types';

function ServiceManagerTab() {
  const queryClient = useQueryClient();
  const { showError } = useNotification();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [newName, setNewName] = useState('');
  const [newUrl, setNewUrl] = useState('');
  const [refreshInterval, setRefreshInterval] = useState(15000);
  const [expandedService, setExpandedService] = useState<string | null>(null);
  const [historyData, setHistoryData] = useState<PingHistoryEntry[]>([]);
  const [historyLoading, setHistoryLoading] = useState(false);

  const { data: services, isLoading: servicesLoading } = useQuery({
    queryKey: ['admin', 'services'],
    queryFn: adminApi.getServices,
    refetchInterval: refreshInterval || false,
    placeholderData: (previousData: any) => previousData,
  });

  const { data: pingResults, isLoading: pingLoading } = useQuery({
    queryKey: ['admin', 'services', 'ping'],
    queryFn: adminApi.pingAll,
    refetchInterval: refreshInterval || false,
    placeholderData: (previousData: any) => previousData,
  });

  const createMutation = useMutation({
    mutationFn: (data: { name: string; url: string }) => adminApi.createService(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'services'] });
      setDialogOpen(false);
      setNewName('');
      setNewUrl('');
    },
    onError: (error: any) => {
      const message = error?.response?.data?.message || 'Service konnte nicht erstellt werden';
      showError(message);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => adminApi.deleteService(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'services'] });
    },
    onError: () => {
      showError('Service konnte nicht gelöscht werden');
    },
  });

  const getPingForUrl = (url: string): PingResult | undefined => {
    return pingResults?.find((p) => p.url === url);
  };

  const toggleHistory = async (serviceName: string) => {
    if (expandedService === serviceName) {
      setExpandedService(null);
      return;
    }
    setExpandedService(serviceName);
    setHistoryLoading(true);
    try {
      const data = await adminApi.getPingHistory(serviceName);
      setHistoryData(data);
    } catch {
      setHistoryData([]);
    } finally {
      setHistoryLoading(false);
    }
  };

  const handleCreate = () => {
    if (newName.trim() && newUrl.trim()) {
      createMutation.mutate({ name: newName.trim(), url: newUrl.trim() });
    }
  };

  if (servicesLoading) {
    return <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}><CircularProgress /></Box>;
  }

  const allItems = [
    ...(services ?? []).map((s) => ({
      id: s.id,
      name: s.name,
      url: s.url,
      type: s.type,
      isCustom: s.type === 'custom',
    })),
  ];

  // Also include internal services from ping results that aren't in the DB
  if (pingResults) {
    for (const pr of pingResults) {
      if (!allItems.find((item) => item.url === pr.url)) {
        allItems.push({
          id: pr.url,
          name: pr.name,
          url: pr.url,
          type: 'internal' as const,
          isCustom: false,
        });
      }
    }
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">Service Monitor</Typography>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <FormControl size="small" sx={{ minWidth: 160 }}>
            <InputLabel>Aktualisierung</InputLabel>
            <Select
              value={refreshInterval}
              label="Aktualisierung"
              onChange={(e) => setRefreshInterval(Number(e.target.value))}
            >
              <MenuItem value={5000}>5 Sekunden</MenuItem>
              <MenuItem value={15000}>15 Sekunden</MenuItem>
              <MenuItem value={30000}>30 Sekunden</MenuItem>
              <MenuItem value={60000}>60 Sekunden</MenuItem>
              <MenuItem value={0}>Aus</MenuItem>
            </Select>
          </FormControl>
          <Button startIcon={<AddIcon />} variant="contained" onClick={() => setDialogOpen(true)}>
            Service hinzufuegen
          </Button>
        </Box>
      </Box>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Status</TableCell>
              <TableCell>Name</TableCell>
              <TableCell>URL</TableCell>
              <TableCell>Typ</TableCell>
              <TableCell>Latenz</TableCell>
              <TableCell>Geprüft</TableCell>
              <TableCell>Aktionen</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {allItems.map((item) => {
              const ping = getPingForUrl(item.url);
              const isExpanded = expandedService === item.name;
              return (
                <React.Fragment key={item.id}>
                <TableRow
                  sx={{ cursor: 'pointer', '& > *': { borderBottom: isExpanded ? 'unset' : undefined } }}
                  onClick={() => toggleHistory(item.name)}
                >
                  <TableCell>
                    {pingLoading ? (
                      <CircularProgress size={16} />
                    ) : (
                      <Box
                        sx={{
                          width: 12,
                          height: 12,
                          borderRadius: '50%',
                          bgcolor: ping?.status === 'up' ? 'success.main' : ping ? 'error.main' : 'grey.400',
                        }}
                      />
                    )}
                  </TableCell>
                  <TableCell>{item.name}</TableCell>
                  <TableCell sx={{ maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {item.url}
                  </TableCell>
                  <TableCell>{item.type}</TableCell>
                  <TableCell>{ping ? `${ping.latencyMs}ms` : '-'}</TableCell>
                  <TableCell>
                    {ping?.checked_at ? new Date(ping.checked_at).toLocaleString('de-DE') : '-'}
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      {item.isCustom && (
                        <IconButton
                          size="small"
                          color="error"
                          onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(item.id); }}
                          disabled={deleteMutation.isPending}
                        >
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                      )}
                      <IconButton size="small">
                        {isExpanded ? <ExpandLessIcon fontSize="small" /> : <ExpandMoreIcon fontSize="small" />}
                      </IconButton>
                    </Box>
                  </TableCell>
                </TableRow>
                <TableRow>
                  <TableCell sx={{ py: 0 }} colSpan={7}>
                    <Collapse in={isExpanded} timeout="auto" unmountOnExit>
                      <Box sx={{ py: 1, px: 2 }}>
                        <Typography variant="subtitle2" sx={{ mb: 1 }}>Ping-Verlauf (letzte 20)</Typography>
                        {historyLoading ? (
                          <CircularProgress size={20} />
                        ) : historyData.length === 0 ? (
                          <Typography variant="body2" color="text.secondary">Keine Historie vorhanden</Typography>
                        ) : (
                          <Table size="small">
                            <TableHead>
                              <TableRow>
                                <TableCell>Status</TableCell>
                                <TableCell>Antwortzeit</TableCell>
                                <TableCell>Zeitpunkt</TableCell>
                              </TableRow>
                            </TableHead>
                            <TableBody>
                              {historyData.map((h) => (
                                <TableRow key={h.id}>
                                  <TableCell>
                                    <Box
                                      sx={{
                                        width: 10,
                                        height: 10,
                                        borderRadius: '50%',
                                        bgcolor: h.status === 'up' ? 'success.main' : 'error.main',
                                        display: 'inline-block',
                                        mr: 1,
                                      }}
                                    />
                                    {h.status}
                                  </TableCell>
                                  <TableCell>{h.response_time_ms != null ? `${h.response_time_ms}ms` : '-'}</TableCell>
                                  <TableCell>{new Date(h.checked_at).toLocaleString('de-DE')}</TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        )}
                      </Box>
                    </Collapse>
                  </TableCell>
                </TableRow>
                </React.Fragment>
              );
            })}
            {allItems.length === 0 && (
              <TableRow>
                <TableCell colSpan={7} align="center">Keine Services konfiguriert</TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Neuen Service hinzufuegen</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="Name"
            fullWidth
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
          />
          <TextField
            margin="dense"
            label="URL"
            fullWidth
            value={newUrl}
            onChange={(e) => setNewUrl(e.target.value)}
            helperText="Vollständige URL mit http:// oder https://"
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)}>Abbrechen</Button>
          <Button
            onClick={handleCreate}
            variant="contained"
            disabled={createMutation.isPending || !newName.trim() || !newUrl.trim()}
          >
            Erstellen
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default ServiceManagerTab;
