import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {  
  LineChart, Line, BarChart, Bar, AreaChart, Area,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
} from "recharts";
import { Calendar, TrendingUp, BarChart3, Globe, Download } from "lucide-react";
import type { NetworkAnalytics } from "@shared/schema";
import { format, parseISO } from "date-fns";
import { useState } from "react";

export default function AnalyticsHistory() {
  const [days, setDays] = useState(30);
  
  // Fetch historical analytics (hourly aggregations)
  const { data: analytics = [], isLoading } = useQuery<NetworkAnalytics[]>({
    queryKey: [`/api/analytics/recent?days=${days}&hourly=true`],
    refetchInterval: 60000, // Aggiorna ogni minuto
  });

  // Prepara dati per grafici
  const trendData = analytics
    .map(a => {
      // Parse JSON fields safely
      let attacksByCountry = {};
      let attacksByType = {};
      
      try {
        attacksByCountry = a.attacksByCountry ? JSON.parse(a.attacksByCountry) : {};
      } catch {}
      
      try {
        attacksByType = a.attacksByType ? JSON.parse(a.attacksByType) : {};
      } catch {}
      
      return {
        date: format(new Date(a.date), "dd/MM HH:mm"),
        fullDate: a.date,
        totalPackets: a.totalPackets || 0,
        normalPackets: a.normalPackets || 0,
        attackPackets: a.attackPackets || 0,
        attackPercentage: a.totalPackets > 0 
          ? ((a.attackPackets || 0) / a.totalPackets * 100).toFixed(1) 
          : "0",
        uniqueIps: a.uniqueIps || 0,
        attackUniqueIps: a.attackUniqueIps || 0,
      };
    })
    .sort((a, b) => new Date(a.fullDate).getTime() - new Date(b.fullDate).getTime());

  // Aggrega dati per paese (da tutti i giorni)
  const countryAggregation: Record<string, number> = {};
  analytics.forEach(a => {
    if (a.attacksByCountry) {
      try {
        const countries = JSON.parse(a.attacksByCountry);
        if (countries && typeof countries === 'object') {
          Object.entries(countries).forEach(([country, count]) => {
            if (typeof count === 'number') {
              countryAggregation[country] = (countryAggregation[country] || 0) + count;
            }
          });
        }
      } catch (e) {
        console.warn('Failed to parse attacksByCountry:', e);
      }
    }
  });

  const topCountries = Object.entries(countryAggregation)
    .map(([name, attacks]) => ({ name, attacks }))
    .sort((a, b) => b.attacks - a.attacks)
    .slice(0, 10);

  // Calcola metriche totali
  const totalTraffic = analytics.reduce((sum, a) => sum + (a.totalPackets || 0), 0);
  const totalAttacks = analytics.reduce((sum, a) => sum + (a.attackPackets || 0), 0);
  const totalNormal = analytics.reduce((sum, a) => sum + (a.normalPackets || 0), 0);
  const avgAttackRate = totalTraffic > 0 ? ((totalAttacks / totalTraffic) * 100).toFixed(2) : "0";

  return (
    <div className="flex flex-col gap-6 p-6" data-testid="page-analytics-history">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-semibold flex items-center gap-2" data-testid="text-page-title">
            <BarChart3 className="h-8 w-8" />
            Analytics Storici
          </h1>
          <p className="text-muted-foreground" data-testid="text-page-subtitle">
            Statistiche permanenti per analisi long-term
          </p>
        </div>
        
        {/* Time Range Selector */}
        <div className="flex items-center gap-2">
          <Button
            variant={days === 7 ? "default" : "outline"}
            size="sm"
            onClick={() => setDays(7)}
            data-testid="button-7days"
          >
            7 Giorni
          </Button>
          <Button
            variant={days === 30 ? "default" : "outline"}
            size="sm"
            onClick={() => setDays(30)}
            data-testid="button-30days"
          >
            30 Giorni
          </Button>
          <Button
            variant={days === 90 ? "default" : "outline"}
            size="sm"
            onClick={() => setDays(90)}
            data-testid="button-90days"
          >
            90 Giorni
          </Button>
        </div>
      </div>

      {isLoading && (
        <div className="text-center py-8" data-testid="text-loading">
          Caricamento dati storici...
        </div>
      )}

      {!isLoading && analytics.length === 0 && (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            <Calendar className="h-12 w-12 mx-auto mb-4 opacity-50" />
            <p>Nessun dato storico disponibile</p>
            <p className="text-sm mt-2">
              I dati verranno aggregati automaticamente ogni ora dal sistema
            </p>
          </CardContent>
        </Card>
      )}

      {!isLoading && analytics.length > 0 && (
        <>
          {/* Summary KPIs */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card data-testid="card-total-summary">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Traffico Totale ({days}g)
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold" data-testid="text-total-summary">
                  {totalTraffic.toLocaleString()}
                </div>
                <p className="text-xs text-muted-foreground mt-1">pacchetti</p>
              </CardContent>
            </Card>

            <Card data-testid="card-normal-summary">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Traffico Normale
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-green-600" data-testid="text-normal-summary">
                  {totalNormal.toLocaleString()}
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  {(100 - parseFloat(avgAttackRate)).toFixed(1)}% del totale
                </p>
              </CardContent>
            </Card>

            <Card data-testid="card-attacks-summary">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Attacchi Totali
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-red-600" data-testid="text-attacks-summary">
                  {totalAttacks.toLocaleString()}
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  {avgAttackRate}% del traffico
                </p>
              </CardContent>
            </Card>

            <Card data-testid="card-avg-daily">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Media Giornaliera
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold" data-testid="text-avg-daily">
                  {Math.round(totalTraffic / analytics.length).toLocaleString()}
                </div>
                <p className="text-xs text-muted-foreground mt-1">pacchetti/giorno</p>
              </CardContent>
            </Card>
          </div>

          {/* Trend Line Chart */}
          <Card data-testid="card-trend">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="h-5 w-5" />
                Trend Traffico (Normale + Attacchi)
              </CardTitle>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={400}>
                <AreaChart data={trendData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Area
                    type="monotone"
                    dataKey="normalPackets"
                    stackId="1"
                    stroke="#22c55e"
                    fill="#22c55e"
                    name="Normale"
                  />
                  <Area
                    type="monotone"
                    dataKey="attackPackets"
                    stackId="1"
                    stroke="#ef4444"
                    fill="#ef4444"
                    name="Attacchi"
                  />
                </AreaChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>

          {/* Attack Rate Trend */}
          <Card data-testid="card-attack-rate">
            <CardHeader>
              <CardTitle>Percentuale Attacchi nel Tempo</CardTitle>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={trendData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line
                    type="monotone"
                    dataKey="attackPercentage"
                    stroke="#ef4444"
                    name="% Attacchi"
                    strokeWidth={2}
                  />
                </LineChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>

          {/* Top Countries (Historical) */}
          <Card data-testid="card-top-countries">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Globe className="h-5 w-5" />
                Top 10 Paesi Attaccanti (Storico)
              </CardTitle>
            </CardHeader>
            <CardContent>
              {topCountries.length > 0 ? (
                <ResponsiveContainer width="100%" height={400}>
                  <BarChart data={topCountries} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis type="number" />
                    <YAxis dataKey="name" type="category" width={100} />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="attacks" fill="#ef4444" name="Attacchi Totali" />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <div className="text-center py-20 text-muted-foreground">
                  Nessun dato disponibile
                </div>
              )}
            </CardContent>
          </Card>

          {/* Export Button (Placeholder) */}
          <Card data-testid="card-export">
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-semibold">Export Report</h3>
                  <p className="text-sm text-muted-foreground">
                    Esporta i dati in formato CSV per analisi esterne
                  </p>
                </div>
                <Button variant="outline" data-testid="button-export">
                  <Download className="h-4 w-4 mr-2" />
                  Esporta CSV
                </Button>
              </div>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
