import { requireGuide } from "@/lib/auth-utils";
import { redirect, notFound } from "next/navigation";
import prisma from "@/lib/db";
import TourForm from "../../create/tour-form";
import ExistingImages from "./existing-images";

type PageProps = {
  params: Promise<{ id: string }>;
};

export default async function EditTourPage({ params }: PageProps) {
  let user;
  try {
    user = await requireGuide();
  } catch {
    redirect("/login");
  }

  const { id } = await params;

  const tour = await prisma.tour.findUnique({
    where: { id },
    include: {
      images: {
        orderBy: {
          order: "asc",
        },
      },
    },
  });

  if (!tour) {
    notFound();
  }

  // Check if user owns this tour
  if (tour.createdById !== user.id) {
    redirect("/dashboard");
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-4xl">
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">Edit Tour</h1>
        <p className="text-muted-foreground">
          Update your tour details and keep your listing fresh.
        </p>
      </div>

      {/* Existing Images Section */}
      {tour.images.length > 0 && (
        <ExistingImages tourId={tour.id} images={tour.images} />
      )}

      <TourForm
        mode="edit"
        initialData={{
          id: tour.id,
          title: tour.title,
          description: tour.description,
          city: tour.city,
          meetingPoint: tour.meetingPoint || undefined,
          durationMin: tour.durationMin || 180,
          priceCents: tour.priceCents || 0,
          maxGuests: tour.maxGuests || 10,
          published: tour.published,
        }}
        initialIncluded={tour.included}
        initialTags={tour.tags}
      />
    </div>
  );
}
