import { notFound, redirect } from "next/navigation";
import db from "@/lib/db";
import { getCurrentUser } from "@/lib/auth-utils";
import { getImageDisplayUrl } from "@/lib/image-utils";
import Image from "next/image";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { 
  MapPin, 
  Users, 
  DollarSign, 
  Clock, 
  CheckCircle2,
  Tag
} from "lucide-react";
import { PreviewActions } from "./preview-actions";
import { PreviewMap } from "./preview-map";

interface TourPreviewPageProps {
  params: Promise<{
    id: string;
  }>;
}

export default async function TourPreviewPage({ params }: TourPreviewPageProps) {
  const { id } = await params;
  
  // Get authenticated user
  const user = await getCurrentUser();

  if (!user) {
    redirect("/login");
  }

  // Only guides can preview their tours
  if (user.role !== "GUIDE") {
    redirect("/dashboard");
  }

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

  if (!tour) {
    notFound();
  }

  // Verify tour belongs to this guide
  if (tour.createdById !== user.id) {
    redirect("/dashboard");
  }

  // Process image URLs to get signed URLs for S3 images
  const processedImages = await Promise.all(
    tour.images.map(async (image) => ({
      ...image,
      displayUrl: await getImageDisplayUrl(image.url),
    }))
  );

  const mainImage = processedImages[0];

  return (
    <div className="container mx-auto py-8 px-4 max-w-5xl">
      {/* Header with Status */}
      <div className="flex items-start justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold mb-2">{tour.title}</h1>
          <div className="flex items-center gap-3">
            {tour.published ? (
              <Badge className="bg-green-500 hover:bg-green-600">
                <CheckCircle2 className="w-3 h-3 mr-1" />
                Published
              </Badge>
            ) : (
              <Badge variant="secondary">Draft</Badge>
            )}
            {tour.archived && (
              <Badge variant="outline" className="text-orange-600 border-orange-600">
                Archived
              </Badge>
            )}
          </div>
        </div>
      </div>

      {/* What happens next message */}
      <Card className="mb-6 border-blue-200 bg-blue-50/50">
        <CardHeader>
          <CardTitle className="text-lg">What happens next?</CardTitle>
        </CardHeader>
        <CardContent>
          {tour.published ? (
            <p className="text-sm text-muted-foreground">
              Your tour is <strong>live</strong> and visible to tourists. They can browse and book this tour. 
              You can unpublish it anytime to make changes or hide it temporarily.
            </p>
          ) : (
            <p className="text-sm text-muted-foreground">
              This tour is currently a <strong>draft</strong> and not visible to tourists. 
              When you&apos;re ready, click &quot;Publish Tour&quot; to make it available for booking.
            </p>
          )}
        </CardContent>
      </Card>

      {/* Action Buttons */}
      <PreviewActions 
        tourId={tour.id} 
        isPublished={tour.published}
        isArchived={tour.archived}
      />

      <Separator className="my-8" />

      {/* Tour Details Preview */}
      <div className="space-y-8">
        {/* Main Image */}
        {mainImage && mainImage.displayUrl && (
          <div className="relative w-full h-[400px] rounded-lg overflow-hidden">
            <Image
              src={mainImage.displayUrl}
              alt={tour.title}
              fill
              className="object-cover"
              priority
            />
          </div>
        )}

        {/* Quick Info Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <MapPin className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm text-muted-foreground">City</p>
                  <p className="font-medium">{tour.city}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <DollarSign className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm text-muted-foreground">Price</p>
                  <p className="font-medium">CHF {tour.priceCents ? (tour.priceCents / 100).toFixed(2) : '0.00'}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <Clock className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm text-muted-foreground">Duration</p>
                  <p className="font-medium">
                    {tour.durationMin ? `${Math.floor(tour.durationMin / 60)}h ${tour.durationMin % 60}m` : 'Not set'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <Users className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm text-muted-foreground">Group Size</p>
                  <p className="font-medium">Max {tour.maxGuests} people</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Description */}
        <Card>
          <CardHeader>
            <CardTitle>Description</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground whitespace-pre-wrap">{tour.description}</p>
          </CardContent>
        </Card>

        {/* What&apos;s Included */}
        {tour.included && tour.included.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>What&apos;s Included</CardTitle>
            </CardHeader>
            <CardContent>
              <ul className="space-y-2">
                {tour.included.map((item, index) => (
                  <li key={index} className="flex items-start gap-2">
                    <CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 shrink-0" />
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
            </CardContent>
          </Card>
        )}

        {/* Tags */}
        {tour.tags && tour.tags.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Tour Tags</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap gap-2">
                {tour.tags.map((tag, index) => (
                  <Badge key={index} variant="secondary" className="flex items-center gap-1">
                    <Tag className="w-3 h-3" />
                    {tag}
                  </Badge>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* All Images */}
        {tour.images.length > 1 && (
          <Card>
            <CardHeader>
              <CardTitle>Tour Images ({tour.images.length})</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                {processedImages.map((image) => (
                  image.displayUrl && (
                    <div
                      key={image.id}
                      className="relative aspect-square rounded-lg overflow-hidden group"
                    >
                      <Image
                        src={image.displayUrl}
                        alt={`Tour image ${image.order}`}
                        fill
                        className="object-cover transition-transform group-hover:scale-105"
                      />
                    </div>
                  )
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Meeting Point Map */}
        {tour.meetingPointLat && tour.meetingPointLng && (
          <PreviewMap
            latitude={tour.meetingPointLat}
            longitude={tour.meetingPointLng}
            meetingPoint={tour.meetingPoint}
          />
        )}
      </div>

      {/* Bottom Actions */}
      <div className="mt-8">
        <Separator className="my-8" />
        <PreviewActions 
          tourId={tour.id} 
          isPublished={tour.published}
          isArchived={tour.archived}
        />
      </div>
    </div>
  );
}
