import { ExternalLink, Loader2, Key, Eye, EyeOff, Copy, Trash2, Plus } from 'lucide-react';
import { useEffect, useState } from 'react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { siteSettingsApi, adminAdvancedApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

interface ApiKey {
  id: string;
  key: string;
  value: string;
  description: string;
}

export default function AdminSettings() {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState<string | null>(null);
  const [cleanupDialogOpen, setCleanupDialogOpen] = useState(false);
  const [cleanupLoading, setCleanupLoading] = useState(false);
  const [backupLoading, setBackupLoading] = useState(false);
  
  // API Keys state
  const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
  const [apiKeysLoading, setApiKeysLoading] = useState(false);
  const [showValues, setShowValues] = useState<Record<string, boolean>>({});
  const [newKey, setNewKey] = useState({ key: '', value: '', description: '' });
  const [isAddKeyOpen, setIsAddKeyOpen] = useState(false);

  const [settings, setSettings] = useState<Record<string, string>>({
    site_logo: '',
    site_name: 'LetsGoCappadocia',
    header_background: '',
    hero_image: '',
    maintenance_mode: 'false',
    registration_open: 'true',
    email_notifications: 'true',
    daily_reports: 'true',
    session_timeout_minutes: '30',
  });

  useEffect(() => {
    loadSettings();
    loadApiKeys();
  }, []);

  const loadSettings = async () => {
    try {
      setLoading(true);
      const data = await siteSettingsApi.getAll();
      const settingsObj: Record<string, string> = {};
      data.forEach((setting: any) => {
        settingsObj[setting.key] = setting.value || '';
      });
      setSettings((prev) => ({ ...prev, ...settingsObj }));
    } catch (error) {
      console.error('Error loading settings:', error);
      toast({
        title: 'Hata',
        description: 'Ayarlar yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const loadApiKeys = async () => {
    try {
      setApiKeysLoading(true);
      const data = await adminAdvancedApi.getApiKeys();
      setApiKeys(data as ApiKey[]);
    } catch (error) {
      console.error('Error loading API keys:', error);
      toast({
        title: 'Hata',
        description: 'API anahtarları yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setApiKeysLoading(false);
    }
  };

  const handleUpdateApiKey = async () => {
    if (!newKey.key || !newKey.value) {
      toast({
        title: 'Uyarı',
        description: 'Lütfen anahtar ve değer alanlarını doldurun.',
        variant: 'destructive',
      });
      return;
    }

    try {
      setApiKeysLoading(true);
      await adminAdvancedApi.updateApiKey(newKey.key, newKey.value, newKey.description);
      
      // Auto-sync to site_settings if it's the Clerk Publishable Key
      if (newKey.key === 'VITE_CLERK_PUBLISHABLE_KEY' || newKey.key === 'CLERK_PUBLISHABLE_KEY') {
        await siteSettingsApi.update('clerk_publishable_key', newKey.value);
      }

      await loadApiKeys();
      setNewKey({ key: '', value: '', description: '' });
      setIsAddKeyOpen(false);
      toast({
        title: 'Başarılı',
        description: 'API anahtarı kaydedildi.',
      });
    } catch (error: any) {
      console.error('Error updating API key:', error);
      toast({
        title: 'Hata',
        description: error.message || 'API anahtarı kaydedilemedi.',
        variant: 'destructive',
      });
    } finally {
      setApiKeysLoading(false);
    }
  };

  const handleDeleteApiKey = async (key: string) => {
    try {
      setApiKeysLoading(true);
      await adminAdvancedApi.deleteApiKey(key);
      await loadApiKeys();
      toast({
        title: 'Başarılı',
        description: 'API anahtarı silindi.',
      });
    } catch (error: any) {
      console.error('Error deleting API key:', error);
      toast({
        title: 'Hata',
        description: error.message || 'API anahtarı silinemedi.',
        variant: 'destructive',
      });
    } finally {
      setApiKeysLoading(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast({
      title: 'Kopyalandı',
      description: 'API anahtarı panoya kopyalandı.',
    });
  };

  const toggleShowValue = (key: string) => {
    setShowValues(prev => ({ ...prev, [key]: !prev[key] }));
  };

  const handleImageUpload = async (key: string, file: File) => {
    if (!file) return;

    // File size check (1MB)
    if (file.size > 1024 * 1024) {
      toast({
        title: 'Error',
        description: 'File size must be less than 1MB.',
        variant: 'destructive',
      });
      return;
    }

    // File type check
    if (!file.type.startsWith('image/')) {
      toast({
        title: 'Error',
        description: 'Only image files can be uploaded.',
        variant: 'destructive',
      });
      return;
    }

    try {
      setUploading(key);

      // Delete old image (if exists)
      if (settings[key]) {
        try {
          await siteSettingsApi.deleteImage(settings[key]);
        } catch (error) {
          console.error('Error deleting old image:', error);
        }
      }

      // Upload new image
      const publicUrl = await siteSettingsApi.uploadImage(file, key);

      // Update setting
      await siteSettingsApi.update(key, publicUrl);

      // Update state
      setSettings((prev) => ({ ...prev, [key]: publicUrl }));

      toast({
        title: 'Success',
        description: 'Image uploaded successfully.',
      });
    } catch (error: any) {
      console.error('Error uploading image:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to upload image.',
        variant: 'destructive',
      });
    } finally {
      setUploading(null);
    }
  };

  const handleSiteNameUpdate = async () => {
    try {
      await siteSettingsApi.update('site_name', settings.site_name);
      toast({
        title: 'Başarılı',
        description: 'Site adı güncellendi. Değişiklikler tüm sayfalara yansıtılıyor.',
      });
    } catch (error: any) {
      console.error('Error updating site name:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Site adı güncellenemedi.',
        variant: 'destructive',
      });
    }
  };

  const handleToggleSetting = async (key: string, value: boolean) => {
    try {
      await siteSettingsApi.update(key, value ? 'true' : 'false');
      setSettings((prev) => ({ ...prev, [key]: value ? 'true' : 'false' }));
      toast({
        title: 'Success',
        description: 'Setting updated successfully.',
      });
    } catch (error: any) {
      console.error('Error updating setting:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to update setting.',
        variant: 'destructive',
      });
    }
  };

  const handleSessionTimeoutChange = async (value: string) => {
    try {
      await siteSettingsApi.update('session_timeout_minutes', value);
      setSettings((prev) => ({ ...prev, session_timeout_minutes: value }));
      toast({
        title: 'Success',
        description: 'Session timeout updated.',
      });
    } catch (error: any) {
      console.error('Error updating session timeout:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to update session timeout.',
        variant: 'destructive',
      });
    }
  };

  const handleDatabaseCleanup = async () => {
    try {
      setCleanupLoading(true);
      
      // Call both cleanup functions in parallel
      const [tripsResult, rateLimitResult] = await Promise.all([
        supabase.rpc('cleanup_old_anonymous_trips'),
        supabase.rpc('cleanup_rate_limit_logs'),
      ]);

      if (tripsResult.error) throw tripsResult.error;
      if (rateLimitResult.error) throw rateLimitResult.error;

      toast({
        title: 'Success',
        description: 'Cleanup completed successfully.',
      });
      setCleanupDialogOpen(false);
    } catch (error: any) {
      console.error('Error during cleanup:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to complete cleanup.',
        variant: 'destructive',
      });
    } finally {
      setCleanupLoading(false);
    }
  };

  const handleDatabaseBackup = async () => {
    try {
      setBackupLoading(true);
      
      const { data, error } = await supabase.rpc('get_admin_dashboard_stats');
      
      if (error) throw error;

      // Create backup JSON
      const backup = {
        exported_at: new Date().toISOString(),
        stats: data,
      };

      // Create download
      const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `backup_${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      toast({
        title: 'Success',
        description: 'Statistics backup downloaded.',
      });
    } catch (error: any) {
      console.error('Error creating backup:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to create backup.',
        variant: 'destructive',
      });
    } finally {
      setBackupLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="p-6 space-y-6">
        <div className="flex items-center justify-center h-64">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Ayarlar</h1>
        <p className="text-muted-foreground mt-2">Sistem genelindeki ayarları yönetin</p>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Site Görünürlüğü */}
        <Card className="md:col-span-2 shadow-sm border-border">
          <CardHeader className="border-b bg-muted/30">
            <CardTitle className="text-xl">Site Görünürlüğü</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6 pt-6">
            {/* Site Name */}
            <div className="space-y-2">
              <Label htmlFor="site_name" className="text-sm font-semibold">Site Adı</Label>
              <div className="flex gap-2">
                <Input
                  id="site_name"
                  value={settings.site_name || ''}
                  onChange={(e) => setSettings((prev) => ({ ...prev, site_name: e.target.value }))}
                  placeholder="LetsGoCappadocia"
                  className="max-w-md focus-visible:ring-primary"
                />
                <Button onClick={handleSiteNameUpdate} className="bg-primary hover:bg-primary/90">Kaydet</Button>
              </div>
            </div>

            {/* Logo Upload */}
            <div className="space-y-2 pt-2 border-t">
              <Label htmlFor="site_logo" className="text-sm font-semibold">Site Logosu</Label>
              <div className="flex items-center gap-4">
                {settings.site_logo && (
                  <div className="relative w-20 h-20 rounded-lg border border-border overflow-hidden bg-muted p-2">
                    <img
                      src={settings.site_logo}
                      alt="Site Logosu"
                      className="w-full h-full object-contain"
                    />
                  </div>
                )}
                <div className="flex-1">
                  <Input
                    id="site_logo"
                    type="file"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) handleImageUpload('site_logo', file);
                    }}
                    disabled={uploading === 'site_logo'}
                    className="cursor-pointer file:bg-primary file:text-white file:border-none file:px-4 file:py-1 file:rounded-md file:mr-4 file:hover:bg-primary/90"
                  />
                  <p className="text-xs text-muted-foreground mt-2">
                    PNG, JPG veya WEBP formatları desteklenir. Maksimum 1MB.
                  </p>
                </div>
                {uploading === 'site_logo' && (
                  <Loader2 className="h-5 w-5 animate-spin text-primary" />
                )}
              </div>
            </div>

            {/* Header Background Image */}
            <div className="space-y-2 pt-2 border-t">
              <Label htmlFor="header_background" className="text-sm font-semibold">Header Arka Plan Görseli</Label>
              <div className="flex items-center gap-4">
                {settings.header_background && (
                  <div className="relative w-32 h-20 rounded-lg border border-border overflow-hidden bg-muted">
                    <img
                      src={settings.header_background}
                      alt="Header Arka Plan"
                      className="w-full h-full object-cover"
                    />
                  </div>
                )}
                <div className="flex-1">
                  <Input
                    id="header_background"
                    type="file"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) handleImageUpload('header_background', file);
                    }}
                    disabled={uploading === 'header_background'}
                    className="cursor-pointer file:bg-primary file:text-white file:border-none file:px-4 file:py-1 file:rounded-md file:mr-4 file:hover:bg-primary/90"
                  />
                  <p className="text-xs text-muted-foreground mt-2">
                    PNG, JPG veya WEBP formatları desteklenir. Maksimum 1MB. Header arka planı olarak kullanılır.
                  </p>
                </div>
                {uploading === 'header_background' && (
                  <Loader2 className="h-5 w-5 animate-spin text-primary" />
                )}
              </div>
            </div>

            {/* Hero Image Upload */}
            <div className="space-y-2">
              <Label htmlFor="hero_image">Homepage Hero Image</Label>
              <div className="flex items-center gap-4">
                {settings.hero_image && (
                  <div className="relative w-32 h-20 rounded-lg border overflow-hidden bg-muted">
                    <img
                      src={settings.hero_image}
                      alt="Hero Image"
                      className="w-full h-full object-cover"
                    />
                  </div>
                )}
                <div className="flex-1">
                  <Input
                    id="hero_image"
                    type="file"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) handleImageUpload('hero_image', file);
                    }}
                    disabled={uploading === 'hero_image'}
                    className="cursor-pointer"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    PNG, JPG or WEBP. Maximum 1MB. Used for the large image on the trip creation page.
                  </p>
                </div>
                {uploading === 'hero_image' && (
                  <Loader2 className="h-5 w-5 animate-spin text-primary" />
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* General Settings */}
        <Card>
          <CardHeader>
            <CardTitle>General Settings</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between">
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <p className="font-medium">Site Maintenance Mode</p>
                  {settings.maintenance_mode === 'true' && (
                    <Badge variant="destructive" className="text-xs">
                      Site closed to users
                    </Badge>
                  )}
                </div>
                <p className="text-sm text-muted-foreground">Put the site in maintenance mode</p>
              </div>
              <Switch
                checked={settings.maintenance_mode === 'true'}
                onCheckedChange={(checked) => handleToggleSetting('maintenance_mode', checked)}
              />
            </div>
            <div className="flex items-center justify-between">
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <p className="font-medium">New Registrations</p>
                  {settings.registration_open === 'false' && (
                    <Badge variant="secondary" className="text-xs bg-yellow-500/10 text-yellow-700 dark:text-yellow-400">
                      New user registration stopped
                    </Badge>
                  )}
                </div>
                <p className="text-sm text-muted-foreground">Yeni kullanıcı kayıtlarını kontrol edin</p>
              </div>
              <Switch
                checked={settings.registration_open === 'true'}
                onCheckedChange={(checked) => handleToggleSetting('registration_open', checked)}
              />
            </div>

            {/* Clerk Publishable Key Section */}
            <div className="pt-4 border-t space-y-4">
              <div className="space-y-1">
                <p className="font-medium">Clerk Publishable Key</p>
                <p className="text-sm text-muted-foreground">Giriş ve kayıt sistemini etkinleştirmek için anahtarı girin.</p>
              </div>
              <div className="flex gap-2">
                <Input
                  type="password"
                  placeholder="pk_test_..."
                  value={settings.clerk_publishable_key || ''}
                  onChange={(e) => setSettings(prev => ({ ...prev, clerk_publishable_key: e.target.value }))}
                />
                <Button onClick={async () => {
                  try {
                    await siteSettingsApi.update('clerk_publishable_key', settings.clerk_publishable_key);
                    toast({ title: 'Başarılı', description: 'Clerk anahtarı kaydedildi. Uygulama yeniden başlatılacak.' });
                    setTimeout(() => window.location.reload(), 1500);
                  } catch (e: any) {
                    toast({ title: 'Hata', description: e.message, variant: 'destructive' });
                  }
                }}>
                  Kaydet
                </Button>
              </div>
              {!import.meta.env.VITE_CLERK_PUBLISHABLE_KEY && !settings.clerk_publishable_key && (
                <p className="text-xs text-yellow-600 bg-yellow-50 p-2 rounded border border-yellow-200">
                  ⚠️ Şu anda "Demo Girişi" aktif. Gerçek kimlik doğrulama için anahtar girmelisiniz.
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Notifications */}
        <Card>
          <CardHeader>
            <CardTitle>Notifications</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="font-medium">Email Notifications</p>
                <p className="text-sm text-muted-foreground">Admin email notifications</p>
              </div>
              <Switch
                checked={settings.email_notifications === 'true'}
                onCheckedChange={(checked) => handleToggleSetting('email_notifications', checked)}
              />
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="font-medium">Daily Reports</p>
                <p className="text-sm text-muted-foreground">Daily activity reports</p>
              </div>
              <Switch
                checked={settings.daily_reports === 'true'}
                onCheckedChange={(checked) => handleToggleSetting('daily_reports', checked)}
              />
            </div>
          </CardContent>
        </Card>

        {/* API Keys Card */}
        <Card className="md:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Key className="h-5 w-5 text-primary" />
                API Anahtarları
              </CardTitle>
              <CardDescription>
                Sistem tarafından kullanılan üçüncü taraf API anahtarlarını yönetin.
              </CardDescription>
            </div>
            <Dialog open={isAddKeyOpen} onOpenChange={setIsAddKeyOpen}>
              <DialogTrigger asChild>
                <Button size="sm">
                  <Plus className="h-4 w-4 mr-2" />
                  Yeni Anahtar
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Yeni API Anahtarı Ekle</DialogTitle>
                  <DialogDescription>
                    Yeni bir API anahtarı ekleyin veya mevcut olanı güncelleyin.
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid gap-2">
                    <Label htmlFor="api_key_name">Anahtar (Örn: GOOGLE_MAPS_KEY)</Label>
                    <Input
                      id="api_key_name"
                      placeholder="API_KEY_NAME"
                      value={newKey.key}
                      onChange={(e) => setNewKey({ ...newKey, key: e.target.value })}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="api_key_value">Değer</Label>
                    <Input
                      id="api_key_value"
                      type="password"
                      placeholder="API anahtar değeri"
                      value={newKey.value}
                      onChange={(e) => setNewKey({ ...newKey, value: e.target.value })}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="api_key_desc">Açıklama</Label>
                    <Input
                      id="api_key_desc"
                      placeholder="Kısa bir açıklama"
                      value={newKey.description}
                      onChange={(e) => setNewKey({ ...newKey, description: e.target.value })}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsAddKeyOpen(false)}>İptal</Button>
                  <Button onClick={handleUpdateApiKey} disabled={apiKeysLoading}>
                    {apiKeysLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    Kaydet
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardHeader>
          <CardContent>
            {apiKeysLoading && apiKeys.length === 0 ? (
              <div className="flex justify-center py-8">
                <Loader2 className="h-8 w-8 animate-spin text-primary" />
              </div>
            ) : apiKeys.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground bg-muted/50 rounded-lg border border-dashed">
                Henüz kayıtlı API anahtarı yok.
              </div>
            ) : (
              <div className="space-y-4">
                {apiKeys.map((apiKey) => (
                  <div key={apiKey.id} className="flex flex-col md:flex-row md:items-center justify-between p-4 rounded-lg border bg-card gap-4">
                    <div className="flex-1 space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="font-mono font-bold text-sm bg-muted px-2 py-0.5 rounded">{apiKey.key}</span>
                        {apiKey.description && (
                          <span className="text-xs text-muted-foreground italic">— {apiKey.description}</span>
                        )}
                      </div>
                      <div className="flex items-center gap-2 mt-2">
                        <div className="relative flex-1 max-w-md">
                          <Input
                            type={showValues[apiKey.key] ? "text" : "password"}
                            value={apiKey.value}
                            readOnly
                            className="h-8 pr-10 font-mono text-xs"
                          />
                          <button
                            onClick={() => toggleShowValue(apiKey.key)}
                            className="absolute right-2 top-1.5 text-muted-foreground hover:text-foreground"
                          >
                            {showValues[apiKey.key] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                          </button>
                        </div>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          onClick={() => copyToClipboard(apiKey.value)}
                        >
                          <Copy className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-destructive hover:text-destructive hover:bg-destructive/10"
                        onClick={() => handleDeleteApiKey(apiKey.key)}
                        disabled={apiKeysLoading}
                      >
                        <Trash2 className="h-4 w-4 mr-2" />
                        Sil
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setNewKey({ key: apiKey.key, value: apiKey.value, description: apiKey.description });
                          setIsAddKeyOpen(true);
                        }}
                      >
                        Düzenle
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Database */}
        <Card>
          <CardHeader>
            <CardTitle>Database</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="font-medium">Backup</p>
                <p className="text-sm text-muted-foreground">Create database backup</p>
              </div>
              <Button 
                variant="outline" 
                size="sm" 
                onClick={handleDatabaseBackup}
                disabled={backupLoading}
              >
                {backupLoading ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin mr-2" />
                    Backing up...
                  </>
                ) : (
                  'Backup'
                )}
              </Button>
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="font-medium">Cleanup</p>
                <p className="text-sm text-muted-foreground">Clean up old data</p>
              </div>
              <Button 
                variant="outline" 
                size="sm"
                onClick={() => setCleanupDialogOpen(true)}
              >
                Clean
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Security */}
        <Card>
          <CardHeader>
            <CardTitle>Security</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="font-medium">Two-Factor Authentication</p>
                <p className="text-sm text-muted-foreground">2FA is configured via Supabase Auth Dashboard.</p>
              </div>
              <Button 
                variant="outline" 
                size="sm"
                asChild
              >
                <a 
                  href="https://supabase.com/dashboard" 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="flex items-center gap-2"
                >
                  Open Dashboard
                  <ExternalLink className="h-3 w-3" />
                </a>
              </Button>
            </div>
            <div className="flex items-center justify-between">
              <div>
                <p className="font-medium">Session Timeout</p>
                <p className="text-sm text-muted-foreground">Automatic logout time</p>
              </div>
              <Select
                value={settings.session_timeout_minutes || '30'}
                onValueChange={handleSessionTimeoutChange}
              >
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="15">15 min</SelectItem>
                  <SelectItem value="30">30 min</SelectItem>
                  <SelectItem value="60">1 hour</SelectItem>
                  <SelectItem value="240">4 hours</SelectItem>
                  <SelectItem value="480">8 hours</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Cleanup Confirmation Dialog */}
      <AlertDialog open={cleanupDialogOpen} onOpenChange={setCleanupDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Confirm Database Cleanup</AlertDialogTitle>
            <AlertDialogDescription>
              You are about to clean up old anonymous trips, rate limit logs, and audit logs older than 90 days. 
              This action cannot be undone. Do you want to continue?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={cleanupLoading}>Cancel</AlertDialogCancel>
            <AlertDialogAction 
              onClick={handleDatabaseCleanup}
              disabled={cleanupLoading}
            >
              {cleanupLoading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  Cleaning...
                </>
              ) : (
                'Continue'
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
