import Link from "next/link";
import {
ArrowRight,
BarChart3,
CalendarDays,
CheckCircle2,
ClipboardList,
Clock3,
Package,
ShoppingBag,
Table2,
Users,
Utensils,
XCircle,
} from "lucide-react";

import { db } from "@/lib/db";

function formatPrice(value: number) {
return new Intl.NumberFormat("fr-FR").format(value);
}

function formatDate(date: Date | string) {
return new Intl.DateTimeFormat("fr-FR", {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(new Date(date));
}

export default async function DashboardPage() {
const [
ordersCount,
pendingOrdersCount,
confirmedOrdersCount,
preparingOrdersCount,
reservationsCount,
pendingReservationsCount,
confirmedReservationsCount,
usersCount,
productsCount,
availableProductsCount,
categoriesCount,
tablesCount,
availableTablesCount,
occupiedTablesCount,
reservedTablesCount,
recentOrders,
recentReservations,
revenueResult,
todayRevenueResult,
] = await Promise.all([
db.order.count(),

db.order.count({
  where: {
    status: "PENDING",
  },
}),

db.order.count({
  where: {
    status: "CONFIRMED",
  },
}),

db.order.count({
  where: {
    status: "PREPARING",
  },
}),

db.reservation.count(),

db.reservation.count({
  where: {
    status: "PENDING",
  },
}),

db.reservation.count({
  where: {
    status: "CONFIRMED",
  },
}),

db.user.count(),

db.product.count(),

db.product.count({
  where: {
    isAvailable: true,
  },
}),

db.category.count(),

db.restauranttable.count(),

db.restauranttable.count({
  where: {
    status: "AVAILABLE",
  },
}),

db.restauranttable.count({
  where: {
    status: "OCCUPIED",
  },
}),

db.restauranttable.count({
  where: {
    status: "RESERVED",
  },
}),

db.order.findMany({
  orderBy: {
    createdAt: "desc",
  },
  take: 5,
  select: {
    id: true,
    orderNumber: true,
    firstName: true,
    lastName: true,
    total: true,
    status: true,
    createdAt: true,
  },
}),

db.reservation.findMany({
  orderBy: {
    createdAt: "desc",
  },
  take: 5,
  select: {
    id: true,
    reservationNumber: true,
    firstName: true,
    lastName: true,
    reservationDate: true,
    reservationTime: true,
    guests: true,
    status: true,
  },
}),

db.order.aggregate({
  _sum: {
    total: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
  },
}),

db.order.aggregate({
  _sum: {
    total: true,
  },
  where: {
    status: {
      not: "CANCELLED",
    },
    createdAt: {
      gte: new Date(
        new Date().setHours(0, 0, 0, 0)
      ),
      lt: new Date(
        new Date().setHours(23, 59, 59, 999)
      ),
    },
  },
}),

]);

const totalRevenue = revenueResult._sum.total ?? 0;

const todayRevenue =
todayRevenueResult._sum.total ?? 0;

const unavailableProductsCount =
productsCount - availableProductsCount;

const occupancyRate =
tablesCount > 0
? Math.round(
(occupiedTablesCount / tablesCount) * 100
)
: 0;

const stats = [
{
label: "Chiffre d'affaires",
value: `${formatPrice(totalRevenue)} FCFA`,
description: "Commandes non annulées",
icon: BarChart3,
href: "/admin/commandes",
},
{
label: "Commandes",
value: ordersCount,
description: `${pendingOrdersCount} en attente`,
icon: ShoppingBag,
href: "/admin/commandes",
},
{
label: "Réservations",
value: reservationsCount,
description: `${pendingReservationsCount} en attente`,
icon: CalendarDays,
href: "/admin/reservations",
},
{
label: "Utilisateurs",
value: usersCount,
description: "Comptes enregistrés",
icon: Users,
href: "/admin/clients",
},
];

return ( <div className="mx-auto max-w-[1440px] space-y-8">
{/* HEADER */} <section> <div className="flex flex-col justify-between gap-5 sm:flex-row sm:items-end"> <div> <p className="text-[10px] font-bold uppercase tracking-[0.25em] text-[#a68b5b]">
Vue d'ensemble </p>

        <h1 className="mt-2 font-serif text-3xl font-semibold tracking-tight text-[#2f2a24] md:text-4xl">
          Tableau de bord
        </h1>

        <p className="mt-2 max-w-2xl text-sm leading-6 text-gray-500">
          Suivez l'activité de Happy Hours,
          consultez les performances du restaurant
          et accédez rapidement aux principales
          fonctionnalités de gestion.
        </p>
      </div>

      <Link
        href="/admin/menu"
        className="inline-flex items-center justify-center gap-2 rounded-full bg-[#b8863b] px-5 py-3 text-sm font-semibold text-white shadow-sm transition hover:bg-[#9f7332] hover:shadow-md"
      >
        <Utensils size={16} />
        Voir le menu
      </Link>
    </div>
  </section>

  {/* STATISTIQUES PRINCIPALES */}
  <section>
    <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-4">
      {stats.map((stat) => {
        const Icon = stat.icon;

        return (
          <Link
            key={stat.label}
            href={stat.href}
            className="group rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm transition-all duration-200 hover:-translate-y-0.5 hover:border-[#d8c19a] hover:shadow-md"
          >
            <div className="flex items-start justify-between gap-4">
              <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b] transition-colors group-hover:bg-[#b8863b] group-hover:text-white">
                <Icon size={20} strokeWidth={1.8} />
              </div>

              <ArrowRight
                size={17}
                className="text-gray-300 transition-all group-hover:translate-x-1 group-hover:text-[#b8863b]"
              />
            </div>

            <div className="mt-6">
              <p className="text-sm font-medium text-gray-500">
                {stat.label}
              </p>

              <p className="mt-2 text-2xl font-bold tracking-tight text-[#2f2a24]">
                {stat.value}
              </p>

              <p className="mt-2 text-xs text-gray-400">
                {stat.description}
              </p>
            </div>
          </Link>
        );
      })}
    </div>
  </section>

  {/* CHIFFRE D'AFFAIRES DU JOUR */}
  <section>
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex flex-col justify-between gap-5 sm:flex-row sm:items-center">
        <div>
          <p className="text-xs font-bold uppercase tracking-[0.2em] text-[#a68b5b]">
            Performance
          </p>

          <h2 className="mt-2 text-xl font-bold text-[#2f2a24]">
            Chiffre d'affaires du jour
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Total des commandes enregistrées aujourd'hui,
            hors commandes annulées.
          </p>
        </div>

        <div className="text-left sm:text-right">
          <p className="text-3xl font-bold text-[#b8863b]">
            {formatPrice(todayRevenue)} FCFA
          </p>

          <Link
            href="/admin/commandes"
            className="mt-2 inline-flex items-center gap-1 text-xs font-semibold text-[#8d754e] hover:text-[#b8863b]"
          >
            Voir les commandes
            <ArrowRight size={13} />
          </Link>
        </div>
      </div>
    </div>
  </section>

  {/* ACTIVITÉ */}
  <section className="grid gap-6 xl:grid-cols-3">
    {/* 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]">
            Commandes
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            État actuel des commandes
          </p>
        </div>

        <ShoppingBag
          size={21}
          className="text-[#a68b5b]"
        />
      </div>

      <div className="mt-6 space-y-3">
        <StatusRow
          label="En attente"
          value={pendingOrdersCount}
          icon={<Clock3 size={16} />}
        />

        <StatusRow
          label="Confirmées"
          value={confirmedOrdersCount}
          icon={<CheckCircle2 size={16} />}
        />

        <StatusRow
          label="En préparation"
          value={preparingOrdersCount}
          icon={<Utensils size={16} />}
        />
      </div>

      <Link
        href="/admin/commandes"
        className="mt-6 inline-flex items-center gap-2 text-sm font-semibold text-[#8d754e] hover:text-[#b8863b]"
      >
        Gérer les commandes
        <ArrowRight size={15} />
      </Link>
    </div>

    {/* RÉSERVATIONS */}
    <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]">
            Réservations
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            État actuel des réservations
          </p>
        </div>

        <CalendarDays
          size={21}
          className="text-[#a68b5b]"
        />
      </div>

      <div className="mt-6 space-y-3">
        <StatusRow
          label="En attente"
          value={pendingReservationsCount}
          icon={<Clock3 size={16} />}
        />

        <StatusRow
          label="Confirmées"
          value={confirmedReservationsCount}
          icon={<CheckCircle2 size={16} />}
        />

        <StatusRow
          label="Total"
          value={reservationsCount}
          icon={<CalendarDays size={16} />}
        />
      </div>

      <Link
        href="/admin/reservations"
        className="mt-6 inline-flex items-center gap-2 text-sm font-semibold text-[#8d754e] hover:text-[#b8863b]"
      >
        Gérer les réservations
        <ArrowRight size={15} />
      </Link>
    </div>

    {/* TABLES */}
    <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]">
            État des tables
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Occupation actuelle
          </p>
        </div>

        <Table2
          size={21}
          className="text-[#a68b5b]"
        />
      </div>

      <div className="mt-6">
        <div className="flex items-center justify-between">
          <span className="text-sm text-gray-500">
            Taux d'occupation
          </span>

          <span className="text-xl font-bold text-[#b8863b]">
            {occupancyRate}%
          </span>
        </div>

        <div className="mt-3 h-2 overflow-hidden rounded-full bg-[#eee8df]">
          <div
            className="h-full rounded-full bg-[#b8863b]"
            style={{
              width: `${occupancyRate}%`,
            }}
          />
        </div>
      </div>

      <div className="mt-6 grid grid-cols-3 gap-2">
        <MiniStat
          label="Libres"
          value={availableTablesCount}
          className="text-green-700"
        />

        <MiniStat
          label="Occupées"
          value={occupiedTablesCount}
          className="text-red-700"
        />

        <MiniStat
          label="Réservées"
          value={reservedTablesCount}
          className="text-orange-700"
        />
      </div>

      <Link
        href="/admin/tables"
        className="mt-6 inline-flex items-center gap-2 text-sm font-semibold text-[#8d754e] hover:text-[#b8863b]"
      >
        Gérer les tables
        <ArrowRight size={15} />
      </Link>
    </div>
  </section>

  {/* DERNIÈRES ACTIVITÉS */}
  <section className="grid gap-6 xl:grid-cols-2">
    {/* DERNIÈRES 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]">
            Dernières commandes
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Les 5 dernières commandes enregistrées
          </p>
        </div>

        <Link
          href="/admin/commandes"
          className="text-xs font-semibold text-[#8d754e]"
        >
          Voir tout
        </Link>
      </div>

      <div className="mt-6 space-y-3">
        {recentOrders.length === 0 ? (
          <EmptyState message="Aucune commande enregistrée." />
        ) : (
          recentOrders.map((order) => (
            <div
              key={order.id}
              className="flex items-center justify-between gap-4 rounded-xl border border-[#eee8df] p-4"
            >
              <div className="min-w-0">
                <p className="font-semibold text-[#2f2a24]">
                  #{order.orderNumber}
                </p>

                <p className="mt-1 truncate text-xs text-gray-500">
                  {order.firstName} {order.lastName}
                </p>

                <p className="mt-1 text-[11px] text-gray-400">
                  {formatDate(order.createdAt)}
                </p>
              </div>

              <div className="text-right">
                <p className="font-bold text-[#a68b5b]">
                  {formatPrice(order.total)} FCFA
                </p>

                <span className="mt-1 inline-block rounded-full bg-[#f5efe5] px-2 py-1 text-[10px] font-semibold text-[#8d754e]">
                  {order.status}
                </span>
              </div>
            </div>
          ))
        )}
      </div>
    </div>

    {/* DERNIÈRES RÉSERVATIONS */}
    <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]">
            Dernières réservations
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Les 5 dernières réservations enregistrées
          </p>
        </div>

        <Link
          href="/admin/reservations"
          className="text-xs font-semibold text-[#8d754e]"
        >
          Voir tout
        </Link>
      </div>

      <div className="mt-6 space-y-3">
        {recentReservations.length === 0 ? (
          <EmptyState message="Aucune réservation enregistrée." />
        ) : (
          recentReservations.map((reservation) => (
            <div
              key={reservation.id}
              className="flex items-center justify-between gap-4 rounded-xl border border-[#eee8df] p-4"
            >
              <div className="min-w-0">
                <p className="font-semibold text-[#2f2a24]">
                  #{reservation.reservationNumber}
                </p>

                <p className="mt-1 truncate text-xs text-gray-500">
                  {reservation.firstName}{" "}
                  {reservation.lastName}
                </p>

                <p className="mt-1 text-[11px] text-gray-400">
                  {new Intl.DateTimeFormat("fr-FR").format(
                    new Date(
                      reservation.reservationDate
                    )
                  )}{" "}
                  à {reservation.reservationTime} —{" "}
                  {reservation.guests} personne
                  {reservation.guests > 1 ? "s" : ""}
                </p>
              </div>

              <span className="whitespace-nowrap rounded-full bg-[#f5efe5] px-2 py-1 text-[10px] font-semibold text-[#8d754e]">
                {reservation.status}
              </span>
            </div>
          ))
        )}
      </div>
    </div>
  </section>

  {/* RÉSUMÉ DU MENU */}
  <section>
    <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
      <SummaryCard
        title="Produits"
        value={productsCount}
        description={`${availableProductsCount} disponibles`}
        icon={<Package size={20} />}
        href="/admin/menu"
      />

      <SummaryCard
        title="Indisponibles"
        value={unavailableProductsCount}
        description="Produits à vérifier"
        icon={<XCircle size={20} />}
        href="/admin/menu"
      />

      <SummaryCard
        title="Catégories"
        value={categoriesCount}
        description="Catégories du menu"
        icon={<ClipboardList size={20} />}
        href="/admin/menu"
      />

      <SummaryCard
        title="Tables"
        value={tablesCount}
        description={`${availableTablesCount} actuellement libres`}
        icon={<Table2 size={20} />}
        href="/admin/tables"
      />
    </div>
  </section>

  {/* ACCÈS RAPIDES */}
  <section>
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b]">
          <BarChart3 size={19} />
        </div>

        <div>
          <h2 className="text-lg font-semibold text-[#2f2a24]">
            Accès rapides
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Actions fréquentes de l'administration
          </p>
        </div>
      </div>

      <div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <QuickLink
          href="/admin/menu"
          icon={<Utensils size={18} />}
          title="Gérer le menu"
          description="Produits et catégories"
        />

        <QuickLink
          href="/admin/commandes"
          icon={<ShoppingBag size={18} />}
          title="Gérer les commandes"
          description="Suivre les commandes"
        />

        <QuickLink
          href="/admin/reservations"
          icon={<CalendarDays size={18} />}
          title="Gérer les réservations"
          description="Consulter les réservations"
        />

        <QuickLink
          href="/admin/tables"
          icon={<Table2 size={18} />}
          title="Gérer les tables"
          description="Disponibilité et occupation"
        />
      </div>
    </div>
  </section>
</div>

);
}

function StatusRow({
label,
value,
icon,
}: {
label: string;
value: number;
icon: React.ReactNode;
}) {
return ( <div className="flex items-center justify-between rounded-xl border border-[#eee8df] p-4"> <div className="flex items-center gap-3"> <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-[#f5efe5] text-[#a68b5b]">
{icon} </div>

    <span className="text-sm font-medium text-gray-600">
      {label}
    </span>
  </div>

  <span className="text-lg font-bold text-[#2f2a24]">
    {value}
  </span>
</div>

);
}

function MiniStat({
label,
value,
className,
}: {
label: string;
value: number;
className: string;
}) {
return ( <div className="rounded-xl bg-[#f8f6f1] p-3 text-center">
<p className={`text-xl font-bold ${className}`}>
{value} </p>

  <p className="mt-1 text-[10px] font-medium text-gray-500">
    {label}
  </p>
</div>

);
}

function SummaryCard({
title,
value,
description,
icon,
href,
}: {
title: string;
value: number;
description: string;
icon: React.ReactNode;
href: string;
}) {
return ( <Link
   href={href}
   className="group rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm transition hover:-translate-y-0.5 hover:border-[#d8c19a] hover:shadow-md"
 > <div className="flex items-center justify-between"> <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b] transition group-hover:bg-[#b8863b] group-hover:text-white">
{icon} </div>

    <ArrowRight
      size={18}
      className="text-gray-300 transition group-hover:translate-x-1 group-hover:text-[#b8863b]"
    />
  </div>

  <p className="mt-5 text-sm font-medium text-gray-500">
    {title}
  </p>

  <p className="mt-1 text-2xl font-bold text-[#2f2a24]">
    {value}
  </p>

  <p className="mt-1 text-xs text-gray-400">
    {description}
  </p>
</Link>

);
}

function QuickLink({
href,
icon,
title,
description,
}: {
href: string;
icon: React.ReactNode;
title: string;
description: string;
}) {
return ( <Link
   href={href}
   className="group flex items-center gap-4 rounded-xl border border-[#eee8df] bg-white p-4 transition-all duration-200 hover:border-[#d8c19a] hover:bg-[#f8f6f1]"
 > <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b] transition-colors group-hover:bg-[#b8863b] group-hover:text-white">
{icon} </div>

  <div className="min-w-0 flex-1">
    <p className="font-semibold text-[#2f2a24]">
      {title}
    </p>

    <p className="mt-1 text-xs text-gray-500">
      {description}
    </p>
  </div>

  <ArrowRight
    size={16}
    className="shrink-0 text-gray-300 transition-all group-hover:translate-x-1 group-hover:text-[#b8863b]"
  />
</Link>

);
}

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>
);
}
