'use client';

import { useEffect, useState, useCallback, useMemo } from 'react';
import { BarChart } from '@/components/charts';
import {
  AlertTriangle,
  Bug,
  Filter,
  Info,
  Keyboard,
  RefreshCw,
  Search,
  Smartphone,
  Monitor,
  Globe,
  ChevronDown,
  ChevronRight,
  Clock,
  Layers,
  CheckCircle,
  XCircle,
  RotateCcw,
  UserX,
  Activity,
} from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

// ─── Types ──────────────────────────────────────────────────────

interface TelemetryEvent {
  id: string;
  productId: string;
  userId?: string;
  anonymousInstallId?: string;
  sessionId: string;
  platform: string;
  channel: string;
  osFamily: string;
  osVersion?: string;
  deviceModel?: string;
  appVersion: string;
  buildNumber: string;
  releaseChannel: string;
  eventType: string;
  module: string;
  feature?: string;
  eventName: string;
  errorDomain?: string;
  errorCode?: string;
  message?: string;
  tags?: Record<string, string>;
  metrics?: Record<string, number>;
  context?: Record<string, unknown>;
  occurredAt: string;
  receivedAt: string;
}

interface TelemetryCluster {
  id: string;
  pk?: string;
  fingerprint: string;
  platform: string;
  channel: string;
  module: string;
  eventName: string;
  affectedVersions: Array<{
    appVersion: string;
    buildNumber: string;
    count: number;
    lastSeenAt: string;
  }>;
  firstSeenAt: string;
  lastSeenAt: string;
  totalCount: number;
  affectedUserIds: string[];
  affectedInstallIds: string[];
  affectedOsFamilies: string[];
  sampleErrorDomain?: string;
  sampleErrorCode?: string;
  sampleMessage?: string;
  severity: string;
  status?: string;
  resolvedBy?: string;
  resolvedAt?: string;
}

interface TelemetryMetrics {
  totalEventsIngested: number;
  totalEventsRejected: number;
  totalBatchRequests: number;
  totalRateLimited: number;
  totalPiiBlocked: number;
  totalDuplicatesDropped: number;
  uptimeSince: string;
}

// ─── Helpers ────────────────────────────────────────────────────

function _eventTypeIcon(type: string) {
  switch (type) {
    case 'fatal':
    case 'error':
      return <Bug className="h-4 w-4 text-red-500" />;
    case 'warn':
      return <AlertTriangle className="h-4 w-4 text-yellow-500" />;
    case 'info':
      return <Info className="h-4 w-4 text-blue-500" />;
    default:
      return <Info className="h-4 w-4 text-muted-foreground" />;
  }
}

function eventTypeBadge(type: string) {
  const colors: Record<string, string> = {
    fatal: 'bg-red-500/20 text-red-400 border-red-500/30',
    error: 'bg-red-500/10 text-red-500 border-red-500/20',
    warn: 'bg-yellow-500/10 text-yellow-500 border-yellow-500/20',
    info: 'bg-blue-500/10 text-blue-500 border-blue-500/20',
    debug: 'bg-gray-500/10 text-gray-400 border-gray-500/20',
  };
  return (
    <Badge variant="outline" className={colors[type] || colors.debug}>
      {type}
    </Badge>
  );
}

function channelIcon(channel: string) {
  switch (channel) {
    case 'keyboard_extension':
      return <Keyboard className="h-3.5 w-3.5" />;
    case 'mobile_app':
      return <Smartphone className="h-3.5 w-3.5" />;
    case 'desktop_app':
      return <Monitor className="h-3.5 w-3.5" />;
    case 'web_app':
      return <Globe className="h-3.5 w-3.5" />;
    default:
      return <Layers className="h-3.5 w-3.5" />;
  }
}

function timeAgo(dateStr: string): string {
  const now = Date.now();
  const then = new Date(dateStr).getTime();
  const diffMs = now - then;
  const diffMin = Math.floor(diffMs / 60000);
  if (diffMin < 1) return 'just now';
  if (diffMin < 60) return `${diffMin}m ago`;
  const diffHr = Math.floor(diffMin / 60);
  if (diffHr < 24) return `${diffHr}h ago`;
  const diffDay = Math.floor(diffHr / 24);
  return `${diffDay}d ago`;
}

// ─── Sub-components ─────────────────────────────────────────────

function ClusterTimelineChart({ clusters }: { clusters: TelemetryCluster[] }) {
  const chartData = useMemo(() => {
    const buckets = new Map<string, { date: string; warn: number; error: number; fatal: number }>();
    for (const c of clusters) {
      const day = c.lastSeenAt?.slice(0, 10) || 'unknown';
      if (!buckets.has(day)) buckets.set(day, { date: day, warn: 0, error: 0, fatal: 0 });
      const b = buckets.get(day)!;
      if (c.severity === 'warn') b.warn += c.totalCount;
      else if (c.severity === 'error') b.error += c.totalCount;
      else if (c.severity === 'fatal') b.fatal += c.totalCount;
    }
    return Array.from(buckets.values())
      .sort((a, b) => a.date.localeCompare(b.date))
      .slice(-14);
  }, [clusters]);

  if (chartData.length === 0) return null;

  return (
    <Card className="mb-4">
      <CardHeader className="pb-2">
        <CardTitle className="text-sm">Cluster Occurrence Timeline</CardTitle>
        <CardDescription>
          Total events per day over the last 14 days, colored by the day&apos;s most severe level
          (fatal / error / warn)
        </CardDescription>
      </CardHeader>
      <CardContent>
        <BarChart
          data={chartData.map((d, i) => ({
            id: d.date,
            value: d.fatal + d.error + d.warn,
            label: i % 3 === 0 ? d.date.slice(5) : '',
            color:
              d.fatal > 0
                ? 'var(--bl-danger)'
                : d.error > 0
                  ? 'var(--chart-5)'
                  : 'var(--bl-warning)',
          }))}
          width={720}
          height={200}
          className="h-auto w-full"
          ariaLabel="Total telemetry cluster occurrences per day over the last 14 days"
        />
      </CardContent>
    </Card>
  );
}

function EventDetailExtras({ event: evt }: { event: TelemetryEvent }) {
  const tags = evt.tags;
  const metrics = evt.metrics;
  const dictCtx = evt.context?.dictation;
  const msg = evt.message;

  return (
    <>
      {tags && Object.keys(tags).length > 0 ? (
        <div className="p-3 pt-0">
          <span className="text-xs text-muted-foreground block mb-1">Tags</span>
          <div className="flex flex-wrap gap-1">
            {(Object.entries(tags) as [string, string][]).map(([k, v]) => (
              <Badge key={k} variant="secondary" className="text-xs font-mono">
                {k}={v}
              </Badge>
            ))}
          </div>
        </div>
      ) : null}

      {metrics && Object.keys(metrics).length > 0 ? (
        <div className="p-3 pt-0">
          <span className="text-xs text-muted-foreground block mb-1">Metrics</span>
          <div className="flex flex-wrap gap-3">
            {(Object.entries(metrics) as [string, number][]).map(([k, v]) => (
              <div key={k} className="text-xs">
                <span className="text-muted-foreground">{k}: </span>
                <span className="font-mono font-medium">{v.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      ) : null}

      {dictCtx != null ? (
        <div className="p-3 pt-0">
          <span className="text-xs text-muted-foreground block mb-1">Dictation Context</span>
          <pre className="text-xs font-mono bg-background rounded p-2 overflow-x-auto">
            {JSON.stringify(dictCtx, null, 2)}
          </pre>
        </div>
      ) : null}

      {msg ? (
        <div className="p-3 pt-0">
          <span className="text-xs text-muted-foreground block mb-1">Message</span>
          <pre className="text-xs font-mono bg-background rounded p-2 whitespace-pre-wrap">
            {msg}
          </pre>
        </div>
      ) : null}
    </>
  );
}

// ─── Component ──────────────────────────────────────────────────

export default function ClientLogsPage() {
  const [events, setEvents] = useState<TelemetryEvent[]>([]);
  const [clusters, setClusters] = useState<TelemetryCluster[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedEvent, setExpandedEvent] = useState<string | null>(null);
  const [tab, setTab] = useState('events');
  const [ingestionMetrics, setIngestionMetrics] = useState<TelemetryMetrics | null>(null);
  const [gdprUserId, setGdprUserId] = useState('');
  const [gdprResult, setGdprResult] = useState<string | null>(null);
  const [gdprLoading, setGdprLoading] = useState(false);
  const [geoData, setGeoData] = useState<Array<{ countryCode: string; count: number }>>([]);
  const [geoLoading, setGeoLoading] = useState(false);

  // Filters
  const [platform, setPlatform] = useState('');
  const [channel, setChannel] = useState('');
  const [eventType, setEventType] = useState('');
  const [module, setModule] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [limit, _setLimit] = useState('50');

  const fetchEvents = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      if (platform) params.set('platform', platform);
      if (channel) params.set('channel', channel);
      if (eventType) params.set('eventType', eventType);
      if (module) params.set('module', module);
      if (limit) params.set('limit', limit);

      if (tab === 'clusters') {
        params.set('view', 'clusters');
        const res = await fetch(`/api/telemetry?${params.toString()}`);
        if (!res.ok) throw new Error('Failed to fetch clusters');
        const data = await res.json();
        setClusters(data.clusters || []);
      } else {
        const res = await fetch(`/api/telemetry?${params.toString()}`);
        if (!res.ok) throw new Error('Failed to fetch events');
        const data = await res.json();
        setEvents(data.events || []);
      }
    } catch (err) {
      setError(String(err));
    } finally {
      setLoading(false);
    }
  }, [platform, channel, eventType, module, limit, tab]);

  useEffect(() => {
    fetchEvents();
  }, [fetchEvents]);

  // Fetch ingestion metrics
  useEffect(() => {
    fetch('/api/telemetry/metrics')
      .then(r => (r.ok ? r.json() : null))
      .then(d => d && setIngestionMetrics(d))
      .catch(() => {});
  }, []);

  // Fetch geo distribution when Geo tab is selected
  useEffect(() => {
    if (tab !== 'geo') return;
    setGeoLoading(true);
    const sevenDaysAgo = new Date(Date.now() - 7 * 86400000).toISOString();
    fetch(`/api/telemetry/geo?from=${encodeURIComponent(sevenDaysAgo)}`)
      .then(r => (r.ok ? r.json() : null))
      .then(d => d && setGeoData(d.distribution || []))
      .catch(() => {})
      .finally(() => setGeoLoading(false));
  }, [tab]);

  const handleClusterAction = async (
    cluster: TelemetryCluster,
    action: 'resolved' | 'ignored' | 'open'
  ) => {
    const pk = cluster.pk || '';
    try {
      await fetch(
        `/api/telemetry/clusters/${encodeURIComponent(cluster.id)}?pk=${encodeURIComponent(pk)}`,
        {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status: action }),
        }
      );
      fetchEvents();
    } catch {
      // best effort
    }
  };

  const handleGdprErasure = async () => {
    if (!gdprUserId.trim()) return;
    if (!confirm(`Delete ALL telemetry data for user "${gdprUserId}"? This cannot be undone.`))
      return;
    setGdprLoading(true);
    setGdprResult(null);
    try {
      const res = await fetch('/api/telemetry/erasure', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: gdprUserId.trim() }),
      });
      const data = await res.json();
      if (res.ok) {
        setGdprResult(`Deleted ${data.eventsDeleted} events for user ${data.userId}`);
        setGdprUserId('');
      } else {
        setGdprResult(`Error: ${data.error}`);
      }
    } catch (err) {
      setGdprResult(`Error: ${String(err)}`);
    } finally {
      setGdprLoading(false);
    }
  };

  // Client-side text filter
  const filteredEvents = events.filter(e => {
    if (!searchQuery) return true;
    const q = searchQuery.toLowerCase();
    return (
      e.eventName.toLowerCase().includes(q) ||
      e.module.toLowerCase().includes(q) ||
      e.message?.toLowerCase().includes(q) ||
      e.userId?.toLowerCase().includes(q) ||
      e.anonymousInstallId?.toLowerCase().includes(q) ||
      e.errorDomain?.toLowerCase().includes(q) ||
      e.errorCode?.toLowerCase().includes(q)
    );
  });

  // Stats
  const errorCount = events.filter(e => e.eventType === 'error' || e.eventType === 'fatal').length;
  const warnCount = events.filter(e => e.eventType === 'warn').length;
  const keyboardCount = events.filter(e => e.channel === 'keyboard_extension').length;
  const uniqueSessions = new Set(events.map(e => e.sessionId)).size;

  return (
    <div className="flex-1 space-y-4 p-8 pt-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight">Client Logs</h2>
          <p className="text-muted-foreground">
            Telemetry events from iOS keyboard, mobile app, and other clients
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchEvents} disabled={loading}>
          <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
          Refresh
        </Button>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 md: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 Events</CardTitle>
            <Layers className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{events.length}</div>
            <p className="text-xs text-muted-foreground">{uniqueSessions} sessions</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Errors</CardTitle>
            <Bug className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-500">{errorCount}</div>
            <p className="text-xs text-muted-foreground">error + fatal</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Warnings</CardTitle>
            <AlertTriangle className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-500">{warnCount}</div>
            <p className="text-xs text-muted-foreground">warn events</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Keyboard Events</CardTitle>
            <Keyboard className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{keyboardCount}</div>
            <p className="text-xs text-muted-foreground">keyboard_extension channel</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center gap-2">
            <Filter className="h-4 w-4" />
            <CardTitle className="text-sm">Filters</CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-3">
            <div className="w-40">
              <Select value={platform} onValueChange={setPlatform}>
                <SelectTrigger>
                  <SelectValue placeholder="Platform" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Platforms</SelectItem>
                  <SelectItem value="ios">iOS</SelectItem>
                  <SelectItem value="android">Android</SelectItem>
                  <SelectItem value="web">Web</SelectItem>
                  <SelectItem value="desktop">Desktop</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="w-48">
              <Select value={channel} onValueChange={setChannel}>
                <SelectTrigger>
                  <SelectValue placeholder="Channel" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Channels</SelectItem>
                  <SelectItem value="keyboard_extension">Keyboard Extension</SelectItem>
                  <SelectItem value="mobile_app">Mobile App</SelectItem>
                  <SelectItem value="desktop_app">Desktop App</SelectItem>
                  <SelectItem value="web_app">Web App</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="w-36">
              <Select value={eventType} onValueChange={setEventType}>
                <SelectTrigger>
                  <SelectValue placeholder="Level" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Levels</SelectItem>
                  <SelectItem value="fatal">Fatal</SelectItem>
                  <SelectItem value="error">Error</SelectItem>
                  <SelectItem value="warn">Warn</SelectItem>
                  <SelectItem value="info">Info</SelectItem>
                  <SelectItem value="debug">Debug</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="w-48">
              <Input
                placeholder="Module..."
                value={module}
                onChange={e => setModule(e.target.value)}
              />
            </div>
            <div className="flex-1 min-w-[200px]">
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search events, errors, users..."
                  className="pl-8"
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tabs: Events | Clusters */}
      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="events">Events</TabsTrigger>
          <TabsTrigger value="clusters">Error Clusters</TabsTrigger>
          <TabsTrigger value="metrics">
            <Activity className="mr-1 h-3.5 w-3.5" />
            Metrics
          </TabsTrigger>
          <TabsTrigger value="geo">
            <Globe className="mr-1 h-3.5 w-3.5" />
            Geo
          </TabsTrigger>
          <TabsTrigger value="gdpr">
            <UserX className="mr-1 h-3.5 w-3.5" />
            GDPR Erasure
          </TabsTrigger>
        </TabsList>

        {/* Events Tab */}
        <TabsContent value="events" className="space-y-4">
          {error && (
            <Card className="border-red-500/20">
              <CardContent className="pt-4">
                <p className="text-sm text-red-500">{error}</p>
              </CardContent>
            </Card>
          )}

          <Card>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[30px]"></TableHead>
                    <TableHead className="w-[70px]">Level</TableHead>
                    <TableHead>Event</TableHead>
                    <TableHead className="w-[120px]">Channel</TableHead>
                    <TableHead className="w-[100px]">Version</TableHead>
                    <TableHead>Message</TableHead>
                    <TableHead className="w-[100px]">Time</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading && events.length === 0 ? (
                    Array.from({ length: 8 }).map((_, i) => (
                      <TableRow key={i}>
                        <TableCell colSpan={7}>
                          <Skeleton className="h-6 w-full" />
                        </TableCell>
                      </TableRow>
                    ))
                  ) : filteredEvents.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                        No telemetry events found. Events will appear here once clients start
                        sending data.
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredEvents.map(evt => (
                      <>
                        <TableRow
                          key={evt.id}
                          className="cursor-pointer hover:bg-muted/50"
                          onClick={() => setExpandedEvent(expandedEvent === evt.id ? null : evt.id)}
                        >
                          <TableCell>
                            {expandedEvent === evt.id ? (
                              <ChevronDown className="h-4 w-4 text-muted-foreground" />
                            ) : (
                              <ChevronRight className="h-4 w-4 text-muted-foreground" />
                            )}
                          </TableCell>
                          <TableCell>{eventTypeBadge(evt.eventType)}</TableCell>
                          <TableCell>
                            <div className="flex flex-col">
                              <span className="font-medium text-sm">{evt.eventName}</span>
                              <span className="text-xs text-muted-foreground">{evt.module}</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-1.5 text-xs">
                              {channelIcon(evt.channel)}
                              <span>{evt.channel.replace('_', ' ')}</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <span className="text-xs font-mono">
                              {evt.appVersion} ({evt.buildNumber})
                            </span>
                          </TableCell>
                          <TableCell>
                            <span className="text-xs text-muted-foreground truncate block max-w-[300px]">
                              {evt.message || '—'}
                            </span>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-1 text-xs text-muted-foreground">
                              <Clock className="h-3 w-3" />
                              {timeAgo(evt.occurredAt)}
                            </div>
                          </TableCell>
                        </TableRow>

                        {/* Expanded detail row */}
                        {expandedEvent === evt.id && (
                          <TableRow key={`${evt.id}-detail`}>
                            <TableCell colSpan={7} className="bg-muted/30">
                              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-3 text-xs">
                                <div>
                                  <span className="text-muted-foreground block">Platform</span>
                                  <span className="font-medium">
                                    {evt.platform} / {evt.osFamily}
                                  </span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground block">OS Version</span>
                                  <span className="font-medium">{evt.osVersion || '—'}</span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground block">Device</span>
                                  <span className="font-medium font-mono">
                                    {evt.deviceModel || '—'}
                                  </span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground block">Release</span>
                                  <span className="font-medium">{evt.releaseChannel}</span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground block">User ID</span>
                                  <span className="font-medium font-mono">{evt.userId || '—'}</span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground block">Install ID</span>
                                  <span className="font-medium font-mono">
                                    {evt.anonymousInstallId
                                      ? `${evt.anonymousInstallId.substring(0, 8)}...`
                                      : '—'}
                                  </span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground block">Session ID</span>
                                  <span className="font-medium font-mono">
                                    {evt.sessionId.substring(0, 8)}...
                                  </span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground block">Occurred At</span>
                                  <span className="font-medium">
                                    {new Date(evt.occurredAt).toLocaleString()}
                                  </span>
                                </div>
                                {evt.errorDomain && (
                                  <div>
                                    <span className="text-muted-foreground block">
                                      Error Domain
                                    </span>
                                    <span className="font-medium font-mono">{evt.errorDomain}</span>
                                  </div>
                                )}
                                {evt.errorCode && (
                                  <div>
                                    <span className="text-muted-foreground block">Error Code</span>
                                    <span className="font-medium font-mono">{evt.errorCode}</span>
                                  </div>
                                )}
                                {evt.feature && (
                                  <div>
                                    <span className="text-muted-foreground block">Feature</span>
                                    <span className="font-medium">{evt.feature}</span>
                                  </div>
                                )}
                              </div>

                              <EventDetailExtras event={evt} />
                            </TableCell>
                          </TableRow>
                        )}
                      </>
                    ))
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Clusters Tab */}
        <TabsContent value="clusters" className="space-y-4">
          <ClusterTimelineChart clusters={clusters} />
          <Card>
            <CardHeader>
              <CardTitle>Error Clusters</CardTitle>
              <CardDescription>
                Errors grouped by fingerprint — same root cause across versions and users.
              </CardDescription>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Severity</TableHead>
                    <TableHead>Error</TableHead>
                    <TableHead>Platform</TableHead>
                    <TableHead>Count</TableHead>
                    <TableHead>Users</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Last Seen</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading && clusters.length === 0 ? (
                    Array.from({ length: 4 }).map((_, i) => (
                      <TableRow key={i}>
                        <TableCell colSpan={7}>
                          <Skeleton className="h-6 w-full" />
                        </TableCell>
                      </TableRow>
                    ))
                  ) : clusters.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                        No error clusters found. Clusters form automatically when warn/error/fatal
                        events arrive.
                      </TableCell>
                    </TableRow>
                  ) : (
                    clusters.map(c => (
                      <TableRow key={c.id}>
                        <TableCell>{eventTypeBadge(c.severity)}</TableCell>
                        <TableCell>
                          <div className="flex flex-col">
                            <span className="font-medium text-sm">{c.eventName}</span>
                            <span className="text-xs text-muted-foreground">{c.module}</span>
                            {c.sampleMessage && (
                              <span className="text-xs text-muted-foreground truncate max-w-[300px] mt-0.5">
                                {c.sampleMessage}
                              </span>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className="text-xs">
                            {c.platform}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <span className="font-bold text-sm">{c.totalCount}</span>
                        </TableCell>
                        <TableCell>
                          <span className="text-sm">
                            {c.affectedUserIds.length + c.affectedInstallIds.length}
                          </span>
                        </TableCell>
                        <TableCell>
                          {c.status === 'resolved' ? (
                            <Badge
                              variant="outline"
                              className="bg-green-500/10 text-green-500 border-green-500/20"
                            >
                              <CheckCircle className="mr-1 h-3 w-3" /> Resolved
                            </Badge>
                          ) : c.status === 'ignored' ? (
                            <Badge
                              variant="outline"
                              className="bg-gray-500/10 text-gray-400 border-gray-500/20"
                            >
                              <XCircle className="mr-1 h-3 w-3" /> Ignored
                            </Badge>
                          ) : (
                            <Badge
                              variant="outline"
                              className="bg-orange-500/10 text-orange-500 border-orange-500/20"
                            >
                              Open
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell>
                          <span className="text-xs text-muted-foreground">
                            {timeAgo(c.lastSeenAt)}
                          </span>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-1">
                            {c.status !== 'resolved' && (
                              <Button
                                variant="ghost"
                                size="sm"
                                title="Resolve"
                                onClick={() => handleClusterAction(c, 'resolved')}
                              >
                                <CheckCircle className="h-4 w-4 text-green-500" />
                              </Button>
                            )}
                            {c.status !== 'ignored' && (
                              <Button
                                variant="ghost"
                                size="sm"
                                title="Ignore"
                                onClick={() => handleClusterAction(c, 'ignored')}
                              >
                                <XCircle className="h-4 w-4 text-muted-foreground" />
                              </Button>
                            )}
                            {(c.status === 'resolved' || c.status === 'ignored') && (
                              <Button
                                variant="ghost"
                                size="sm"
                                title="Reopen"
                                onClick={() => handleClusterAction(c, 'open')}
                              >
                                <RotateCcw className="h-4 w-4 text-orange-500" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Metrics Tab */}
        <TabsContent value="metrics" className="space-y-4">
          {ingestionMetrics ? (
            <div className="grid gap-4 md:grid-cols-3">
              <Card>
                <CardHeader className="pb-2">
                  <CardDescription>Events Ingested</CardDescription>
                  <CardTitle className="text-3xl text-green-500">
                    {ingestionMetrics.totalEventsIngested.toLocaleString()}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-xs text-muted-foreground">
                    {ingestionMetrics.totalBatchRequests.toLocaleString()} batch requests
                  </p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardDescription>Events Rejected</CardDescription>
                  <CardTitle className="text-3xl text-red-500">
                    {ingestionMetrics.totalEventsRejected.toLocaleString()}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-xs text-muted-foreground">
                    {ingestionMetrics.totalPiiBlocked} PII blocked,{' '}
                    {ingestionMetrics.totalDuplicatesDropped} duplicates
                  </p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardDescription>Rate Limited</CardDescription>
                  <CardTitle className="text-3xl text-yellow-500">
                    {ingestionMetrics.totalRateLimited.toLocaleString()}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-xs text-muted-foreground">
                    Since {new Date(ingestionMetrics.uptimeSince).toLocaleString()}
                  </p>
                </CardContent>
              </Card>
            </div>
          ) : (
            <div className="space-y-3">
              {[1, 2, 3].map(i => (
                <Skeleton key={i} className="h-24 w-full" />
              ))}
            </div>
          )}
        </TabsContent>

        {/* Geo Distribution Tab */}
        <TabsContent value="geo" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Globe className="h-5 w-5" />
                Geographic Distribution
              </CardTitle>
              <CardDescription>
                Event distribution by country (last 7 days). Requires geo enrichment to be enabled.
              </CardDescription>
            </CardHeader>
            <CardContent>
              {geoLoading ? (
                <div className="space-y-3">
                  {[1, 2, 3].map(i => (
                    <Skeleton key={i} className="h-8 w-full" />
                  ))}
                </div>
              ) : geoData.length === 0 ? (
                <p className="text-sm text-muted-foreground py-8 text-center">
                  No geo data available. Enable geo enrichment with{' '}
                  <code>TELEMETRY_GEO_ENABLED=true</code> and configure{' '}
                  <code>TELEMETRY_GEO_API_URL</code>.
                </p>
              ) : (
                <div className="space-y-4">
                  <BarChart
                    data={geoData.map(g => ({
                      id: g.countryCode,
                      value: g.count,
                      label: g.countryCode,
                    }))}
                    width={720}
                    height={240}
                    className="h-auto w-full"
                    ariaLabel="Telemetry events by country over the last 7 days"
                  />
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Country</TableHead>
                        <TableHead className="text-right">Events</TableHead>
                        <TableHead className="text-right">Share</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {(() => {
                        const total = geoData.reduce((s, g) => s + g.count, 0);
                        return geoData.map(g => (
                          <TableRow key={g.countryCode}>
                            <TableCell className="font-medium">{g.countryCode}</TableCell>
                            <TableCell className="text-right">{g.count.toLocaleString()}</TableCell>
                            <TableCell className="text-right text-muted-foreground">
                              {total > 0 ? ((g.count / total) * 100).toFixed(1) : 0}%
                            </TableCell>
                          </TableRow>
                        ));
                      })()}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* GDPR Erasure Tab */}
        <TabsContent value="gdpr" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <UserX className="h-5 w-5 text-destructive" />
                GDPR Data Erasure
              </CardTitle>
              <CardDescription>
                Delete all telemetry events for a specific user. This action is irreversible and
                will be logged in the audit trail.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex gap-3 max-w-lg">
                <Input
                  placeholder="Enter user ID..."
                  value={gdprUserId}
                  onChange={e => setGdprUserId(e.target.value)}
                />
                <Button
                  variant="destructive"
                  onClick={handleGdprErasure}
                  disabled={!gdprUserId.trim() || gdprLoading}
                >
                  {gdprLoading ? 'Deleting...' : 'Erase Data'}
                </Button>
              </div>
              {gdprResult && (
                <p
                  className={`text-sm ${
                    gdprResult.startsWith('Error') ? 'text-red-500' : 'text-green-500'
                  }`}
                >
                  {gdprResult}
                </p>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
