"use client";

import { useEffect, useState } from "react";
import {
RefreshCw,
CalendarDays,
Clock,
CheckCircle,
XCircle,
CircleAlert,
Users,
} from "lucide-react";

type ReservationStatus =
| "PENDING"
| "CONFIRMED"
| "COMPLETED"
| "CANCELLED";

interface RestaurantTable {
id: string;
number: number;
seats: number;
}

interface Reservation {
id: string;
reservationNumber: string;
firstName: string;
lastName: string;
phone: string;
email?: string | null;
reservationDate: string;
reservationTime: string;
guests: number;
notes?: string | null;
status: ReservationStatus;
createdAt: string;
updatedAt: string;
table?: RestaurantTable | null;
}

function getStatusLabel(status: ReservationStatus) {
switch (status) {
case "PENDING":
return "En attente";

case "CONFIRMED":
  return "Confirmée";

case "COMPLETED":
  return "Terminée";

case "CANCELLED":
  return "Annulée";

default:
  return status;

}
}

function getStatusClass(status: ReservationStatus) {
switch (status) {
case "PENDING":
return "bg-yellow-100 text-yellow-700 border-yellow-200";

case "CONFIRMED":
  return "bg-blue-100 text-blue-700 border-blue-200";

case "COMPLETED":
  return "bg-green-100 text-green-700 border-green-200";

case "CANCELLED":
  return "bg-red-100 text-red-700 border-red-200";

default:
  return "bg-gray-100 text-gray-700 border-gray-200";

}
}

function getStatusIcon(status: ReservationStatus) {
switch (status) {
case "PENDING":
return <CircleAlert size={16} />;

case "CONFIRMED":
  return <CheckCircle size={16} />;

case "COMPLETED":
  return <CheckCircle size={16} />;

case "CANCELLED":
  return <XCircle size={16} />;

default:
  return <CircleAlert size={16} />;

}
}

function formatDate(date: string) {
return new Intl.DateTimeFormat("fr-FR", {
dateStyle: "long",
}).format(new Date(date));
}

function formatCreatedAt(date: string) {
return new Intl.DateTimeFormat("fr-FR", {
dateStyle: "short",
timeStyle: "short",
}).format(new Date(date));
}

export default function AdminReservationsPage() {
const [reservations, setReservations] = useState<Reservation[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [updatingReservationId, setUpdatingReservationId] =
useState<string | null>(null);

async function loadReservations() {
try {
setLoading(true);
setError("");

  const response = await fetch("/api/reservations", {
    cache: "no-store",
  });

  if (!response.ok) {
    throw new Error(
      "Erreur lors du chargement des réservations."
    );
  }

  const data = await response.json();

  if (!data.success) {
    throw new Error(
      data.message ||
        "Impossible de récupérer les réservations."
    );
  }

  setReservations(data.reservations || []);
} catch (error) {
  console.error(error);

  setError(
    error instanceof Error
      ? error.message
      : "Une erreur est survenue."
  );
} finally {
  setLoading(false);
}

}

async function updateReservationStatus(
reservationId: string,
status: ReservationStatus
) {
try {
setUpdatingReservationId(reservationId);

  const response = await fetch(
    `/api/reservations/${reservationId}`,
    {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        status,
      }),
    }
  );

  const data = await response.json();

  if (!response.ok || !data.success) {
    throw new Error(
      data.message ||
        "Impossible de modifier le statut."
    );
  }

  setReservations((currentReservations) =>
    currentReservations.map((reservation) =>
      reservation.id === reservationId
        ? {
            ...reservation,
            status: data.reservation.status,
            updatedAt:
              data.reservation.updatedAt ||
              reservation.updatedAt,
          }
        : reservation
    )
  );
} catch (error) {
  console.error(error);

  alert(
    error instanceof Error
      ? error.message
      : "Une erreur est survenue."
  );
} finally {
  setUpdatingReservationId(null);
}

}

useEffect(() => {
loadReservations();
}, []);

const total = reservations.length;

const pending = reservations.filter(
(reservation) =>
reservation.status === "PENDING"
).length;

const confirmed = reservations.filter(
(reservation) =>
reservation.status === "CONFIRMED"
).length;

const completed = reservations.filter(
(reservation) =>
reservation.status === "COMPLETED"
).length;

return ( <div className="mx-auto max-w-7xl space-y-8">
{/* HEADER */} <div className="flex flex-col justify-between gap-5 md:flex-row md:items-center"> <div> <p className="text-sm font-semibold uppercase tracking-[0.25em] text-[#a68b5b]">
Gestion </p>

      <h1 className="mt-2 text-3xl font-bold tracking-tight text-[#2f2a24]">
        Gestion des réservations
      </h1>

      <p className="mt-2 text-sm text-gray-500">
        Consultez et gérez les réservations du restaurant.
      </p>
    </div>

    <button
      type="button"
      onClick={loadReservations}
      disabled={loading}
      className="flex items-center justify-center gap-2 rounded-xl bg-[#2f2a24] px-5 py-3 text-sm font-semibold text-white transition hover:bg-[#4a4238] disabled:cursor-not-allowed disabled:opacity-50"
    >
      <RefreshCw
        size={17}
        className={loading ? "animate-spin" : ""}
      />

      Actualiser
    </button>
  </div>

  {/* STATISTIQUES */}
  <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-4">
    {/* TOTAL */}
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-500">
          Total réservations
        </p>

        <CalendarDays
          size={21}
          className="text-[#a68b5b]"
        />
      </div>

      <p className="mt-3 text-3xl font-bold text-[#2f2a24]">
        {total}
      </p>

      <p className="mt-2 text-xs text-[#a68b5b]">
        Toutes les réservations
      </p>
    </div>

    {/* EN ATTENTE */}
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-500">
          En attente
        </p>

        <CircleAlert
          size={21}
          className="text-yellow-500"
        />
      </div>

      <p className="mt-3 text-3xl font-bold text-yellow-600">
        {pending}
      </p>

      <p className="mt-2 text-xs text-gray-400">
        À confirmer
      </p>
    </div>

    {/* CONFIRMÉES */}
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-500">
          Confirmées
        </p>

        <CheckCircle
          size={21}
          className="text-blue-500"
        />
      </div>

      <p className="mt-3 text-3xl font-bold text-blue-600">
        {confirmed}
      </p>

      <p className="mt-2 text-xs text-gray-400">
        Réservations validées
      </p>
    </div>

    {/* TERMINÉES */}
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-500">
          Terminées
        </p>

        <CheckCircle
          size={21}
          className="text-green-500"
        />
      </div>

      <p className="mt-3 text-3xl font-bold text-green-600">
        {completed}
      </p>

      <p className="mt-2 text-xs text-gray-400">
        Réservations effectuées
      </p>
    </div>
  </div>

  {/* ERREUR */}
  {error && (
    <div className="rounded-2xl border border-red-100 bg-red-50 p-5 text-sm text-red-600">
      {error}
    </div>
  )}

  {/* CHARGEMENT */}
  {loading && (
    <div className="rounded-2xl border border-[#e8e1d6] bg-white p-12 text-center shadow-sm">
      <RefreshCw
        size={30}
        className="mx-auto animate-spin text-[#a68b5b]"
      />

      <p className="mt-4 text-sm text-gray-500">
        Chargement des réservations...
      </p>
    </div>
  )}

  {/* AUCUNE RÉSERVATION */}
  {!loading &&
    !error &&
    reservations.length === 0 && (
      <div className="rounded-2xl border border-[#e8e1d6] bg-white p-16 text-center shadow-sm">
        <CalendarDays
          size={50}
          className="mx-auto text-gray-300"
        />

        <h2 className="mt-5 text-2xl font-bold text-[#2f2a24]">
          Aucune réservation
        </h2>

        <p className="mt-2 text-sm text-gray-500">
          Les nouvelles réservations apparaîtront ici.
        </p>
      </div>
    )}

  {/* LISTE DES RÉSERVATIONS */}
  {!loading &&
    !error &&
    reservations.length > 0 && (
      <div className="space-y-5">
        {reservations.map((reservation) => (
          <article
            key={reservation.id}
            className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm transition hover:shadow-md"
          >
            {/* INFORMATIONS PRINCIPALES */}
            <div className="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
              {/* CLIENT */}
              <div>
                <div className="flex flex-wrap items-center gap-3">
                  <h2 className="text-lg font-semibold text-[#2f2a24]">
                    {reservation.reservationNumber}
                  </h2>

                  <span
                    className={`flex items-center gap-2 rounded-full border px-3 py-1 text-xs font-semibold ${getStatusClass(
                      reservation.status
                    )}`}
                  >
                    {getStatusIcon(
                      reservation.status
                    )}

                    {getStatusLabel(
                      reservation.status
                    )}
                  </span>
                </div>

                <p className="mt-3 font-semibold text-[#2f2a24]">
                  {reservation.firstName}{" "}
                  {reservation.lastName}
                </p>

                <p className="mt-1 text-sm text-gray-500">
                  {reservation.phone}
                </p>

                {reservation.email && (
                  <p className="mt-1 text-sm text-gray-500">
                    {reservation.email}
                  </p>
                )}
              </div>

              {/* DATE ET HEURE */}
              <div className="rounded-xl bg-[#f8f6f1] p-4 lg:min-w-[270px]">
                <div className="flex items-center gap-3">
                  <CalendarDays
                    size={19}
                    className="text-[#a68b5b]"
                  />

                  <div>
                    <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">
                      Date
                    </p>

                    <p className="mt-1 text-sm font-semibold text-[#2f2a24]">
                      {formatDate(
                        reservation.reservationDate
                      )}
                    </p>
                  </div>
                </div>

                <div className="mt-4 flex items-center gap-3">
                  <Clock
                    size={19}
                    className="text-[#a68b5b]"
                  />

                  <div>
                    <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">
                      Heure
                    </p>

                    <p className="mt-1 text-sm font-semibold text-[#2f2a24]">
                      {reservation.reservationTime}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* DÉTAILS */}
            <div className="mt-6 grid gap-5 border-t border-[#eee8df] pt-6 sm:grid-cols-2 lg:grid-cols-4">
              {/* PERSONNES */}
              <div>
                <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">
                  Nombre de personnes
                </p>

                <div className="mt-2 flex items-center gap-2 text-sm font-semibold text-[#2f2a24]">
                  <Users
                    size={18}
                    className="text-[#a68b5b]"
                  />

                  {reservation.guests} personne
                  {reservation.guests > 1
                    ? "s"
                    : ""}
                </div>
              </div>

              {/* TABLE */}
              <div>
                <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">
                  Table
                </p>

                <p className="mt-2 text-sm font-semibold text-[#2f2a24]">
                  {reservation.table
                    ? `Table ${reservation.table.number}`
                    : "Aucune table attribuée"}
                </p>

                {reservation.table && (
                  <p className="mt-1 text-xs text-gray-500">
                    {reservation.table.seats} places
                  </p>
                )}
              </div>

              {/* NOTES */}
              <div className="sm:col-span-2">
                <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">
                  Notes
                </p>

                <p className="mt-2 text-sm text-gray-600">
                  {reservation.notes ||
                    "Aucune note"}
                </p>
              </div>
            </div>

            {/* STATUT */}
            <div className="mt-6 flex flex-col gap-4 border-t border-[#eee8df] pt-6 sm:flex-row sm:items-end sm:justify-between">
              <div>
                <label
                  htmlFor={`status-${reservation.id}`}
                  className="mb-2 block text-xs font-semibold uppercase tracking-wider text-gray-400"
                >
                  Modifier le statut
                </label>

                <select
                  id={`status-${reservation.id}`}
                  value={reservation.status}
                  disabled={
                    updatingReservationId ===
                    reservation.id
                  }
                  onChange={(event) =>
                    updateReservationStatus(
                      reservation.id,
                      event.target
                        .value as ReservationStatus
                    )
                  }
                  className="w-full rounded-xl border border-[#e8e1d6] bg-white px-4 py-3 text-sm font-semibold text-[#2f2a24] outline-none transition focus:border-[#a68b5b] disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
                >
                  <option value="PENDING">
                    En attente
                  </option>

                  <option value="CONFIRMED">
                    Confirmée
                  </option>

                  <option value="COMPLETED">
                    Terminée
                  </option>

                  <option value="CANCELLED">
                    Annulée
                  </option>
                </select>
              </div>

              <div className="text-xs text-gray-400">
                Créée le{" "}
                {formatCreatedAt(
                  reservation.createdAt
                )}
              </div>
            </div>
          </article>
        ))}
      </div>
    )}
</div>

);
}