import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { useUserRole } from '@/hooks/useUserRole';
import { useRateLimitStats, useRecentMetrics } from '@/hooks/useRateLimitMetrics';
import { useAlertConfigs, useAlertHistory, useUnresolvedAlerts, useUpdateAlertConfig, useResolveAlert } from '@/hooks/useRateLimitAlerts';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line, Legend } from 'recharts';
import { Activity, Shield, TrendingUp, Users, Clock, AlertTriangle, Bell, BellOff, CheckCircle } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ConfirmationDialog } from '@/components/moderation/ConfirmationDialog';
import { format } from 'date-fns';

const COLORS = ['hsl(var(--primary))', 'hsl(var(--secondary))', 'hsl(var(--accent))', 'hsl(var(--muted))', 'hsl(var(--destructive))'];

export default function RateLimitMetrics() {
  useDocumentTitle('Rate Limit Metrics');
  const navigate = useNavigate();
  const { user } = useAuth();
  const { isModerator, loading: rolesLoading } = useUserRole();
  const [timeWindow, setTimeWindow] = useState(60000); // 1 minute default
  const [resolvingAlertId, setResolvingAlertId] = useState<string | null>(null);

  const { data: stats, isLoading: statsLoading, error: statsError } = useRateLimitStats(timeWindow);
  const { data: recentData, isLoading: recentLoading } = useRecentMetrics(50);
  const { data: alertConfigs, isLoading: alertConfigsLoading } = useAlertConfigs();
  const { data: alertHistory, isLoading: alertHistoryLoading } = useAlertHistory(50);
  const { data: unresolvedAlerts } = useUnresolvedAlerts();
  
  const updateConfig = useUpdateAlertConfig();
  const resolveAlert = useResolveAlert();

  // Redirect if not authorized
  if (!rolesLoading && !isModerator()) {
    navigate('/');
    return null;
  }

  if (!user || rolesLoading) {
    return (
      <div className="container mx-auto p-6 space-y-6">
        <Skeleton className="h-12 w-64" />
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <Skeleton key={i} className="h-32" />
          ))}
        </div>
      </div>
    );
  }

  const recentMetrics = recentData?.metrics || [];

  // Prepare chart data
  const tierData = stats?.tierDistribution ? Object.entries(stats.tierDistribution).map(([name, value]) => ({
    name,
    value,
  })) : [];

  const topBlockedIPsData = stats?.topBlockedIPs || [];
  const topBlockedUsersData = stats?.topBlockedUsers || [];

  // Calculate block rate percentage
  const blockRatePercentage = stats?.blockRate ? (stats.blockRate * 100).toFixed(1) : '0.0';

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Rate Limit Metrics</h1>
          <p className="text-muted-foreground">Monitor rate limiting activity and patterns</p>
        </div>
        <Select value={timeWindow.toString()} onValueChange={(v) => setTimeWindow(parseInt(v))}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Time window" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="60000">Last minute</SelectItem>
            <SelectItem value="300000">Last 5 minutes</SelectItem>
            <SelectItem value="900000">Last 15 minutes</SelectItem>
            <SelectItem value="3600000">Last hour</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {statsError && (
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertDescription>
            Failed to load metrics: {statsError instanceof Error ? statsError.message : 'Unknown error'}
          </AlertDescription>
        </Alert>
      )}

      {/* Overview Stats */}
      {statsLoading ? (
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <Skeleton key={i} className="h-32" />
          ))}
        </div>
      ) : (
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Requests</CardTitle>
              <Activity className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.totalRequests || 0}</div>
              <p className="text-xs text-muted-foreground">
                {stats?.allowedRequests || 0} allowed, {stats?.blockedRequests || 0} blocked
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Block Rate</CardTitle>
              <Shield className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{blockRatePercentage}%</div>
              <p className="text-xs text-muted-foreground">
                Percentage of blocked requests
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Unique IPs</CardTitle>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.uniqueIPs || 0}</div>
              <p className="text-xs text-muted-foreground">
                Distinct client addresses
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Unique Users</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.uniqueUsers || 0}</div>
              <p className="text-xs text-muted-foreground">
                Authenticated users
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      <Tabs defaultValue="overview" className="space-y-6">
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="blocked">Blocked Requests</TabsTrigger>
          <TabsTrigger value="recent">Recent Activity</TabsTrigger>
          <TabsTrigger value="alerts">
            Alerts
            {unresolvedAlerts && unresolvedAlerts.length > 0 && (
              <Badge variant="destructive" className="ml-2">{unresolvedAlerts.length}</Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="config">Configuration</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-6">
          <div className="grid gap-6 md:grid-cols-2">
            {/* Tier Distribution */}
            <Card>
              <CardHeader>
                <CardTitle>Tier Distribution</CardTitle>
                <CardDescription>Requests by rate limit tier</CardDescription>
              </CardHeader>
              <CardContent>
                {tierData.length > 0 ? (
                  <ResponsiveContainer width="100%" height={300}>
                    <PieChart>
                      <Pie
                        data={tierData}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                        outerRadius={80}
                        fill="hsl(var(--primary))"
                        dataKey="value"
                      >
                        {tierData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip />
                    </PieChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="flex h-[300px] items-center justify-center text-muted-foreground">
                    No data available
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Request Status */}
            <Card>
              <CardHeader>
                <CardTitle>Request Status</CardTitle>
                <CardDescription>Allowed vs blocked requests</CardDescription>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart
                    data={[
                      { name: 'Allowed', count: stats?.allowedRequests || 0 },
                      { name: 'Blocked', count: stats?.blockedRequests || 0 },
                    ]}
                  >
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="count" fill="hsl(var(--primary))" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="blocked" className="space-y-6">
          <div className="grid gap-6 md:grid-cols-2">
            {/* Top Blocked IPs */}
            <Card>
              <CardHeader>
                <CardTitle>Top Blocked IPs</CardTitle>
                <CardDescription>Most frequently blocked IP addresses</CardDescription>
              </CardHeader>
              <CardContent>
                {topBlockedIPsData.length > 0 ? (
                  <ResponsiveContainer width="100%" height={300}>
                    <BarChart data={topBlockedIPsData} layout="vertical">
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis type="number" />
                      <YAxis dataKey="ip" type="category" width={100} />
                      <Tooltip />
                      <Bar dataKey="count" fill="hsl(var(--destructive))" />
                    </BarChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="flex h-[300px] items-center justify-center text-muted-foreground">
                    No blocked IPs in this time window
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Top Blocked Users */}
            <Card>
              <CardHeader>
                <CardTitle>Top Blocked Users</CardTitle>
                <CardDescription>Most frequently blocked authenticated users</CardDescription>
              </CardHeader>
              <CardContent>
                {topBlockedUsersData.length > 0 ? (
                  <div className="space-y-2">
                    {topBlockedUsersData.map((user, idx) => (
                      <div key={idx} className="flex items-center justify-between p-2 border rounded">
                        <span className="text-sm font-mono truncate flex-1">{user.userId}</span>
                        <Badge variant="destructive">{user.count}</Badge>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="flex h-[300px] items-center justify-center text-muted-foreground">
                    No blocked users in this time window
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="recent" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Recent Activity</CardTitle>
              <CardDescription>Last 50 rate limit checks</CardDescription>
            </CardHeader>
            <CardContent>
              {recentLoading ? (
                <div className="space-y-2">
                  {[1, 2, 3].map((i) => (
                    <Skeleton key={i} className="h-16" />
                  ))}
                </div>
              ) : recentMetrics.length > 0 ? (
                <div className="space-y-2 max-h-[600px] overflow-y-auto">
                  {recentMetrics.map((metric, idx) => (
                    <div
                      key={idx}
                      className={`flex items-center justify-between p-3 border rounded ${
                        metric.allowed ? 'border-border' : 'border-destructive/50 bg-destructive/5'
                      }`}
                    >
                      <div className="flex items-center gap-4 flex-1">
                        <Clock className="h-4 w-4 text-muted-foreground" />
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <span className="font-mono text-sm">{metric.functionName}</span>
                            <Badge variant={metric.allowed ? 'secondary' : 'destructive'}>
                              {metric.allowed ? 'Allowed' : 'Blocked'}
                            </Badge>
                            <Badge variant="outline">{metric.tier}</Badge>
                          </div>
                          <div className="text-xs text-muted-foreground mt-1">
                            IP: {metric.clientIP} {metric.userId && `• User: ${metric.userId.slice(0, 8)}...`}
                          </div>
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium">
                          {metric.allowed ? `${metric.remaining} left` : `Retry: ${metric.retryAfter}s`}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {format(new Date(metric.timestamp), 'HH:mm:ss')}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex h-[300px] items-center justify-center text-muted-foreground">
                  No recent activity
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="alerts" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Alert History</CardTitle>
              <CardDescription>Recent rate limit threshold violations</CardDescription>
            </CardHeader>
            <CardContent>
              {alertHistoryLoading ? (
                <div className="space-y-2">
                  {[1, 2, 3].map((i) => (
                    <Skeleton key={i} className="h-20" />
                  ))}
                </div>
              ) : alertHistory && alertHistory.length > 0 ? (
                <div className="space-y-2 max-h-[600px] overflow-y-auto">
                  {alertHistory.map((alert) => (
                    <div
                      key={alert.id}
                      className={`flex items-start justify-between p-4 border rounded ${
                        alert.resolved_at ? 'border-border bg-muted/30' : 'border-destructive/50 bg-destructive/5'
                      }`}
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          {alert.resolved_at ? (
                            <CheckCircle className="h-4 w-4 text-muted-foreground" />
                          ) : (
                            <AlertTriangle className="h-4 w-4 text-destructive" />
                          )}
                          <Badge variant={alert.resolved_at ? 'secondary' : 'destructive'}>
                            {alert.metric_type}
                          </Badge>
                          <span className="text-xs text-muted-foreground">
                            {format(new Date(alert.created_at), 'PPp')}
                          </span>
                        </div>
                        <p className="text-sm mb-2">{alert.alert_message}</p>
                        <div className="flex gap-4 text-xs text-muted-foreground">
                          <span>Value: {alert.metric_value.toFixed(2)}</span>
                          <span>Threshold: {alert.threshold_value.toFixed(2)}</span>
                          <span>Window: {alert.time_window_ms / 1000}s</span>
                        </div>
                        {alert.resolved_at && (
                          <p className="text-xs text-muted-foreground mt-1">
                            Resolved: {format(new Date(alert.resolved_at), 'PPp')}
                          </p>
                        )}
                      </div>
                      {!alert.resolved_at && (
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => setResolvingAlertId(alert.id)}
                          loading={resolveAlert.isPending && resolvingAlertId === alert.id}
                          disabled={resolveAlert.isPending}
                          className="gap-2"
                        >
                          <CheckCircle className="h-4 w-4" />
                          Resolve
                        </Button>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex h-[300px] items-center justify-center text-muted-foreground">
                  No alerts triggered yet
                </div>
              )}
            </CardContent>
          </Card>
          
          <ConfirmationDialog
            open={resolvingAlertId !== null}
            onOpenChange={(open) => !open && setResolvingAlertId(null)}
            title="Resolve Alert"
            description="Are you sure you want to mark this alert as resolved? This action cannot be undone."
            confirmLabel="Resolve"
            onConfirm={() => {
              if (resolvingAlertId) {
                resolveAlert.mutate(resolvingAlertId);
                setResolvingAlertId(null);
              }
            }}
          />
        </TabsContent>

        <TabsContent value="config" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Alert Configuration</CardTitle>
              <CardDescription>Configure thresholds for automated alerts</CardDescription>
            </CardHeader>
            <CardContent>
              {alertConfigsLoading ? (
                <div className="space-y-4">
                  {[1, 2, 3].map((i) => (
                    <Skeleton key={i} className="h-24" />
                  ))}
                </div>
              ) : alertConfigs && alertConfigs.length > 0 ? (
                <div className="space-y-4">
                  {alertConfigs.map((config) => (
                    <div key={config.id} className="p-4 border rounded space-y-3">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <Badge variant="outline">{config.metric_type}</Badge>
                          <Switch
                            checked={config.enabled}
                            onCheckedChange={(enabled) =>
                              updateConfig.mutate({ id: config.id, updates: { enabled } })
                            }
                          />
                          {config.enabled ? (
                            <span className="text-sm text-muted-foreground flex items-center gap-1">
                              <Bell className="h-3 w-3" /> Enabled
                            </span>
                          ) : (
                            <span className="text-sm text-muted-foreground flex items-center gap-1">
                              <BellOff className="h-3 w-3" /> Disabled
                            </span>
                          )}
                        </div>
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label className="text-xs">Threshold Value</Label>
                          <Input
                            type="number"
                            step="0.01"
                            value={config.threshold_value}
                            onChange={(e) => {
                              const value = parseFloat(e.target.value);
                              if (!isNaN(value)) {
                                updateConfig.mutate({ 
                                  id: config.id, 
                                  updates: { threshold_value: value } 
                                });
                              }
                            }}
                            className="mt-1"
                          />
                          <p className="text-xs text-muted-foreground mt-1">
                            {config.metric_type === 'block_rate' && 'Value between 0 and 1 (e.g., 0.5 = 50%)'}
                            {config.metric_type === 'total_requests' && 'Number of requests'}
                            {config.metric_type === 'unique_ips' && 'Number of unique IPs'}
                          </p>
                        </div>
                        <div>
                          <Label className="text-xs">Time Window (ms)</Label>
                          <Input
                            type="number"
                            step="1000"
                            value={config.time_window_ms}
                            onChange={(e) => {
                              const value = parseInt(e.target.value);
                              if (!isNaN(value)) {
                                updateConfig.mutate({ 
                                  id: config.id, 
                                  updates: { time_window_ms: value } 
                                });
                              }
                            }}
                            className="mt-1"
                          />
                          <p className="text-xs text-muted-foreground mt-1">
                            Currently: {config.time_window_ms / 1000}s
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex h-[200px] items-center justify-center text-muted-foreground">
                  No alert configurations found
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
