import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  TextField,
  Button,
  Alert,
  Chip,
  Typography,
  CircularProgress,
  Divider,
  Stack,
} from '@mui/material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { usePermissionContext } from '../../contexts/PermissionContext';
import { useNotification } from '../../contexts/NotificationContext';
import { toolConfigApi } from '../../services/toolConfig';
import type { ToolConfig } from '../../types/toolConfig.types';
import { scheduledMessagesApi } from '../../services/scheduledMessages';

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

  const { data, isLoading } = useQuery({
    queryKey: ['tool-config', 'nextcloud'],
    queryFn: () => toolConfigApi.get('nextcloud'),
  });

  const [url, setUrl] = useState('');
  const [botUsername, setBotUsername] = useState('');
  const [botAppPassword, setBotAppPassword] = useState('');
  const [testResult, setTestResult] = useState<{ success: boolean; message: string; latencyMs: number } | null>(null);

  useEffect(() => {
    if (data) {
      setUrl(data.url ?? '');
      const d = data as unknown as Record<string, unknown>;
      setBotUsername((d.bot_username as string) ?? '');
      setBotAppPassword((d.bot_app_password as string) ?? '');
    }
  }, [data]);

  const saveMutation = useMutation({
    mutationFn: () => toolConfigApi.update('nextcloud', { url }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tool-config', 'nextcloud'] });
      showSuccess('Nextcloud-Konfiguration gespeichert');
    },
    onError: () => showError('Fehler beim Speichern der Konfiguration'),
  });

  const saveBotMutation = useMutation({
    mutationFn: () =>
      toolConfigApi.update('nextcloud', {
        bot_username: botUsername,
        bot_app_password: botAppPassword,
      } as unknown as Partial<ToolConfig>),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tool-config', 'nextcloud'] });
      showSuccess('Bot-Konfiguration gespeichert');
    },
    onError: () => showError('Fehler beim Speichern der Bot-Konfiguration'),
  });

  const testMutation = useMutation({
    mutationFn: () =>
      toolConfigApi.test('nextcloud', { url: url || undefined }),
    onSuccess: (result) => setTestResult(result),
    onError: () => setTestResult({ success: false, message: 'Verbindungstest fehlgeschlagen', latencyMs: 0 }),
  });

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

  return (
    <Stack spacing={3}>
      <Card>
        <CardContent>
          <Typography variant="h6" sx={{ mb: 1 }}>Nextcloud</Typography>
          <Divider sx={{ mb: 2 }} />

          {!isFeatureEnabled('nextcloud') && (
            <Alert severity="warning" sx={{ mb: 2 }}>
              Dieses Werkzeug befindet sich im Wartungsmodus.
            </Alert>
          )}

          <Stack spacing={2}>
            <TextField
              label="URL"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              size="small"
              fullWidth
              placeholder="https://nextcloud.example.com"
            />

            <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
              <Button
                variant="contained"
                size="small"
                onClick={() => saveMutation.mutate()}
                disabled={saveMutation.isPending}
              >
                Speichern
              </Button>
              <Button
                variant="outlined"
                size="small"
                onClick={() => {
                  setTestResult(null);
                  testMutation.mutate();
                }}
                disabled={testMutation.isPending}
              >
                {testMutation.isPending ? <CircularProgress size={18} sx={{ mr: 1 }} /> : null}
                Verbindung testen
              </Button>
              {testResult && (
                <Chip
                  label={testResult.success ? `Verbunden (${testResult.latencyMs}ms)` : `Fehler: ${testResult.message}`}
                  color={testResult.success ? 'success' : 'error'}
                  size="small"
                />
              )}
            </Box>
          </Stack>

          <Divider sx={{ my: 2 }} />
          <Typography variant="subtitle2" gutterBottom>Bot-Konto</Typography>
          <Stack spacing={2}>
            <TextField
              label="Bot-Benutzername"
              value={botUsername}
              onChange={(e) => setBotUsername(e.target.value)}
              fullWidth
              size="small"
            />
            <TextField
              label="Bot-App-Passwort"
              type="password"
              value={botAppPassword}
              onChange={(e) => setBotAppPassword(e.target.value)}
              fullWidth
              size="small"
            />
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
              <Button
                variant="contained"
                size="small"
                onClick={() => saveBotMutation.mutate()}
                disabled={saveBotMutation.isPending}
              >
                Bot speichern
              </Button>
              <Button
                variant="outlined"
                size="small"
                onClick={async () => {
                  try {
                    const result = await scheduledMessagesApi.getRooms();
                    if (result.configured) {
                      showSuccess(`Verbindung erfolgreich (${result.data?.length ?? 0} Räume)`);
                    } else {
                      showError('Bot nicht konfiguriert');
                    }
                  } catch {
                    showError('Verbindungstest fehlgeschlagen');
                  }
                }}
              >
                Verbindung testen
              </Button>
            </Box>
          </Stack>
        </CardContent>
      </Card>
    </Stack>
  );
}
