import {
ArrowDownRight,
ArrowUpRight,
BarChart3,
CalendarDays,
CheckCircle2,
CreditCard,
ShoppingBag,
Users,
XCircle,
} from "lucide-react";

import { db } from "@/lib/db";

function formatPrice(value: number) {
return new Intl.NumberFormat("fr-FR").format(Math.round(value));
}

function formatNumber(value: number) {
return new Intl.NumberFormat("fr-FR").format(value);
}

function getStartOfDay() {
const date = new Date();
date.setHours(0, 0, 0, 0);
return date;
}

function getStartOfMonth() {
const date = new Date();
date.setDate(1);
date.setHours(0, 0, 0, 0);
return date;
}

export default async function StatistiquesPage() {
const startOfDay = getStartOfDay();
const startOfMonth = getStartOfMonth();

const [
ordersCount,
todayOrdersCount,
monthOrdersCount,
cancelledOrdersCount,
confirmedOrdersCount,
totalRevenueResult,
todayRevenueResult,
monthRevenueResult,
usersCount,
reservationsCount,
todayReservationsCount,
averageOrderResult,
paymentMethods,
orderTypes,
topProducts,
] = await Promise.all([
// TOTAL COMMANDES
db.order.count(),

// COMMANDES DU JOUR
db.order.count({
  where: {
    createdAt: {
      gte: startOfDay,
    },
  },
}),

// COMMANDES DU MOIS
db.order.count({
  where: {
    createdAt: {
      gte: startOfMonth,
    },
  },
}),

// COMMANDES ANNULÉES
db.order.count({
  where: {
    status: "CANCELLED",
  },
}),

// COMMANDES CONFIRMÉES
db.order.count({
  where: {
    status: {
      not: "CANCELLED",
    },
  },
}),

// CA TOTAL
db.order.aggregate({
  _sum: {
    total: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
  },
}),

// CA DU JOUR
db.order.aggregate({
  _sum: {
    total: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
    createdAt: {
      gte: startOfDay,
    },
  },
}),

// CA DU MOIS
db.order.aggregate({
  _sum: {
    total: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
    createdAt: {
      gte: startOfMonth,
    },
  },
}),

// CLIENTS
db.user.count({
  where: {
    role: "CUSTOMER",
  },
}),

// RÉSERVATIONS
db.reservation.count(),

// RÉSERVATIONS DU JOUR
db.reservation.count({
  where: {
    reservationDate: {
      gte: startOfDay,
    },
  },
}),

// PANIER MOYEN
db.order.aggregate({
  _avg: {
    total: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
  },
}),

// MODES DE PAIEMENT
db.order.groupBy({
  by: ["paymentMethod"],
  _count: {
    id: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
  },
  orderBy: {
    _count: {
      id: "desc",
    },
  },
}),

// TYPES DE COMMANDES
db.order.groupBy({
  by: ["orderType"],
  _count: {
    id: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
  },
  orderBy: {
    _count: {
      id: "desc",
    },
  },
}),

// PRODUITS LES PLUS COMMANDÉS
db.orderItems.groupBy({
  by: ["productId", "productName"],
  _sum: {
    quantity: true,
  },
  _count: {
    id: true,
  },
  orderBy: {
    _sum: {
      quantity: "desc",
    },
  },
  take: 5,
}),

]);

const totalRevenue = totalRevenueResult._sum.total ?? 0;
const todayRevenue = todayRevenueResult._sum.total ?? 0;
const monthRevenue = monthRevenueResult._sum.total ?? 0;

const averageOrder = averageOrderResult._avg.total ?? 0;

const cancellationRate =
ordersCount > 0
? Math.round((cancelledOrdersCount / ordersCount) * 100)
: 0;

const paymentLabels: Record<string, string> = {
CASH: "Espèces",
WAVE: "Wave",
ORANGE_MONEY: "Orange Money",
MTN_MONEY: "MTN Money",
};

const orderTypeLabels: Record<string, string> = {
RESTAURANT: "Sur place",
DELIVERY: "Livraison",
TAKEAWAY: "À emporter",
};

return ( <div className="mx-auto max-w-[1440px] space-y-8">
{/* HEADER */} <section> <div> <p className="text-[10px] font-bold uppercase tracking-[0.25em] text-[#a68b5b]">
Analyse & performance </p>

      <h1 className="mt-2 font-serif text-3xl font-semibold tracking-tight text-[#2f2a24] md:text-4xl">
        Statistiques
      </h1>

      <p className="mt-2 max-w-2xl text-sm leading-6 text-gray-500">
        Analysez l'activité de Happy Hours, suivez les performances
        commerciales et identifiez les tendances de votre restaurant.
      </p>
    </div>
  </section>

  {/* INDICATEURS PRINCIPAUX */}
  <section>
    <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-4">
      <StatCard
        title="Chiffre d'affaires total"
        value={`${formatPrice(totalRevenue)} FCFA`}
        description="Commandes non annulées"
        icon={<BarChart3 size={21} />}
      />

      <StatCard
        title="Chiffre d'affaires du mois"
        value={`${formatPrice(monthRevenue)} FCFA`}
        description={`${formatNumber(monthOrdersCount)} commandes ce mois`}
        icon={<CreditCard size={21} />}
      />

      <StatCard
        title="Commandes"
        value={formatNumber(ordersCount)}
        description={`${formatNumber(todayOrdersCount)} aujourd'hui`}
        icon={<ShoppingBag size={21} />}
      />

      <StatCard
        title="Clients"
        value={formatNumber(usersCount)}
        description="Clients enregistrés"
        icon={<Users size={21} />}
      />
    </div>
  </section>

  {/* PERFORMANCE DU JOUR */}
  <section>
    <div className="grid gap-5 md:grid-cols-3">
      <PerformanceCard
        title="CA aujourd'hui"
        value={`${formatPrice(todayRevenue)} FCFA`}
        description={`${formatNumber(todayOrdersCount)} commande(s)`}
        icon={<ArrowUpRight size={20} />}
      />

      <PerformanceCard
        title="Panier moyen"
        value={`${formatPrice(averageOrder)} FCFA`}
        description="Montant moyen par commande"
        icon={<CreditCard size={20} />}
      />

      <PerformanceCard
        title="Réservations"
        value={formatNumber(reservationsCount)}
        description={`${formatNumber(todayReservationsCount)} aujourd'hui`}
        icon={<CalendarDays size={20} />}
      />
    </div>
  </section>

  {/* ACTIVITÉ GLOBALE */}
  <section className="grid gap-6 lg:grid-cols-2">
    {/* COMMANDES */}
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-[#2f2a24]">
            Activité des commandes
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Vue globale de l'activité commerciale
          </p>
        </div>

        <ShoppingBag
          size={21}
          className="text-[#a68b5b]"
        />
      </div>

      <div className="mt-6 space-y-3">
        <ActivityRow
          label="Total des commandes"
          value={ordersCount}
        />

        <ActivityRow
          label="Commandes non annulées"
          value={confirmedOrdersCount}
        />

        <ActivityRow
          label="Commandes annulées"
          value={cancelledOrdersCount}
        />

        <div className="mt-4 rounded-xl bg-[#f8f6f1] p-4">
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-500">
              Taux d'annulation
            </span>

            <span className="font-bold text-[#2f2a24]">
              {cancellationRate}%
            </span>
          </div>

          <div className="mt-3 h-2 overflow-hidden rounded-full bg-[#eee8df]">
            <div
              className="h-full rounded-full bg-[#b8863b]"
              style={{
                width: `${cancellationRate}%`,
              }}
            />
          </div>
        </div>
      </div>
    </div>

    {/* PAIEMENTS */}
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-[#2f2a24]">
            Modes de paiement
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Répartition des commandes par moyen de paiement
          </p>
        </div>

        <CreditCard
          size={21}
          className="text-[#a68b5b]"
        />
      </div>

      <div className="mt-6 space-y-4">
        {paymentMethods.length === 0 ? (
          <EmptyState message="Aucune donnée disponible." />
        ) : (
          paymentMethods.map((payment) => {
            const count = payment._count.id;

            const percentage =
              confirmedOrdersCount > 0
                ? Math.round(
                    (count / confirmedOrdersCount) * 100
                  )
                : 0;

            return (
              <div key={payment.paymentMethod}>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-[#2f2a24]">
                    {paymentLabels[payment.paymentMethod] ??
                      payment.paymentMethod}
                  </span>

                  <span className="text-sm font-semibold text-[#8d754e]">
                    {count} ({percentage}%)
                  </span>
                </div>

                <div className="mt-2 h-2 overflow-hidden rounded-full bg-[#eee8df]">
                  <div
                    className="h-full rounded-full bg-[#b8863b]"
                    style={{
                      width: `${percentage}%`,
                    }}
                  />
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  </section>

  {/* TYPES DE COMMANDES */}
  <section>
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div>
        <h2 className="text-lg font-semibold text-[#2f2a24]">
          Répartition des commandes
        </h2>

        <p className="mt-1 text-sm text-gray-500">
          Origine des commandes enregistrées
        </p>
      </div>

      <div className="mt-6 grid gap-4 md:grid-cols-3">
        {orderTypes.length === 0 ? (
          <EmptyState message="Aucune donnée disponible." />
        ) : (
          orderTypes.map((type) => (
            <div
              key={type.orderType}
              className="rounded-xl border border-[#eee8df] bg-[#faf9f6] p-5"
            >
              <p className="text-sm font-medium text-gray-500">
                {orderTypeLabels[type.orderType] ??
                  type.orderType}
              </p>

              <p className="mt-2 text-2xl font-bold text-[#2f2a24]">
                {formatNumber(type._count.id)}
              </p>

              <p className="mt-1 text-xs text-gray-400">
                commande(s)
              </p>
            </div>
          ))
        )}
      </div>
    </div>
  </section>

  {/* PRODUITS LES PLUS VENDUS */}
  <section>
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-[#2f2a24]">
            Produits les plus commandés
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Les 5 produits ayant généré le plus de ventes en quantité
          </p>
        </div>

        <BarChart3
          size={21}
          className="text-[#a68b5b]"
        />
      </div>

      <div className="mt-6 space-y-3">
        {topProducts.length === 0 ? (
          <EmptyState message="Aucun produit vendu pour le moment." />
        ) : (
          topProducts.map((product, index) => (
            <div
              key={`${product.productId}-${product.productName}`}
              className="flex items-center gap-4 rounded-xl border border-[#eee8df] p-4"
            >
              <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#f5efe5] text-sm font-bold text-[#a68b5b]">
                {index + 1}
              </div>

              <div className="min-w-0 flex-1">
                <p className="truncate font-semibold text-[#2f2a24]">
                  {product.productName}
                </p>

                <p className="mt-1 text-xs text-gray-500">
                  {product._count.id} ligne(s) de commande
                </p>
              </div>

              <div className="text-right">
                <p className="font-bold text-[#b8863b]">
                  {product._sum.quantity ?? 0}
                </p>

                <p className="text-[10px] text-gray-400">
                  vendu(s)
                </p>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  </section>

  {/* RÉSUMÉ */}
  <section>
    <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
      <SummaryCard
        title="Commandes ce mois"
        value={monthOrdersCount}
        icon={<ShoppingBag size={20} />}
      />

      <SummaryCard
        title="Réservations"
        value={reservationsCount}
        icon={<CalendarDays size={20} />}
      />

      <SummaryCard
        title="Clients"
        value={usersCount}
        icon={<Users size={20} />}
      />

      <SummaryCard
        title="Commandes annulées"
        value={cancelledOrdersCount}
        icon={<XCircle size={20} />}
      />
    </div>
  </section>
</div>

);
}

function StatCard({
title,
value,
description,
icon,
}: {
title: string;
value: string;
description: string;
icon: React.ReactNode;
}) {
return ( <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm"> <div className="flex items-start justify-between"> <div> <p className="text-sm font-medium text-gray-500">
{title} </p>

      <p className="mt-3 text-2xl font-bold tracking-tight text-[#2f2a24]">
        {value}
      </p>

      <p className="mt-2 text-xs text-gray-400">
        {description}
      </p>
    </div>

    <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b]">
      {icon}
    </div>
  </div>
</div>

);
}

function PerformanceCard({
title,
value,
description,
icon,
}: {
title: string;
value: string;
description: string;
icon: React.ReactNode;
}) {
return ( <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm"> <div className="flex items-center justify-between"> <div> <p className="text-xs font-bold uppercase tracking-[0.15em] text-[#a68b5b]">
{title} </p>

      <p className="mt-3 text-2xl font-bold text-[#2f2a24]">
        {value}
      </p>

      <p className="mt-1 text-sm text-gray-500">
        {description}
      </p>
    </div>

    <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[#f5efe5] text-[#b8863b]">
      {icon}
    </div>
  </div>
</div>

);
}

function ActivityRow({
label,
value,
}: {
label: string;
value: number;
}) {
return ( <div className="flex items-center justify-between rounded-xl border border-[#eee8df] p-4"> <span className="text-sm font-medium text-gray-600">
{label} </span>

  <span className="text-lg font-bold text-[#2f2a24]">
    {formatNumber(value)}
  </span>
</div>

);
}

function SummaryCard({
title,
value,
icon,
}: {
title: string;
value: number;
icon: React.ReactNode;
}) {
return ( <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b]">
{icon} </div>

  <p className="mt-5 text-sm font-medium text-gray-500">
    {title}
  </p>

  <p className="mt-2 text-2xl font-bold text-[#2f2a24]">
    {formatNumber(value)}
  </p>
</div>

);
}

function EmptyState({
message,
}: {
message: string;
}) {
return ( <div className="rounded-xl border border-dashed border-[#e8e1d6] p-8 text-center"> <p className="text-sm text-gray-500">
{message} </p> </div>
);
}
