import Link from "next/link";
import { notFound } from "next/navigation";
import {
  ArrowLeft,
  CalendarDays,
  Mail,
  Phone,
  ShoppingBag,
  ClipboardList,
} from "lucide-react";
import { db } from "@/lib/db";

export default async function ClientDetailsPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  const client = await db.user.findUnique({
    where: {
      id,
    },
  });

  if (!client || client.role !== "CUSTOMER") {
    notFound();
  }

  const orders = await db.order.findMany({
    where: {
      OR: [
        {
          email: client.email,
        },
        {
          phone: client.phone || undefined,
        },
      ],
    },
    orderBy: {
      createdAt: "desc",
    },
    include: {
      items: true,
    },
  });

  const reservations = await db.reservation.findMany({
    where: {
      OR: [
        {
          email: client.email,
        },
        {
          phone: client.phone || undefined,
        },
      ],
    },
    orderBy: {
      createdAt: "desc",
    },
    include: {
      table: true,
    },
  });

  const totalSpent = orders
    .filter(
      (order) => order.status !== "CANCELLED"
    )
    .reduce(
      (total, order) => total + order.total,
      0
    );

  return (
    <div className="mx-auto max-w-7xl space-y-8">

      {/* RETOUR */}
      <Link
        href="/admin/clients"
        className="inline-flex items-center gap-2 text-sm font-semibold text-[#8d754e] transition hover:text-[#2f2a24]"
      >
        <ArrowLeft size={18} />
        Retour aux clients
      </Link>

      {/* HEADER CLIENT */}
      <div className="rounded-2xl border border-[#e8e1d6] bg-white p-7 shadow-sm">

        <div className="flex flex-col gap-6 md:flex-row md:items-center md:justify-between">

          <div className="flex items-center gap-5">

            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-[#d8c19a] text-xl font-bold text-white">
              {client.firstName.charAt(0)}
              {client.lastName.charAt(0)}
            </div>

            <div>
              <h1 className="text-2xl font-bold text-[#2f2a24]">
                {client.firstName}{" "}
                {client.lastName}
              </h1>

              <p className="mt-1 text-sm text-gray-500">
                Client Happy Hours
              </p>
            </div>

          </div>

          <span
            className={`inline-flex w-fit rounded-full px-4 py-2 text-xs font-semibold ${
              client.isActive
                ? "bg-green-100 text-green-700"
                : "bg-red-100 text-red-700"
            }`}
          >
            {client.isActive
              ? "Compte actif"
              : "Compte désactivé"}
          </span>

        </div>

      </div>

      {/* INFORMATIONS */}
      <div className="grid gap-6 lg:grid-cols-2">

        {/* CONTACT */}
        <div className="rounded-2xl border border-[#e8e1d6] bg-white p-7 shadow-sm">

          <h2 className="text-lg font-semibold">
            Informations personnelles
          </h2>

          <div className="mt-6 space-y-5">

            <div className="flex items-center gap-4">

              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b]">
                <Mail size={18} />
              </div>

              <div>
                <p className="text-xs text-gray-400">
                  Adresse e-mail
                </p>

                <p className="mt-1 text-sm font-medium">
                  {client.email}
                </p>
              </div>

            </div>

            <div className="flex items-center gap-4">

              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b]">
                <Phone size={18} />
              </div>

              <div>
                <p className="text-xs text-gray-400">
                  Téléphone
                </p>

                <p className="mt-1 text-sm font-medium">
                  {client.phone || "Non renseigné"}
                </p>
              </div>

            </div>

            <div className="flex items-center gap-4">

              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[#f5efe5] text-[#a68b5b]">
                <CalendarDays size={18} />
              </div>

              <div>
                <p className="text-xs text-gray-400">
                  Date d'inscription
                </p>

                <p className="mt-1 text-sm font-medium">
                  {new Intl.DateTimeFormat(
                    "fr-FR",
                    {
                      dateStyle: "long",
                    }
                  ).format(
                    new Date(client.createdAt)
                  )}
                </p>
              </div>

            </div>

          </div>

        </div>

        {/* STATISTIQUES */}
        <div className="rounded-2xl border border-[#e8e1d6] bg-white p-7 shadow-sm">

          <h2 className="text-lg font-semibold">
            Activité du client
          </h2>

          <div className="mt-6 grid gap-4 sm:grid-cols-3">

            <div className="rounded-xl bg-[#f8f6f1] p-5">

              <ShoppingBag
                size={20}
                className="text-[#a68b5b]"
              />

              <p className="mt-4 text-2xl font-bold">
                {orders.length}
              </p>

              <p className="mt-1 text-xs text-gray-500">
                Commandes
              </p>

            </div>

            <div className="rounded-xl bg-[#f8f6f1] p-5">

              <ClipboardList
                size={20}
                className="text-[#a68b5b]"
              />

              <p className="mt-4 text-2xl font-bold">
                {reservations.length}
              </p>

              <p className="mt-1 text-xs text-gray-500">
                Réservations
              </p>

            </div>

            <div className="rounded-xl bg-[#f8f6f1] p-5">

              <p className="text-sm text-gray-500">
                Total dépensé
              </p>

              <p className="mt-4 text-xl font-bold">
                {new Intl.NumberFormat(
                  "fr-FR"
                ).format(totalSpent)}{" "}
                FCFA
              </p>

              <p className="mt-1 text-xs text-gray-500">
                Hors commandes annulées
              </p>

            </div>

          </div>

        </div>

      </div>

      {/* COMMANDES */}
      <div className="rounded-2xl border border-[#e8e1d6] bg-white shadow-sm">

        <div className="border-b border-[#eee8df] p-6">

          <h2 className="text-lg font-semibold">
            Historique des commandes
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Commandes associées à ce client
          </p>

        </div>

        {orders.length === 0 ? (
          <div className="p-10 text-center text-sm text-gray-500">
            Aucune commande enregistrée.
          </div>
        ) : (
          <div className="overflow-x-auto">

            <table className="w-full min-w-[700px]">

              <thead>
                <tr className="border-b border-[#eee8df] bg-[#f8f6f1] text-left">

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Commande
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Type
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Total
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Statut
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Date
                  </th>

                </tr>
              </thead>

              <tbody>

                {orders.map((order) => (
                  <tr
                    key={order.id}
                    className="border-b border-[#eee8df] last:border-b-0"
                  >

                    <td className="px-6 py-5 text-sm font-semibold">
                      #{order.orderNumber}
                    </td>

                    <td className="px-6 py-5 text-sm text-gray-600">
                      {order.orderType ===
                      "DELIVERY"
                        ? "Livraison"
                        : "Restaurant"}
                    </td>

                    <td className="px-6 py-5 text-sm font-semibold">
                      {new Intl.NumberFormat(
                        "fr-FR"
                      ).format(order.total)}{" "}
                      FCFA
                    </td>

                    <td className="px-6 py-5">

                      <span className="rounded-full bg-[#f5efe5] px-3 py-1 text-xs font-semibold text-[#8d754e]">
                        {order.status}
                      </span>

                    </td>

                    <td className="px-6 py-5 text-sm text-gray-500">
                      {new Intl.DateTimeFormat(
                        "fr-FR"
                      ).format(
                        new Date(
                          order.createdAt
                        )
                      )}
                    </td>

                  </tr>
                ))}

              </tbody>

            </table>

          </div>
        )}

      </div>

      {/* RESERVATIONS */}
      <div className="rounded-2xl border border-[#e8e1d6] bg-white shadow-sm">

        <div className="border-b border-[#eee8df] p-6">

          <h2 className="text-lg font-semibold">
            Historique des réservations
          </h2>

          <p className="mt-1 text-sm text-gray-500">
            Réservations associées à ce client
          </p>

        </div>

        {reservations.length === 0 ? (
          <div className="p-10 text-center text-sm text-gray-500">
            Aucune réservation enregistrée.
          </div>
        ) : (
          <div className="overflow-x-auto">

            <table className="w-full min-w-[700px]">

              <thead>
                <tr className="border-b border-[#eee8df] bg-[#f8f6f1] text-left">

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Réservation
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Date
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Heure
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Convives
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Table
                  </th>

                  <th className="px-6 py-4 text-xs font-semibold uppercase tracking-wider text-gray-500">
                    Statut
                  </th>

                </tr>
              </thead>

              <tbody>

                {reservations.map(
                  (reservation) => (
                    <tr
                      key={reservation.id}
                      className="border-b border-[#eee8df] last:border-b-0"
                    >

                      <td className="px-6 py-5 text-sm font-semibold">
                        #
                        {
                          reservation.reservationNumber
                        }
                      </td>

                      <td className="px-6 py-5 text-sm text-gray-600">
                        {new Intl.DateTimeFormat(
                          "fr-FR"
                        ).format(
                          new Date(
                            reservation.reservationDate
                          )
                        )}
                      </td>

                      <td className="px-6 py-5 text-sm text-gray-600">
                        {
                          reservation.reservationTime
                        }
                      </td>

                      <td className="px-6 py-5 text-sm text-gray-600">
                        {reservation.guests}
                      </td>

                      <td className="px-6 py-5 text-sm text-gray-600">
                        {reservation.table
                          ? `Table ${reservation.table.number}`
                          : "Non attribuée"}
                      </td>

                      <td className="px-6 py-5">

                        <span className="rounded-full bg-[#f5efe5] px-3 py-1 text-xs font-semibold text-[#8d754e]">
                          {
                            reservation.status
                          }
                        </span>

                      </td>

                    </tr>
                  )
                )}

              </tbody>

            </table>

          </div>
        )}

      </div>

    </div>
  );
}