'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ScrollArea } from '@/components/ui/scroll-area';
import { AlertTriangle, TrendingUp, TrendingDown, Activity, Users, Clock, AlertCircle, CheckCircle, XCircle, RefreshCw } from 'lucide-react';

interface ErrorStats {
  totalErrors: number;
  last24Hours: number;
  last7Days: number;
  resolved: number;
  unresolved: number;
  criticalErrors: number;
}

interface ErrorEvent {
  id: string;
  type: string;
  message: string;
  timestamp: Date;
  severity: 'critical' | 'high' | 'medium' | 'low';
  status: 'new' | 'investigating' | 'resolved';
  count: number;
  affectedUsers: number;
  browser?: string;
  os?: string;
  stackTrace?: string;
}

interface ErrorTrend {
  date: string;
  count: number;
}

export function ErrorAnalyticsDashboard() {
  const [timeRange, setTimeRange] = useState('7d');
  const [selectedSeverity, setSelectedSeverity] = useState('all');
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState<ErrorStats>({
    totalErrors: 0,
    last24Hours: 0,
    last7Days: 0,
    resolved: 0,
    unresolved: 0,
    criticalErrors: 0,
  });
  const [errors, setErrors] = useState<ErrorEvent[]>([]);
  const [trends, setTrends] = useState<ErrorTrend[]>([]);

  useEffect(() => {
    loadErrorAnalytics();
  }, [timeRange, selectedSeverity]);

  const loadErrorAnalytics = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`/api/analytics/errors?range=${timeRange}&severity=${selectedSeverity}`);
      const data = await response.json();
      
      setStats(data.stats || generateMockStats());
      setErrors(data.errors || generateMockErrors());
      setTrends(data.trends || generateMockTrends());
    } catch (error) {
      console.error('Failed to load error analytics:', error);
      // Fallback to mock data
      setStats(generateMockStats());
      setErrors(generateMockErrors());
      setTrends(generateMockTrends());
    } finally {
      setIsLoading(false);
    }
  };

  const handleRefresh = () => {
    loadErrorAnalytics();
  };

  const handleResolve = async (errorId: string) => {
    try {
      await fetch(`/api/analytics/errors/${errorId}/resolve`, {
        method: 'POST',
      });
      
      setErrors(errors.map(err =>
        err.id === errorId ? { ...err, status: 'resolved' } : err
      ));
      
      setStats({
        ...stats,
        resolved: stats.resolved + 1,
        unresolved: stats.unresolved - 1,
      });
    } catch (error) {
      console.error('Failed to resolve error:', error);
    }
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'critical': return 'bg-red-100 text-red-800 border-red-200';
      case 'high': return 'bg-orange-100 text-orange-800 border-orange-200';
      case 'medium': return 'bg-yellow-100 text-yellow-800 border-yellow-200';
      case 'low': return 'bg-blue-100 text-blue-800 border-blue-200';
      default: return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'resolved': return <CheckCircle className="h-4 w-4 text-green-600" />;
      case 'investigating': return <Activity className="h-4 w-4 text-blue-600" />;
      case 'new': return <AlertCircle className="h-4 w-4 text-orange-600" />;
      default: return <XCircle className="h-4 w-4 text-gray-600" />;
    }
  };

  const filteredErrors = selectedSeverity === 'all' 
    ? errors 
    : errors.filter(err => err.severity === selectedSeverity);

  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">Error Analytics</h1>
          <p className="text-gray-600 mt-1">Monitor and analyze application errors</p>
        </div>
        <div className="flex gap-3">
          <Select value={timeRange} onValueChange={setTimeRange}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="24h">Last 24 Hours</SelectItem>
              <SelectItem value="7d">Last 7 Days</SelectItem>
              <SelectItem value="30d">Last 30 Days</SelectItem>
              <SelectItem value="90d">Last 90 Days</SelectItem>
            </SelectContent>
          </Select>
          <Button onClick={handleRefresh} variant="outline" size="icon">
            <RefreshCw className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">Total Errors</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <p className="text-2xl font-bold">{stats.totalErrors.toLocaleString()}</p>
              <Activity className="h-5 w-5 text-gray-400" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">Last 24 Hours</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <p className="text-2xl font-bold">{stats.last24Hours}</p>
              <Clock className="h-5 w-5 text-blue-400" />
            </div>
            <div className="flex items-center gap-1 mt-1 text-xs">
              <TrendingDown className="h-3 w-3 text-green-600" />
              <span className="text-green-600">-12% from yesterday</span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">Critical Errors</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <p className="text-2xl font-bold text-red-600">{stats.criticalErrors}</p>
              <AlertTriangle className="h-5 w-5 text-red-400" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">Resolved</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <p className="text-2xl font-bold text-green-600">{stats.resolved}</p>
              <CheckCircle className="h-5 w-5 text-green-400" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">Unresolved</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <p className="text-2xl font-bold text-orange-600">{stats.unresolved}</p>
              <XCircle className="h-5 w-5 text-orange-400" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-gray-600">Resolution Rate</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <p className="text-2xl font-bold">
                {Math.round((stats.resolved / (stats.resolved + stats.unresolved)) * 100)}%
              </p>
              <TrendingUp className="h-5 w-5 text-green-400" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Main Content */}
      <Tabs defaultValue="errors" className="space-y-4">
        <TabsList>
          <TabsTrigger value="errors">Error List</TabsTrigger>
          <TabsTrigger value="trends">Trends</TabsTrigger>
          <TabsTrigger value="insights">Insights</TabsTrigger>
        </TabsList>

        {/* Error List */}
        <TabsContent value="errors" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>Error Events</CardTitle>
                  <CardDescription>Detailed list of application errors</CardDescription>
                </div>
                <Select value={selectedSeverity} onValueChange={setSelectedSeverity}>
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="All Severities" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Severities</SelectItem>
                    <SelectItem value="critical">Critical</SelectItem>
                    <SelectItem value="high">High</SelectItem>
                    <SelectItem value="medium">Medium</SelectItem>
                    <SelectItem value="low">Low</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardHeader>
            <CardContent>
              <ScrollArea className="h-[600px]">
                <div className="space-y-3">
                  {filteredErrors.map((error) => (
                    <Card key={error.id} className="border-l-4" style={{
                      borderLeftColor: error.severity === 'critical' ? '#ef4444' : 
                        error.severity === 'high' ? '#f97316' : 
                        error.severity === 'medium' ? '#eab308' : '#3b82f6'
                    }}>
                      <CardContent className="pt-4">
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-2">
                              {getStatusIcon(error.status)}
                              <Badge className={getSeverityColor(error.severity)}>
                                {error.severity.toUpperCase()}
                              </Badge>
                              <Badge variant="outline">{error.type}</Badge>
                              <span className="text-xs text-gray-500">
                                {new Date(error.timestamp).toLocaleString()}
                              </span>
                            </div>
                            
                            <h4 className="font-semibold mb-2">{error.message}</h4>
                            
                            <div className="grid grid-cols-3 gap-4 text-sm text-gray-600 mb-3">
                              <div>
                                <span className="font-medium">Occurrences:</span> {error.count}
                              </div>
                              <div>
                                <span className="font-medium">Affected Users:</span> {error.affectedUsers}
                              </div>
                              <div>
                                <span className="font-medium">Browser:</span> {error.browser || 'Unknown'}
                              </div>
                            </div>

                            {error.stackTrace && (
                              <details className="text-xs">
                                <summary className="cursor-pointer text-blue-600 hover:text-blue-800">
                                  View Stack Trace
                                </summary>
                                <pre className="mt-2 p-2 bg-gray-50 rounded overflow-x-auto">
                                  {error.stackTrace}
                                </pre>
                              </details>
                            )}
                          </div>
                          
                          <div className="flex gap-2">
                            {error.status !== 'resolved' && (
                              <Button 
                                size="sm" 
                                variant="outline"
                                onClick={() => handleResolve(error.id)}
                              >
                                Mark Resolved
                              </Button>
                            )}
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Trends */}
        <TabsContent value="trends">
          <Card>
            <CardHeader>
              <CardTitle>Error Trends</CardTitle>
              <CardDescription>Track error patterns over time</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-[400px] flex items-center justify-center">
                <div className="text-center text-gray-500">
                  <Activity className="h-12 w-12 mx-auto mb-3 opacity-30" />
                  <p>Error trend visualization would be displayed here</p>
                  <p className="text-sm mt-2">Integrate with Chart.js or Recharts for detailed charts</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Insights */}
        <TabsContent value="insights">
          <div className="grid gap-4">
            <Card>
              <CardHeader>
                <CardTitle>Key Insights</CardTitle>
                <CardDescription>AI-powered error analysis and recommendations</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-start gap-3 p-4 bg-blue-50 rounded-lg">
                  <AlertCircle className="h-5 w-5 text-blue-600 mt-0.5" />
                  <div>
                    <h4 className="font-semibold text-blue-900">High API Error Rate</h4>
                    <p className="text-sm text-blue-800 mt-1">
                      API endpoint /api/quotes is experiencing 23% error rate. Consider implementing retry logic and rate limiting.
                    </p>
                  </div>
                </div>

                <div className="flex items-start gap-3 p-4 bg-orange-50 rounded-lg">
                  <AlertTriangle className="h-5 w-5 text-orange-600 mt-0.5" />
                  <div>
                    <h4 className="font-semibold text-orange-900">Memory Leak Detected</h4>
                    <p className="text-sm text-orange-800 mt-1">
                      Potential memory leak in dashboard component. Memory usage increased by 45% over the last 3 hours.
                    </p>
                  </div>
                </div>

                <div className="flex items-start gap-3 p-4 bg-green-50 rounded-lg">
                  <CheckCircle className="h-5 w-5 text-green-600 mt-0.5" />
                  <div>
                    <h4 className="font-semibold text-green-900">Improved Stability</h4>
                    <p className="text-sm text-green-800 mt-1">
                      Error rate decreased by 34% after recent deployment. Great job on the fixes!
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}

// Mock data generators
function generateMockStats(): ErrorStats {
  return {
    totalErrors: 1247,
    last24Hours: 43,
    last7Days: 312,
    resolved: 892,
    unresolved: 355,
    criticalErrors: 12,
  };
}

function generateMockErrors(): ErrorEvent[] {
  return [
    {
      id: '1',
      type: 'TypeError',
      message: 'Cannot read property "id" of undefined',
      timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
      severity: 'critical',
      status: 'new',
      count: 45,
      affectedUsers: 23,
      browser: 'Chrome 120',
      os: 'Windows 10',
      stackTrace: 'at QuoteGenerator.tsx:145\nat processQuote.ts:89\nat async handler.ts:23',
    },
    {
      id: '2',
      type: 'NetworkError',
      message: 'Failed to fetch: /api/quotes - 500 Internal Server Error',
      timestamp: new Date(Date.now() - 5 * 60 * 60 * 1000),
      severity: 'high',
      status: 'investigating',
      count: 127,
      affectedUsers: 67,
      browser: 'Safari 17',
      os: 'macOS 14',
      stackTrace: 'at fetch (native)\nat apiClient.ts:34\nat getQuotes.ts:12',
    },
    {
      id: '3',
      type: 'ValidationError',
      message: 'Invalid email format provided',
      timestamp: new Date(Date.now() - 8 * 60 * 60 * 1000),
      severity: 'medium',
      status: 'resolved',
      count: 8,
      affectedUsers: 8,
      browser: 'Firefox 121',
      os: 'Ubuntu 22.04',
    },
    {
      id: '4',
      type: 'ReferenceError',
      message: 'localStorage is not defined',
      timestamp: new Date(Date.now() - 12 * 60 * 60 * 1000),
      severity: 'low',
      status: 'resolved',
      count: 3,
      affectedUsers: 2,
      browser: 'Edge 120',
      os: 'Windows 11',
    },
  ];
}

function generateMockTrends(): ErrorTrend[] {
  const trends: ErrorTrend[] = [];
  for (let i = 6; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    trends.push({
      date: date.toISOString().split('T')[0],
      count: Math.floor(Math.random() * 100) + 20,
    });
  }
  return trends;
}
