import prisma from "@/lib/prisma";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { updateBookingStatus, updateReviewStatus } from "@/app/actions/admin";
import { confirmPaymentAndBooking } from "@/app/actions/settings";

export default async function AdminDashboard() {
  const session = await getServerSession(authOptions);
  const role = (session?.user as any)?.role;

  const bookings = await prisma.booking.findMany({
    include: { room: true },
    orderBy: { createdAt: "desc" },
    take: 10,
  });

  const pendingReviews = await prisma.review.findMany({
    where: { status: "PENDING" },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div>
      <h1 style={{ fontSize: "2.5rem", marginBottom: "2rem", color: "#0f172a" }}>Overview Dashboard</h1>

      {/* Bookings Section */}
      <section style={{ marginBottom: "3rem" }}>
        <h2 style={{ fontSize: "1.5rem", marginBottom: "1rem", color: "#334155", borderBottom: "2px solid #e2e8f0", paddingBottom: "0.5rem" }}>
          Recent Booking Requests
        </h2>
        
        <div style={{ backgroundColor: "white", borderRadius: "0.5rem", boxShadow: "0 1px 3px rgba(0,0,0,0.1)", overflow: "hidden" }}>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead style={{ backgroundColor: "#f8fafc", borderBottom: "1px solid #e2e8f0" }}>
              <tr>
                <th style={{ padding: "1rem", textAlign: "left", color: "#64748b" }}>Guest</th>
                <th style={{ padding: "1rem", textAlign: "left", color: "#64748b" }}>Room & Dates</th>
                <th style={{ padding: "1rem", textAlign: "left", color: "#64748b" }}>Payment</th>
                <th style={{ padding: "1rem", textAlign: "left", color: "#64748b" }}>Status</th>
                <th style={{ padding: "1rem", textAlign: "left", color: "#64748b" }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {bookings.length === 0 ? (
                <tr>
                  <td colSpan={5} style={{ padding: "2rem", textAlign: "center", color: "#94a3b8" }}>No bookings found</td>
                </tr>
              ) : bookings.map((booking) => (
                <tr key={booking.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                  <td style={{ padding: "1rem" }}>
                    <div><strong>{booking.guestName}</strong></div>
                    <div style={{ fontSize: "0.875rem", color: "#64748b" }}>{booking.guestPhone}</div>
                  </td>
                  <td style={{ padding: "1rem" }}>
                    <div><strong>{booking.room.title}</strong></div>
                    <div style={{ fontSize: "0.875rem", color: "#64748b" }}>In: {booking.checkInDate.toLocaleDateString()}</div>
                    <div style={{ fontSize: "0.875rem", color: "#64748b" }}>Out: {booking.checkOutDate.toLocaleDateString()}</div>
                  </td>
                  <td style={{ padding: "1rem" }}>
                    <div><strong style={{ fontSize: "0.875rem" }}>{booking.paymentMethod}</strong></div>
                    <div style={{ fontSize: "0.75rem", color: booking.paymentStatus === "PAID" ? "#166534" : "#92400e" }}>
                      Status: {booking.paymentStatus}
                    </div>
                    {booking.amountPaid && <div style={{ fontSize: "0.75rem", fontWeight: "bold" }}>EGP {booking.amountPaid}</div>}
                    {booking.receiptUrl && (
                      <a href={booking.receiptUrl} target="_blank" rel="noreferrer" style={{ fontSize: "0.75rem", color: "#2563eb", textDecoration: "underline" }}>View Receipt</a>
                    )}
                  </td>
                  <td style={{ padding: "1rem" }}>
                    <span style={{ 
                      padding: "0.25rem 0.75rem", 
                      borderRadius: "999px", 
                      fontSize: "0.75rem", 
                      fontWeight: "bold",
                      backgroundColor: booking.status === "PENDING" ? "#fef3c7" : booking.status === "CONFIRMED" ? "#dcfce3" : "#fee2e2",
                      color: booking.status === "PENDING" ? "#92400e" : booking.status === "CONFIRMED" ? "#166534" : "#991b1b"
                    }}>
                      {booking.status}
                    </span>
                  </td>
                  <td style={{ padding: "1rem" }}>
                    {booking.status === "PENDING" && (
                      <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
                        {booking.paymentStatus === "PENDING_VERIFICATION" && (
                          <form action={async () => { "use server"; await confirmPaymentAndBooking(booking.id); }}>
                            <button style={{ padding: "0.5rem 1rem", backgroundColor: "#3b82f6", color: "white", border: "none", borderRadius: "0.25rem", cursor: "pointer", fontSize: "0.75rem" }}>
                              Confirm Payment & Booking
                            </button>
                          </form>
                        )}
                        {booking.paymentStatus !== "PENDING_VERIFICATION" && (
                          <form action={async () => { "use server"; await updateBookingStatus(booking.id, "CONFIRMED"); }}>
                            <button style={{ padding: "0.5rem 1rem", backgroundColor: "#10b981", color: "white", border: "none", borderRadius: "0.25rem", cursor: "pointer", fontSize: "0.75rem" }}>
                              Confirm
                            </button>
                          </form>
                        )}
                        <form action={async () => { "use server"; await updateBookingStatus(booking.id, "CANCELLED"); }}>
                          <button style={{ padding: "0.5rem 1rem", backgroundColor: "#ef4444", color: "white", border: "none", borderRadius: "0.25rem", cursor: "pointer", fontSize: "0.75rem" }}>
                            Cancel
                          </button>
                        </form>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {/* Reviews Moderation (Admin Only) */}
      {role === "ADMIN" && (
        <section>
          <h2 style={{ fontSize: "1.5rem", marginBottom: "1rem", color: "#334155", borderBottom: "2px solid #e2e8f0", paddingBottom: "0.5rem" }}>
            Pending Reviews (Moderation)
          </h2>
          <div style={{ display: "grid", gap: "1rem" }}>
            {pendingReviews.length === 0 ? (
              <p style={{ color: "#94a3b8" }}>No pending reviews to moderate.</p>
            ) : pendingReviews.map((review) => (
              <div key={review.id} style={{ backgroundColor: "white", padding: "1.5rem", borderRadius: "0.5rem", boxShadow: "0 1px 3px rgba(0,0,0,0.1)", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                <div>
                  <strong style={{ fontSize: "1.125rem" }}>{review.guestName}</strong>
                  <div style={{ color: "#eab308", margin: "0.25rem 0" }}>{"★".repeat(review.rating)}{"☆".repeat(5 - review.rating)}</div>
                  <p style={{ color: "#475569", marginTop: "0.5rem", fontStyle: "italic" }}>"{review.comment}"</p>
                </div>
                <div style={{ display: "flex", gap: "0.5rem" }}>
                  <form action={async () => { "use server"; await updateReviewStatus(review.id, "APPROVED"); }}>
                    <button style={{ padding: "0.5rem 1rem", backgroundColor: "#10b981", color: "white", border: "none", borderRadius: "0.25rem", cursor: "pointer", fontSize: "0.75rem" }}>Approve</button>
                  </form>
                  <form action={async () => { "use server"; await updateReviewStatus(review.id, "REJECTED"); }}>
                    <button style={{ padding: "0.5rem 1rem", backgroundColor: "#ef4444", color: "white", border: "none", borderRadius: "0.25rem", cursor: "pointer", fontSize: "0.75rem" }}>Reject</button>
                  </form>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
