import prisma from "@/lib/prisma";
import Link from "next/link";
import type { Metadata } from "next";

const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";

export const metadata: Metadata = {
  title: "Escort Events & Tours | AdultWorld",
  description: "Browse upcoming escort events and tours. Find escorts available for bookings in your city.",
  alternates: { canonical: `${baseUrl}/events` },
  openGraph: {
    title: "Escort Events & Tours | AdultWorld",
    description: "Browse upcoming escort events and tours near you.",
    url: `${baseUrl}/events`,
  },
  twitter: {
    card: "summary_large_image",
    title: "Escort Events & Tours | AdultWorld",
    description: "Browse upcoming escort events and tours near you.",
  },
};

interface Tour {
  id: number;
  user_id: number;
  username: string | null;
  profile_photo: string | null;
  city: string;
  start_date: string;
  end_date: string;
  notes: string | null;
  id_aw: string | null;
}

export default async function EventsPage() {
  let tours: Tour[] = [];

  try {
    tours = await prisma.$queryRawUnsafe(`
      SELECT t.id, t.user_id, u.username, u.profile_photo, u.id_aw,
             t.city, t.start_date::text, t.end_date::text, t.notes
      FROM tours t
      JOIN users u ON u.id = t.user_id
      WHERE t.start_date > CURRENT_DATE
      ORDER BY t.start_date ASC
      LIMIT 50
    `);
  } catch {
    // tours table may not exist yet
  }

  const eventsLd = tours.length === 0 ? null : tours.map((tour) => ({
    "@context": "https://schema.org",
    "@type": "Event",
    name: `${tour.username ?? "Escort"} in ${tour.city}`,
    startDate: tour.start_date,
    endDate: tour.end_date,
    eventStatus: "https://schema.org/EventScheduled",
    eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
    location: { "@type": "Place", name: tour.city },
    ...(tour.username && {
      organizer: { "@type": "Person", name: tour.username, url: `${baseUrl}/view/${tour.id_aw ?? tour.user_id}` },
    }),
    url: `${baseUrl}/view/${tour.id_aw ?? tour.user_id}`,
    ...(tour.notes && { description: tour.notes }),
  }));

  return (
    <div className="max-w-6xl mx-auto py-8 px-4">
      {eventsLd && (
        <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(eventsLd) }} />
      )}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-white">Upcoming Events & Tours</h1>
        <p className="text-text-muted mt-2">
          Discover escorts visiting your city soon. Book ahead for the best experience.
        </p>
      </div>

      {tours.length === 0 ? (
        <div className="text-center py-20 bg-surface rounded-xl border border-surface-light">
          <svg className="w-16 h-16 text-text-muted mx-auto mb-4" 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>
          <h2 className="text-xl font-semibold text-white mb-2">No Upcoming Events</h2>
          <p className="text-text-muted mb-6">
            Check back soon for upcoming escort tours and events.
          </p>
          <Link
            href="/escorts"
            className="inline-flex items-center gap-2 bg-gold hover:bg-gold-light text-black font-semibold px-6 py-3 rounded-xl transition-all"
          >
            Browse Escorts
          </Link>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {tours.map((tour) => {
            const startDate = new Date(tour.start_date);
            const endDate = new Date(tour.end_date);
            const formatDate = (d: Date) =>
              d.toLocaleDateString(undefined, { day: "numeric", month: "short" });

            return (
              <div
                key={tour.id}
                className="bg-surface rounded-xl border border-surface-light overflow-hidden hover:border-gold/30 transition-all group"
              >
                <div className="p-5 space-y-3">
                  {/* City & Dates */}
                  <div className="flex items-start justify-between">
                    <div>
                      <h3 className="text-lg font-semibold text-white group-hover:text-gold transition-colors">
                        {tour.city}
                      </h3>
                      <p className="text-gold text-sm font-medium">
                        {formatDate(startDate)} - {formatDate(endDate)}
                      </p>
                    </div>
                    <span className="bg-green-500/20 text-green-400 text-xs font-medium px-2.5 py-1 rounded-full">
                      Available
                    </span>
                  </div>

                  {/* Escort info */}
                  <div className="flex items-center gap-3">
                    <img
                      src={tour.profile_photo ? `/storage/${tour.profile_photo}` : "/placeholder-avatar.svg"}
                      alt={tour.username ?? ""}
                      className="w-10 h-10 rounded-full object-cover border border-surface-light"
                    />
                    <div>
                      <Link
                        href={`/view/${tour.id_aw ?? tour.user_id}`}
                        className="text-white text-sm font-medium hover:text-gold transition-colors"
                      >
                        {tour.username ?? "Anonymous"}
                      </Link>
                      <p className="text-text-muted text-xs">Available for bookings</p>
                    </div>
                  </div>

                  {/* Notes */}
                  {tour.notes && (
                    <p className="text-text-muted text-sm line-clamp-2">{tour.notes}</p>
                  )}

                  {/* Action */}
                  <Link
                    href={`/view/${tour.id_aw ?? tour.user_id}`}
                    className="block w-full text-center bg-surface-light hover:bg-gold hover:text-black text-white font-medium py-2.5 rounded-lg transition-all text-sm mt-2"
                  >
                    View Profile & Book
                  </Link>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
