import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/db/supabase';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Skeleton } from '@/components/ui/skeleton';
import { toast } from '@/hooks/use-toast';
import { 
  AlertDialog, 
  AlertDialogAction, 
  AlertDialogCancel, 
  AlertDialogContent, 
  AlertDialogDescription, 
  AlertDialogFooter, 
  AlertDialogHeader, 
  AlertDialogTitle, 
  AlertDialogTrigger 
} from '@/components/ui/alert-dialog';
import { Pencil, Check, X, Shield, Trash2, UserX } from 'lucide-react';

interface RateLimitRule {
  id: string;
  endpoint: string;
  max_requests: number;
  window_seconds: number;
  enabled: boolean;
}

interface RateLimitLog {
  id: string;
  created_at: string;
  user_id: string;
  endpoint: string;
  request_count: number;
  ip_address: string;
  blocked: boolean;
  profiles?: {
    email: string;
    username: string;
  };
}

export default function AdminRateLimits() {
  const queryClient = useQueryClient();
  const [editingRuleId, setEditingRuleId] = useState<string | null>(null);
  const [editMaxRequests, setEditMaxRequests] = useState<number>(0);
  const [editWindowSeconds, setEditWindowSeconds] = useState<number>(0);

  // Fetch rate limit rules
  const { data: rules, isLoading: rulesLoading } = useQuery({
    queryKey: ['rate-limit-rules'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('rate_limit_rules')
        .select('*')
        .order('endpoint');
      
      if (error) throw error;
      return data as RateLimitRule[];
    }
  });

  // Fetch blocked requests
  const { data: blockedLogs, isLoading: logsLoading } = useQuery({
    queryKey: ['rate-limit-logs'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('rate_limit_logs')
        .select('*, profiles(email, username)')
        .eq('blocked', true)
        .order('created_at', { ascending: false })
        .limit(50);
      
      if (error) throw error;
      return data as RateLimitLog[];
    }
  });

  // Update rule mutation
  const updateRuleMutation = useMutation({
    mutationFn: async ({ endpoint, maxRequests, windowSeconds }: { endpoint: string; maxRequests: number; windowSeconds: number }) => {
      const { error } = await (supabase.from('rate_limit_rules') as any)
        .update({ 
          max_requests: maxRequests,
          window_seconds: windowSeconds
        })
        .eq('endpoint', endpoint);
      
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rate-limit-rules'] });
      toast({
        title: 'Başarılı',
        description: 'Rate limit kuralı güncellendi',
      });
      setEditingRuleId(null);
    },
    onError: () => {
      toast({
        title: 'Hata',
        description: 'Rate limit kuralı güncellenirken hata oluştu',
        variant: 'destructive'
      });
    }
  });

  // Toggle enabled mutation
  const toggleEnabledMutation = useMutation({
    mutationFn: async ({ endpoint, enabled }: { endpoint: string; enabled: boolean }) => {
      const { error } = await (supabase.from('rate_limit_rules') as any)
        .update({ enabled })
        .eq('endpoint', endpoint);
      
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rate-limit-rules'] });
      toast({
        title: 'Başarılı',
        description: 'Rate limit durumu güncellendi',
      });
    },
    onError: () => {
      toast({
        title: 'Hata',
        description: 'Rate limit durumu güncellenirken hata oluştu',
        variant: 'destructive'
      });
    }
  });

  // Clear single user rate limit mutation
  const clearUserRateLimitMutation = useMutation({
    mutationFn: async (userId: string) => {
      const { error } = await (supabase as any).rpc('admin_clear_rate_limit', {
        p_user_id: userId
      });
      
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rate-limit-logs'] });
      toast({
        title: 'Başarılı',
        description: 'Engel kaldırıldı',
      });
    },
    onError: () => {
      toast({
        title: 'Hata',
        description: 'Engel kaldırılırken hata oluştu',
        variant: 'destructive'
      });
    }
  });

  // Clear all blocked requests mutation
  const clearAllBlockedMutation = useMutation({
    mutationFn: async () => {
      const { error } = await supabase
        .from('rate_limit_logs')
        .delete()
        .eq('blocked', true);
      
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rate-limit-logs'] });
      toast({
        title: 'Başarılı',
        description: 'Tüm engeller temizlendi',
      });
    },
    onError: () => {
      toast({
        title: 'Hata',
        description: 'Engeller temizlenirken hata oluştu',
        variant: 'destructive'
      });
    }
  });

  const handleEditClick = (rule: RateLimitRule) => {
    setEditingRuleId(rule.id);
    setEditMaxRequests(rule.max_requests);
    setEditWindowSeconds(rule.window_seconds);
  };

  const handleSaveClick = (endpoint: string) => {
    updateRuleMutation.mutate({ 
      endpoint, 
      maxRequests: editMaxRequests, 
      windowSeconds: editWindowSeconds 
    });
  };

  const handleCancelClick = () => {
    setEditingRuleId(null);
    setEditMaxRequests(0);
    setEditWindowSeconds(0);
  };

  const formatWindowSeconds = (seconds: number): string => {
    if (seconds === 60) return '1dk';
    if (seconds === 300) return '5dk';
    if (seconds === 3600) return '1sa';
    if (seconds === 86400) return '1gün';
    return `${seconds}sn`;
  };

  if (rulesLoading || logsLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Skeleton className="h-12 w-[300px] mb-6" />
        <Skeleton className="h-[400px] mb-8" />
        <Skeleton className="h-[400px]" />
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex items-center gap-3 mb-6">
        <div className="p-2 bg-primary/10 rounded-lg">
          <Shield className="h-6 w-6 text-primary" />
        </div>
        <h1 className="text-3xl font-bold">Rate Limits Yönetimi</h1>
      </div>

      <div className="space-y-8">
        {/* Rate Limit Rules Card */}
        <Card>
          <CardHeader>
            <CardTitle className="text-xl">Limit Kuralları</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Endpoint</TableHead>
                  <TableHead>Max İstek</TableHead>
                  <TableHead>Pencere (Zaman)</TableHead>
                  <TableHead>Durum</TableHead>
                  <TableHead className="text-right">Düzenle</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rules?.map((rule) => (
                  <TableRow key={rule.id}>
                    <TableCell className="font-mono text-sm">{rule.endpoint}</TableCell>
                    <TableCell>
                      {editingRuleId === rule.id ? (
                        <Input
                          type="number"
                          value={editMaxRequests}
                          onChange={(e) => setEditMaxRequests(Number(e.target.value))}
                          className="w-24"
                        />
                      ) : (
                        <span className="font-semibold">{rule.max_requests}</span>
                      )}
                    </TableCell>
                    <TableCell>
                      {editingRuleId === rule.id ? (
                        <Input
                          type="number"
                          value={editWindowSeconds}
                          onChange={(e) => setEditWindowSeconds(Number(e.target.value))}
                          className="w-24"
                        />
                      ) : (
                        <Badge variant="outline">{formatWindowSeconds(rule.window_seconds)}</Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <Switch
                          checked={rule.enabled}
                          onCheckedChange={(checked) => 
                            toggleEnabledMutation.mutate({ endpoint: rule.endpoint, enabled: checked })
                          }
                        />
                        <Badge variant={rule.enabled ? 'default' : 'destructive'} className={rule.enabled ? 'bg-green-600' : ''}>
                          {rule.enabled ? 'Aktif' : 'Pasif'}
                        </Badge>
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      {editingRuleId === rule.id ? (
                        <div className="flex justify-end gap-2">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleSaveClick(rule.endpoint)}
                          >
                            <Check className="h-4 w-4 text-green-600" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={handleCancelClick}
                          >
                            <X className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      ) : (
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => handleEditClick(rule)}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Blocked Requests Card */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-xl">Engellenen İstekler (Son 50)</CardTitle>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button variant="destructive" size="sm" className="gap-2">
                  <Trash2 className="h-4 w-4" />
                  Tüm Engelleri Temizle
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Emin misiniz?</AlertDialogTitle>
                  <AlertDialogDescription>
                    Tüm engellenen istekler temizlenecek. Bu işlem engellenen kullanıcıların tekrar erişim sağlamasına izin verir.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>İptal</AlertDialogCancel>
                  <AlertDialogAction onClick={() => clearAllBlockedMutation.mutate()} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                    Onayla
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Tarih</TableHead>
                  <TableHead>Kullanıcı</TableHead>
                  <TableHead>Endpoint</TableHead>
                  <TableHead>İstek</TableHead>
                  <TableHead>IP Adresi</TableHead>
                  <TableHead className="text-right">Aksiyon</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {blockedLogs?.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell className="text-xs">
                      {new Date(log.created_at).toLocaleString('tr-TR')}
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="font-medium">{log.profiles?.username || 'Anonim'}</span>
                        <span className="text-xs text-muted-foreground">{log.profiles?.email || 'N/A'}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="font-mono text-[10px]">{log.endpoint}</Badge>
                    </TableCell>
                    <TableCell className="font-bold text-red-600">{log.request_count}</TableCell>
                    <TableCell className="text-xs font-mono">{log.ip_address}</TableCell>
                    <TableCell className="text-right">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => clearUserRateLimitMutation.mutate(log.user_id)}
                        className="gap-1 text-xs"
                      >
                        <UserX className="h-3 w-3" />
                        Engeli Kaldır
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
                {(!blockedLogs || blockedLogs.length === 0) && (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-12 text-muted-foreground italic">
                      Şu an engellenmiş aktif bir istek bulunmuyor.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
