"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

interface Booking {
  id: string;
  guest_name: string;
  guest_email: string;
  check_in: string;
  check_out: string;
  nights: number;
  total_usd: number;
  status: string;
  created_at: string;
}

const STATUS_STYLES: Record<string, string> = {
  confirmed: "bg-green-100 text-green-800",
  pending: "bg-yellow-100 text-yellow-800",
  cancelled: "bg-red-100 text-red-700",
};

export default function AdminDashboard() {
  const [bookings, setBookings] = useState<Booking[] | null>(null);
  const [error, setError] = useState("");
  const router = useRouter();

  async function load() {
    const res = await fetch("/api/admin/bookings");
    if (res.status === 401) {
      router.push("/admin/login");
      return;
    }
    const data = await res.json();
    if (!res.ok) {
      setError(data.error || "Failed to load bookings");
      return;
    }
    setBookings(data.bookings);
  }

  useEffect(() => {
    load();
  }, []);

  async function updateStatus(id: string, status: string) {
    await fetch("/api/admin/bookings", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status }),
    });
    load();
  }

  if (error) return <main className="p-10 text-red-700">{error}</main>;
  if (!bookings) return <main className="p-10 text-ink/60">Loading…</main>;

  return (
    <main className="mx-auto max-w-4xl px-6 py-10">
      <h1 className="font-display text-3xl text-tealDark mb-6">Bookings</h1>

      {bookings.length === 0 ? (
        <p className="text-ink/60">No bookings yet.</p>
      ) : (
        <div className="overflow-x-auto rounded-lg border border-sandDark">
          <table className="w-full text-sm">
            <thead className="bg-sandDark/50 text-left">
              <tr>
                <th className="p-3">Guest</th>
                <th className="p-3">Dates</th>
                <th className="p-3">Nights</th>
                <th className="p-3">Total</th>
                <th className="p-3">Status</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody>
              {bookings.map((b) => (
                <tr key={b.id} className="border-t border-sandDark/60">
                  <td className="p-3">
                    <div className="font-medium">{b.guest_name}</div>
                    <div className="text-ink/50 text-xs">{b.guest_email}</div>
                  </td>
                  <td className="p-3">{b.check_in} → {b.check_out}</td>
                  <td className="p-3">{b.nights}</td>
                  <td className="p-3">${b.total_usd.toLocaleString()}</td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-1 text-xs font-medium ${STATUS_STYLES[b.status] || ""}`}>
                      {b.status}
                    </span>
                  </td>
                  <td className="p-3">
                    {b.status !== "cancelled" && (
                      <button
                        onClick={() => updateStatus(b.id, "cancelled")}
                        className="focus-ring text-xs text-red-700 underline"
                      >
                        Cancel
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </main>
  );
}
