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';

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

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

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

  useEffect(() => {
    if (data) {
      setUrl(data.url ?? '');
      setApiToken('');
    }
  }, [data]);

  const saveMutation = useMutation({
    mutationFn: () => {
      const payload: Record<string, string> = { url };
      if (apiToken) payload.apiToken = apiToken;
      return toolConfigApi.update('vikunja', payload);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tool-config', 'vikunja'] });
      showSuccess('Vikunja-Konfiguration gespeichert');
    },
    onError: () => showError('Fehler beim Speichern der Konfiguration'),
  });

  const testMutation = useMutation({
    mutationFn: () =>
      toolConfigApi.test('vikunja', {
        url: url || undefined,
        apiToken: apiToken || 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 (
    <Card>
      <CardContent>
        <Typography variant="h6" sx={{ mb: 1 }}>Vikunja</Typography>
        <Divider sx={{ mb: 2 }} />

        {!isFeatureEnabled('vikunja') && (
          <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://vikunja.example.com"
          />
          <TextField
            label="API Token"
            type="password"
            value={apiToken}
            onChange={(e) => setApiToken(e.target.value)}
            size="small"
            fullWidth
            helperText="Leer lassen um vorhandenen Wert zu behalten"
          />

          <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>
      </CardContent>
    </Card>
  );
}
