import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

type TimelineEntry = {
  label: string;
  salles: number;
  materiel: number;
};

type CategoryEntry = {
  name: string;
  value: number;
};

type RoomOccupancyEntry = {
  name: string;
  taux: number;
};

type MaterialUsageEntry = {
  name: string;
  quantite: number;
  demandes: number;
};

type AdminAnalyticsChartsProps = {
  periodLabel?: string | null;
  timelineData: TimelineEntry[];
  categoryData: CategoryEntry[];
  roomOccupancyData: RoomOccupancyEntry[];
  materialUsageData: MaterialUsageEntry[];
};

const COLORS = ["#000091", "#6a6af4", "#009081", "#e1000f", "#c9191e", "#b34000"];

export default function AdminAnalyticsCharts({
  periodLabel,
  timelineData,
  categoryData,
  roomOccupancyData,
  materialUsageData,
}: AdminAnalyticsChartsProps) {
  return (
    <>
      <div className="grid gap-6 xl:grid-cols-[1.15fr_0.85fr]">
        <Card>
          <CardHeader>
            <CardTitle>Répartition des réservations</CardTitle>
            <CardDescription>
              Vue {periodLabel?.toLowerCase() || "périodique"} des salles et du matériel.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[320px]">
              {timelineData.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={timelineData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="label" fontSize={12} />
                    <YAxis fontSize={12} />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="salles" name="Salles" fill="#000091" radius={[6, 6, 0, 0]} />
                    <Bar dataKey="materiel" name="Matériel" fill="#009081" radius={[6, 6, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
                  Pas encore de réservations sur cette période.
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Catégories d’utilisateurs</CardTitle>
            <CardDescription>
              Répartition par typologie d’associations et structures utilisatrices.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[320px]">
              {categoryData.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={categoryData}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      outerRadius={105}
                      dataKey="value"
                      label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    >
                      {categoryData.map((entry, index) => (
                        <Cell key={`${entry.name}-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
                  Catégorisation indisponible pour le moment.
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 xl:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Taux d’occupation des salles</CardTitle>
            <CardDescription>
              Lecture simple des espaces les plus mobilisés sur la période.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[320px]">
              {roomOccupancyData.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={roomOccupancyData} layout="vertical" margin={{ top: 8, right: 8, left: 24, bottom: 8 }}>
                    <CartesianGrid strokeDasharray="3 3" horizontal={false} />
                    <XAxis type="number" fontSize={12} unit="%" />
                    <YAxis dataKey="name" type="category" width={120} fontSize={12} />
                    <Tooltip formatter={(value: number, name: string) => [name === "taux" ? `${value}%` : value, name === "taux" ? "Occupation" : "Jours réservés"]} />
                    <Bar dataKey="taux" name="Occupation" fill="#6a6af4" radius={[0, 6, 6, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
                  Aucune occupation à afficher.
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Matériels les plus demandés</CardTitle>
            <CardDescription>
              Quantité totale demandée et nombre de dossiers concernés.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[320px]">
              {materialUsageData.length > 0 ? (
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={materialUsageData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" fontSize={12} />
                    <YAxis fontSize={12} />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="quantite" name="Quantité" fill="#000091" radius={[6, 6, 0, 0]} />
                    <Bar dataKey="demandes" name="Dossiers" fill="#f4b740" radius={[6, 6, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
                  Aucune demande matérielle à afficher.
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </>
  );
}
