import DashboardLayout from "@/components/DashboardLayout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { trpc } from "@/lib/trpc";
import { BarChart, TrendingUp, AlertCircle, Mail, CheckCircle2, XCircle } from "lucide-react";
import {
  LineChart,
  Line,
  BarChart as RechartsBarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";

export default function AdminRappelsStats() {
  const { data: stats, isLoading: statsLoading } = trpc.rappels.statistiques.useQuery();
  const { data: evolution, isLoading: evolutionLoading } = trpc.rappels.evolution.useQuery();

  const formatPercentage = (value: number) => {
    return `${value.toFixed(1)}%`;
  };

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="page-title">Statistiques des Rappels</h1>
            <p className="text-muted-foreground mt-1">
              Analysez les performances du système de rappels
            </p>
          </div>
          <TrendingUp className="h-8 w-8 text-muted-foreground" />
        </div>

        {/* Cartes de statistiques */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total envoyés</CardTitle>
              <Mail className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {statsLoading ? "..." : stats?.totalEnvoyes || 0}
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                Tous les rappels confondus
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Succès</CardTitle>
              <CheckCircle2 className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">
                {statsLoading ? "..." : stats?.totalSucces || 0}
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                Rappels envoyés avec succès
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Échecs</CardTitle>
              <XCircle className="h-4 w-4 text-red-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-red-600">
                {statsLoading ? "..." : stats?.totalEchecs || 0}
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                Rappels en échec
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Taux de succès</CardTitle>
              <BarChart className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {statsLoading ? "..." : formatPercentage(stats?.tauxSucces || 0)}
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                Ratio succès/total
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Graphique d'évolution */}
        <Card>
          <CardHeader>
            <CardTitle>Évolution des envois</CardTitle>
            <CardDescription>Nombre de rappels envoyés par jour</CardDescription>
          </CardHeader>
          <CardContent>
            {evolutionLoading ? (
              <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                Chargement...
              </div>
            ) : !evolution || evolution.length === 0 ? (
              <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                Aucune donnée disponible
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={evolution}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis
                    dataKey="date"
                    tickFormatter={(value) => {
                      const date = new Date(value);
                      return `${date.getDate()}/${date.getMonth() + 1}`;
                    }}
                  />
                  <YAxis />
                  <Tooltip
                    labelFormatter={(value) => {
                      const date = new Date(value as string);
                      return date.toLocaleDateString("fr-FR");
                    }}
                  />
                  <Legend />
                  <Line
                    type="monotone"
                    dataKey="nbSucces"
                    stroke="#22c55e"
                    name="Succès"
                    strokeWidth={2}
                  />
                  <Line
                    type="monotone"
                    dataKey="nbEchecs"
                    stroke="#ef4444"
                    name="Échecs"
                    strokeWidth={2}
                  />
                </LineChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        {/* Graphique du taux de succès */}
        <Card>
          <CardHeader>
            <CardTitle>Taux de succès par jour</CardTitle>
            <CardDescription>Pourcentage de rappels réussis</CardDescription>
          </CardHeader>
          <CardContent>
            {evolutionLoading ? (
              <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                Chargement...
              </div>
            ) : !evolution || evolution.length === 0 ? (
              <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                Aucune donnée disponible
              </div>
            ) : (
              <ResponsiveContainer width="100%" height={300}>
                <RechartsBarChart
                  data={evolution.map(e => ({
                    ...e,
                    tauxSucces: e.nbEnvoyes > 0 ? (e.nbSucces / e.nbEnvoyes) * 100 : 0,
                  }))}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis
                    dataKey="date"
                    tickFormatter={(value) => {
                      const date = new Date(value);
                      return `${date.getDate()}/${date.getMonth() + 1}`;
                    }}
                  />
                  <YAxis domain={[0, 100]} tickFormatter={(value) => `${value}%`} />
                  <Tooltip
                    labelFormatter={(value) => {
                      const date = new Date(value as string);
                      return date.toLocaleDateString("fr-FR");
                    }}
                    formatter={(value: any) => [`${value.toFixed(1)}%`, "Taux de succès"]}
                  />
                  <Bar dataKey="tauxSucces" fill="#3b82f6" name="Taux de succès" />
                </RechartsBarChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        {/* Emails problématiques */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-orange-600" />
              Emails problématiques
            </CardTitle>
            <CardDescription>
              Top 10 des emails avec le plus d'échecs
            </CardDescription>
          </CardHeader>
          <CardContent>
            {statsLoading ? (
              <div className="text-center py-8 text-muted-foreground">
                Chargement...
              </div>
            ) : !stats?.emailsProblematiques || stats.emailsProblematiques.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                Aucun email problématique détecté
              </div>
            ) : (
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Email</TableHead>
                      <TableHead className="text-right">Nombre d'échecs</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {stats.emailsProblematiques.map((item, index) => (
                      <TableRow key={index}>
                        <TableCell className="font-medium">{item.email}</TableCell>
                        <TableCell className="text-right">
                          <span className="inline-flex items-center justify-center rounded-full bg-red-100 px-3 py-1 text-sm font-medium text-red-800">
                            {item.nbEchecs}
                          </span>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
