
/**
 * Performance Monitoring Dashboard Component
 * Displays real-time performance metrics
 */

'use client';

import { useState, useEffect } from 'react';
import { Activity, Clock, AlertTriangle, CheckCircle } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { perfMonitor } from '@/lib/performance';
import { errorLogger } from '@/lib/error-logger';

export function PerformanceMonitor() {
  const [isOpen, setIsOpen] = useState(false);
  const [metrics, setMetrics] = useState<any>({});
  const [errorStats, setErrorStats] = useState<any>({});

  useEffect(() => {
    if (isOpen) {
      // Update metrics every 2 seconds
      const interval = setInterval(() => {
        setMetrics(perfMonitor.getAllMetrics());
        setErrorStats(errorLogger.getStatistics());
      }, 2000);

      return () => clearInterval(interval);
    }
  }, [isOpen]);

  if (!isOpen) {
    return (
      <Button
        onClick={() => setIsOpen(true)}
        variant="outline"
        size="sm"
        className="fixed bottom-20 right-6 z-40 shadow-lg"
      >
        <Activity className="h-4 w-4 mr-2" />
        Performance
      </Button>
    );
  }

  return (
    <Card className="fixed bottom-20 right-6 w-[400px] max-h-[500px] overflow-auto shadow-2xl z-40 p-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold flex items-center gap-2">
          <Activity className="h-5 w-5 text-emerald-600" />
          Performance Monitor
        </h3>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setIsOpen(false)}
        >
          ✕
        </Button>
      </div>

      {/* Performance Metrics */}
      <div className="space-y-4">
        <div>
          <h4 className="text-sm font-semibold mb-2 flex items-center gap-2">
            <Clock className="h-4 w-4" />
            Response Times
          </h4>
          <div className="space-y-2">
            {Object.entries(metrics).length === 0 ? (
              <p className="text-sm text-gray-500">No metrics yet</p>
            ) : (
              Object.entries(metrics).map(([label, data]: [string, any]) => (
                <div key={label} className="flex justify-between items-center text-sm">
                  <span className="text-gray-600">{label}:</span>
                  <div className="flex gap-2">
                    <Badge variant="outline">
                      {data.avg.toFixed(2)}ms avg
                    </Badge>
                    <Badge variant="secondary">
                      {data.count} calls
                    </Badge>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Error Statistics */}
        <div>
          <h4 className="text-sm font-semibold mb-2 flex items-center gap-2">
            <AlertTriangle className="h-4 w-4" />
            Error Statistics
          </h4>
          <div className="space-y-2">
            <div className="flex justify-between items-center text-sm">
              <span className="text-gray-600">Total Errors:</span>
              <Badge variant={errorStats.total > 0 ? 'destructive' : 'outline'}>
                {errorStats.total || 0}
              </Badge>
            </div>
            {errorStats.bySeverity && (
              <>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-600">Critical:</span>
                  <Badge variant={errorStats.bySeverity.critical > 0 ? 'destructive' : 'outline'}>
                    {errorStats.bySeverity.critical}
                  </Badge>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-600">High:</span>
                  <Badge variant={errorStats.bySeverity.high > 0 ? 'destructive' : 'outline'}>
                    {errorStats.bySeverity.high}
                  </Badge>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-600">Medium:</span>
                  <Badge variant="secondary">
                    {errorStats.bySeverity.medium}
                  </Badge>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-600">Low:</span>
                  <Badge variant="outline">
                    {errorStats.bySeverity.low}
                  </Badge>
                </div>
              </>
            )}
          </div>
        </div>

        {/* Actions */}
        <div className="pt-4 border-t flex gap-2">
          <Button
            variant="outline"
            size="sm"
            className="flex-1"
            onClick={() => {
              perfMonitor.clear();
              errorLogger.clear();
              setMetrics({});
              setErrorStats({});
            }}
          >
            Clear Metrics
          </Button>
          <Button
            variant="outline"
            size="sm"
            className="flex-1"
            onClick={() => {
              console.log('Performance Metrics:', perfMonitor.getAllMetrics());
              console.log('Error Logs:', errorLogger.getAllLogs());
            }}
          >
            Log to Console
          </Button>
        </div>
      </div>

      <div className="mt-4 pt-4 border-t">
        <div className="flex items-center gap-2 text-xs text-gray-500">
          <CheckCircle className="h-3 w-3 text-green-600" />
          Real-time monitoring active
        </div>
      </div>
    </Card>
  );
}
