'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { AlertTriangle, CheckCircle, XCircle, AlertCircle, Bell, Filter } from 'lucide-react';
import StatCard from '@/components/dashboard/stat-card';

interface Alert {
  alertId: string;
  timestamp: string;
  type: string;
  severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
  category: string;
  title: string;
  description: string;
  metric: string;
  currentValue: number;
  threshold: number;
  status: 'OPEN' | 'ACKNOWLEDGED' | 'RESOLVED';
  assignedTo?: string;
}

interface AlertStats {
  total: number;
  critical: number;
  high: number;
  medium: number;
  low: number;
  open: number;
  acknowledged: number;
  resolved: number;
}

export default function AlertsPage() {
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [stats, setStats] = useState<AlertStats | null>(null);
  const [filterSeverity, setFilterSeverity] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');

  useEffect(() => {
    const loadData = async () => {
      try {
        const response = await fetch('/api/alerts');
        const data = await response.json();
        
        setAlerts(data.alerts || generateMockAlerts());
        setStats(data.stats || calculateStats(data.alerts || generateMockAlerts()));
      } catch (error) {
        console.error('Erreur chargement alertes:', error);
        const mockAlerts = generateMockAlerts();
        setAlerts(mockAlerts);
        setStats(calculateStats(mockAlerts));
      }
    };
    
    loadData();
  }, []);

  const filteredAlerts = alerts.filter(alert => {
    const matchesSeverity = filterSeverity === 'all' || alert.severity === filterSeverity;
    const matchesStatus = filterStatus === 'all' || alert.status === filterStatus;
    return matchesSeverity && matchesStatus;
  });

  const getSeverityIcon = (severity: string) => {
    switch (severity) {
      case 'CRITICAL': return <XCircle className="h-5 w-5 text-red-600" />;
      case 'HIGH': return <AlertTriangle className="h-5 w-5 text-orange-600" />;
      case 'MEDIUM': return <AlertCircle className="h-5 w-5 text-yellow-600" />;
      case 'LOW': return <Bell className="h-5 w-5 text-blue-600" />;
      default: return <AlertCircle className="h-5 w-5" />;
    }
  };

  const getSeverityVariant = (severity: string) => {
    switch (severity) {
      case 'CRITICAL': return 'destructive';
      case 'HIGH': return 'default';
      case 'MEDIUM': return 'secondary';
      default: return 'outline';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'OPEN': return 'destructive';
      case 'ACKNOWLEDGED': return 'default';
      case 'RESOLVED': return 'secondary';
      default: return 'outline';
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Alertes & Anomalies</h1>
          <p className="text-muted-foreground">Monitoring temps réel et gestion des incidents</p>
        </div>
        <Button>
          <Bell className="h-4 w-4 mr-2" />
          Configurer Alertes
        </Button>
      </div>

      {/* KPIs */}
      <div className="grid gap-4 md:grid-cols-4">
        <StatCard
          title="Alertes Actives"
          value={stats?.open.toString() || '0'}
          icon={AlertTriangle}
          trend={{ value: -12.5, isPositive: true }}
        />
        <StatCard
          title="Critiques"
          value={stats?.critical.toString() || '0'}
          icon={XCircle}
          trend={{ value: -25, isPositive: true }}
        />
        <StatCard
          title="En Traitement"
          value={stats?.acknowledged.toString() || '0'}
          icon={CheckCircle}
          trend={{ value: 8, isPositive: false }}
        />
        <StatCard
          title="Résolues 24h"
          value={stats?.resolved.toString() || '0'}
          icon={CheckCircle}
          trend={{ value: 15, isPositive: true }}
        />
      </div>

      {/* Filtres */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Filtres</CardTitle>
              <CardDescription>{filteredAlerts.length} alerte(s)</CardDescription>
            </div>
            <Filter className="h-5 w-5 text-muted-foreground" />
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex gap-4">
            <div className="space-y-2">
              <div className="text-sm font-medium">Sévérité</div>
              <div className="flex gap-2">
                <Badge
                  variant={filterSeverity === 'all' ? 'default' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterSeverity('all')}
                >
                  Toutes
                </Badge>
                <Badge
                  variant={filterSeverity === 'CRITICAL' ? 'destructive' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterSeverity('CRITICAL')}
                >
                  Critique
                </Badge>
                <Badge
                  variant={filterSeverity === 'HIGH' ? 'default' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterSeverity('HIGH')}
                >
                  Haute
                </Badge>
                <Badge
                  variant={filterSeverity === 'MEDIUM' ? 'secondary' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterSeverity('MEDIUM')}
                >
                  Moyenne
                </Badge>
                <Badge
                  variant={filterSeverity === 'LOW' ? 'outline' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterSeverity('LOW')}
                >
                  Basse
                </Badge>
              </div>
            </div>

            <div className="space-y-2">
              <div className="text-sm font-medium">Statut</div>
              <div className="flex gap-2">
                <Badge
                  variant={filterStatus === 'all' ? 'default' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterStatus('all')}
                >
                  Tous
                </Badge>
                <Badge
                  variant={filterStatus === 'OPEN' ? 'destructive' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterStatus('OPEN')}
                >
                  Ouvertes
                </Badge>
                <Badge
                  variant={filterStatus === 'ACKNOWLEDGED' ? 'default' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterStatus('ACKNOWLEDGED')}
                >
                  Acquittées
                </Badge>
                <Badge
                  variant={filterStatus === 'RESOLVED' ? 'secondary' : 'outline'}
                  className="cursor-pointer"
                  onClick={() => setFilterStatus('RESOLVED')}
                >
                  Résolues
                </Badge>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Liste des alertes */}
      <Tabs defaultValue="list" className="space-y-4">
        <TabsList>
          <TabsTrigger value="list">Liste</TabsTrigger>
          <TabsTrigger value="category">Par Catégorie</TabsTrigger>
          <TabsTrigger value="timeline">Timeline</TabsTrigger>
        </TabsList>

        {/* Liste */}
        <TabsContent value="list">
          <div className="space-y-3">
            {filteredAlerts.map((alert) => (
              <Card key={alert.alertId} className="hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-start gap-4">
                    <div className="mt-1">{getSeverityIcon(alert.severity)}</div>
                    
                    <div className="flex-1 space-y-2">
                      <div className="flex items-start justify-between">
                        <div>
                          <div className="font-semibold">{alert.title}</div>
                          <div className="text-sm text-muted-foreground">{alert.description}</div>
                        </div>
                        <div className="flex gap-2">
                          <Badge variant={getSeverityVariant(alert.severity)}>
                            {alert.severity}
                          </Badge>
                          <Badge variant={getStatusColor(alert.status)}>
                            {alert.status}
                          </Badge>
                        </div>
                      </div>

                      <div className="grid grid-cols-4 gap-4 text-sm">
                        <div>
                          <div className="text-muted-foreground">Catégorie</div>
                          <div className="font-medium">{alert.category}</div>
                        </div>
                        <div>
                          <div className="text-muted-foreground">Métrique</div>
                          <div className="font-medium">{alert.metric}</div>
                        </div>
                        <div>
                          <div className="text-muted-foreground">Valeur</div>
                          <div className="font-medium text-orange-600">
                            {alert.currentValue} (seuil: {alert.threshold})
                          </div>
                        </div>
                        <div>
                          <div className="text-muted-foreground">Date</div>
                          <div className="font-medium">
                            {new Date(alert.timestamp).toLocaleString('fr-FR')}
                          </div>
                        </div>
                      </div>

                      <div className="flex gap-2">
                        {alert.status === 'OPEN' && (
                          <Button size="sm" variant="outline">Acquitter</Button>
                        )}
                        {alert.status !== 'RESOLVED' && (
                          <Button size="sm" variant="outline">Résoudre</Button>
                        )}
                        <Button size="sm" variant="ghost">Détails</Button>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* Par catégorie */}
        <TabsContent value="category">
          <div className="grid gap-4 md:grid-cols-2">
            {['Stock', 'Ventes', 'Système', 'Sécurité'].map((category) => {
              const categoryAlerts = filteredAlerts.filter(a => a.category === category);
              return (
                <Card key={category}>
                  <CardHeader>
                    <CardTitle>{category}</CardTitle>
                    <CardDescription>{categoryAlerts.length} alerte(s)</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      {categoryAlerts.slice(0, 5).map((alert) => (
                        <div key={alert.alertId} className="flex items-center justify-between p-2 border rounded">
                          <div className="flex items-center gap-2">
                            {getSeverityIcon(alert.severity)}
                            <span className="text-sm">{alert.title}</span>
                          </div>
                          <Badge variant={getStatusColor(alert.status)} className="text-xs">
                            {alert.status}
                          </Badge>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </TabsContent>

        {/* Timeline */}
        <TabsContent value="timeline">
          <Card>
            <CardHeader>
              <CardTitle>Timeline des Alertes</CardTitle>
              <CardDescription>Chronologie des 24 dernières heures</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {filteredAlerts.slice(0, 10).map((alert, idx) => (
                  <div key={alert.alertId} className="flex gap-4">
                    <div className="flex flex-col items-center">
                      <div className={`w-3 h-3 rounded-full ${
                        alert.severity === 'CRITICAL' ? 'bg-red-600' :
                        alert.severity === 'HIGH' ? 'bg-orange-600' :
                        alert.severity === 'MEDIUM' ? 'bg-yellow-600' : 'bg-blue-600'
                      }`} />
                      {idx < filteredAlerts.length - 1 && (
                        <div className="w-0.5 h-12 bg-border" />
                      )}
                    </div>
                    <div className="flex-1 pb-4">
                      <div className="flex items-center justify-between">
                        <div className="font-medium">{alert.title}</div>
                        <div className="text-sm text-muted-foreground">
                          {new Date(alert.timestamp).toLocaleTimeString('fr-FR')}
                        </div>
                      </div>
                      <div className="text-sm text-muted-foreground">{alert.description}</div>
                      <div className="flex gap-2 mt-2">
                        <Badge variant={getSeverityVariant(alert.severity)} className="text-xs">
                          {alert.severity}
                        </Badge>
                        <Badge variant="outline" className="text-xs">{alert.category}</Badge>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

// Génération de données mock
function generateMockAlerts(): Alert[] {
  const now = new Date();
  return [
    {
      alertId: 'ALT-001',
      timestamp: new Date(now.getTime() - 30 * 60000).toISOString(),
      type: 'THRESHOLD',
      severity: 'CRITICAL',
      category: 'Stock',
      title: 'Niveau Critique Cuve Diesel',
      description: 'Cuve #1 Diesel sous le seuil critique (5%)',
      metric: 'Tank Level',
      currentValue: 5,
      threshold: 10,
      status: 'OPEN',
    },
    {
      alertId: 'ALT-002',
      timestamp: new Date(now.getTime() - 60 * 60000).toISOString(),
      type: 'ANOMALY',
      severity: 'HIGH',
      category: 'Ventes',
      title: 'Baisse Anormale des Ventes',
      description: 'Volume des ventes -65% par rapport à la moyenne',
      metric: 'Sales Volume',
      currentValue: 350,
      threshold: 1000,
      status: 'ACKNOWLEDGED',
    },
    {
      alertId: 'ALT-003',
      timestamp: new Date(now.getTime() - 90 * 60000).toISOString(),
      type: 'DISCREPANCY',
      severity: 'HIGH',
      category: 'Stock',
      title: 'Écart Inventaire SP95',
      description: 'Différence de 150L entre théorique et physique',
      metric: 'Stock Discrepancy',
      currentValue: 150,
      threshold: 50,
      status: 'OPEN',
    },
    {
      alertId: 'ALT-004',
      timestamp: new Date(now.getTime() - 120 * 60000).toISOString(),
      type: 'SYSTEM',
      severity: 'MEDIUM',
      category: 'Système',
      title: 'Connexion Pompe Instable',
      description: 'Pompe #3 perte de connexion intermittente',
      metric: 'Connection',
      currentValue: 45,
      threshold: 95,
      status: 'ACKNOWLEDGED',
    },
    {
      alertId: 'ALT-005',
      timestamp: new Date(now.getTime() - 180 * 60000).toISOString(),
      type: 'SECURITY',
      severity: 'MEDIUM',
      category: 'Sécurité',
      title: 'Tentative Accès Non Autorisé',
      description: '3 tentatives de connexion échouées',
      metric: 'Login Attempts',
      currentValue: 3,
      threshold: 3,
      status: 'RESOLVED',
    },
    {
      alertId: 'ALT-006',
      timestamp: new Date(now.getTime() - 240 * 60000).toISOString(),
      type: 'THRESHOLD',
      severity: 'LOW',
      category: 'Stock',
      title: 'Stock Bas Café',
      description: 'Stock café sous 20% - commande suggérée',
      metric: 'Shop Stock',
      currentValue: 18,
      threshold: 20,
      status: 'OPEN',
    },
  ];
}

function calculateStats(alerts: Alert[]): AlertStats {
  return {
    total: alerts.length,
    critical: alerts.filter(a => a.severity === 'CRITICAL').length,
    high: alerts.filter(a => a.severity === 'HIGH').length,
    medium: alerts.filter(a => a.severity === 'MEDIUM').length,
    low: alerts.filter(a => a.severity === 'LOW').length,
    open: alerts.filter(a => a.status === 'OPEN').length,
    acknowledged: alerts.filter(a => a.status === 'ACKNOWLEDGED').length,
    resolved: alerts.filter(a => a.status === 'RESOLVED').length,
  };
}
