"use client";

import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useConfirm } from "@/components/shared/use-confirm";
import { useToastStore } from "@/lib/stores/toast-store";

interface Booking {
  id: number;
  client_id: number;
  escort_id: number;
  client_name: string;
  escort_name: string;
  booking_date: string;
  duration: string;
  booking_type: string;
  notes: string | null;
  status: string;
  created_at: string;
}

const statusColors: Record<string, string> = {
  pending: "bg-yellow-500/20 text-yellow-400 border-yellow-500/30",
  accepted: "bg-green-500/20 text-green-400 border-green-500/30",
  rejected: "bg-red-500/20 text-red-400 border-red-500/30",
  completed: "bg-blue-500/20 text-blue-400 border-blue-500/30",
  cancelled: "bg-zinc-500/20 text-zinc-400 border-zinc-500/30",
};

export default function MyBookingsPage() {
  const { data: session } = useSession();
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();
  const addToast = useToastStore((s) => s.addToast);
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<string>("all");
  const [updating, setUpdating] = useState<number | null>(null);

  const userId = session?.user?.id ? parseInt(session.user.id) : 0;
  const isEscort = (session?.user as Record<string, unknown>)?.userType === "escort";

  useEffect(() => {
    fetch("/api/bookings")
      .then((r) => r.json())
      .then((data) => setBookings(data.bookings || []))
      .finally(() => setLoading(false));
  }, []);

  async function handleStatusUpdate(bookingId: number, status: "accepted" | "rejected" | "cancelled" | "completed") {
    // Cancellation is destructive and irreversible — require an explicit
    // confirm. The other transitions are routine enough to fire on click.
    if (status === "cancelled") {
      const ok = await askConfirm({
        title: "Cancel booking?",
        message: "Cancelling a booking can't be undone. The other party will be notified.",
        confirmLabel: "Cancel booking",
        cancelLabel: "Keep booking",
      });
      if (!ok) return;
    }
    setUpdating(bookingId);
    try {
      const res = await fetch("/api/bookings", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ booking_id: bookingId, status }),
      });
      if (res.ok) {
        setBookings((prev) =>
          prev.map((b) => (b.id === bookingId ? { ...b, status } : b))
        );
        addToast("success", `Booking ${status}.`);
      } else {
        addToast("error", "Failed to update booking. Please try again.");
      }
    } catch {
      // Silent return previously hid genuine network failures.
      addToast("error", "Network error — couldn't reach the server.");
    } finally {
      setUpdating(null);
    }
  }

  const filtered =
    filter === "all" ? bookings : bookings.filter((b) => b.status === filter);

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto" aria-busy="true">
        <div className="h-8 w-48 bg-surface-light rounded mb-6 animate-pulse" />
        <div className="flex flex-wrap gap-2 mb-6">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="h-9 w-24 bg-surface rounded-lg animate-pulse" />
          ))}
        </div>
        <div className="space-y-4">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="bg-surface rounded-lg p-5 animate-pulse">
              <div className="h-5 w-2/3 bg-surface-light rounded mb-3" />
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                {Array.from({ length: 4 }).map((_, j) => (
                  <div key={j}>
                    <div className="h-3 w-16 bg-surface-light rounded mb-1" />
                    <div className="h-4 w-20 bg-surface-light rounded" />
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto">
      {confirmDialog}
      <h1 className="text-3xl font-bold text-text mb-6">My Bookings</h1>

      {/* Filters */}
      <div className="flex flex-wrap gap-2 mb-6">
        {["all", "pending", "accepted", "completed", "rejected", "cancelled"].map((status) => (
          <button
            key={status}
            onClick={() => setFilter(status)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors capitalize ${
              filter === status
                ? "bg-gold text-black"
                : "bg-surface text-text-muted hover:text-text"
            }`}
          >
            {status}
            {status !== "all" && (
              <span className="ml-1.5 text-xs opacity-75">
                ({bookings.filter((b) => b.status === status).length})
              </span>
            )}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="bg-surface rounded-lg p-12 text-center">
          <div className="relative w-16 h-16 mx-auto mb-4">
            <svg className="w-16 h-16 text-text-muted/30" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            <svg className="w-6 h-6 text-gold absolute -bottom-1 -right-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-text mb-1">No bookings yet</h3>
          <p className="text-text-muted mb-6">Browse escorts and request a booking to get started</p>
          <a
            href="/escorts"
            className="inline-flex items-center gap-2 bg-gold hover:bg-gold/90 text-black font-semibold px-6 py-3 rounded-lg transition-colors"
          >
            Browse Escorts
          </a>
        </div>
      ) : (
        <div className="space-y-4">
          {filtered.map((booking) => (
            <div key={booking.id} className="bg-surface rounded-lg p-5">
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <h3 className="font-semibold text-text">
                      {isEscort
                        ? `Booking from ${booking.client_name}`
                        : `Booking with ${booking.escort_name}`}
                    </h3>
                    <span
                      className={`px-2.5 py-0.5 rounded-full text-xs font-medium border capitalize ${
                        statusColors[booking.status] || statusColors.pending
                      }`}
                    >
                      {booking.status}
                    </span>
                  </div>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                    <div>
                      <p className="text-text-muted text-xs">Date</p>
                      <p className="text-text">
                        {new Date(booking.booking_date).toLocaleDateString(undefined, {
                          day: "numeric",
                          month: "short",
                          year: "numeric",
                        })}
                      </p>
                    </div>
                    <div>
                      <p className="text-text-muted text-xs">Duration</p>
                      <p className="text-text">{booking.duration}</p>
                    </div>
                    <div>
                      <p className="text-text-muted text-xs">Type</p>
                      <p className="text-text capitalize">{booking.booking_type}</p>
                    </div>
                    <div>
                      <p className="text-text-muted text-xs">Requested</p>
                      <p className="text-text">
                        {new Date(booking.created_at).toLocaleDateString(undefined)}
                      </p>
                    </div>
                  </div>
                  {booking.notes && (
                    <p className="text-text-muted text-sm mt-2 italic">
                      &ldquo;{booking.notes}&rdquo;
                    </p>
                  )}
                </div>

                {/* Accept/Reject buttons for escorts */}
                {isEscort && booking.status === "pending" && (
                  <div className="flex gap-2 shrink-0">
                    <button
                      onClick={() => handleStatusUpdate(booking.id, "accepted")}
                      disabled={updating === booking.id}
                      className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
                    >
                      Accept
                    </button>
                    <button
                      onClick={() => handleStatusUpdate(booking.id, "rejected")}
                      disabled={updating === booking.id}
                      className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
                    >
                      Reject
                    </button>
                  </div>
                )}

                {/* Cancel button for clients on their own pending/accepted bookings */}
                {!isEscort && booking.client_id === userId && (booking.status === "pending" || booking.status === "accepted") && (
                  <div className="flex gap-2 shrink-0">
                    <button
                      onClick={() => handleStatusUpdate(booking.id, "cancelled")}
                      disabled={updating === booking.id}
                      className="bg-zinc-700 hover:bg-zinc-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
                    >
                      Cancel
                    </button>
                  </div>
                )}

                {/* Mark-completed button for escorts on accepted bookings.
                    Without this UI nothing transitions to completed, which
                    means the Round-7 reviews booking-gate (requires a
                    completed booking) is unreachable. */}
                {isEscort && booking.status === "accepted" && (
                  <div className="flex gap-2 shrink-0">
                    <button
                      onClick={() => handleStatusUpdate(booking.id, "completed")}
                      disabled={updating === booking.id}
                      className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
                    >
                      Mark Completed
                    </button>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
