"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import dynamic from "next/dynamic";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Clock,
  MapPin,
  Star,
  Users,
  Calendar,
  CheckCircle2,
} from "lucide-react";
import { ReviewList } from "@/components/review-list";

// Lazy load heavy modal components (only loaded when opened)
const AuthModal = dynamic(
  () => import("@/components/auth-modal").then((mod) => ({ default: mod.AuthModal })),
  {
    loading: () => <div>Loading...</div>,
  }
);

const BookingForm = dynamic(
  () => import("@/components/booking-form").then((mod) => ({ default: mod.BookingForm })),
  {
    loading: () => <div>Loading...</div>,
  }
);

const ReviewForm = dynamic(
  () => import("@/components/review-form").then((mod) => ({ default: mod.ReviewForm })),
  {
    loading: () => <div>Loading...</div>,
  }
);

// Lazy load map components (they're heavy and not needed immediately)
const TourMap = dynamic(
  () => import("@/components/maps/tour-map").then((mod) => ({ default: mod.TourMap })),
  {
    loading: () => (
      <div className="h-96 bg-muted animate-pulse rounded-lg flex items-center justify-center">
        <div className="text-muted-foreground">Loading map...</div>
      </div>
    ),
    ssr: false, // Maps don't need server-side rendering
  }
);

const DirectionsButton = dynamic(
  () => import("@/components/maps/directions-button").then((mod) => ({ default: mod.DirectionsButton })),
  {
    loading: () => <div className="h-10 w-32 bg-muted animate-pulse rounded" />,
    ssr: false,
  }
);

interface Review {
  id: string;
  rating: number;
  comment: string | null;
  createdAt: Date;
  user: {
    name: string | null;
    image: string | null;
  };
}

interface TourHost {
  user: {
    id: string;
    name: string | null;
    image: string | null;
  };
}

interface TourDetailClientProps {
  tour: {
    id: string;
    title: string;
    slug: string;
    description: string;
    city: string;
    meetingPoint: string | null;
    meetingPointLat: number | null;
    meetingPointLng: number | null;
    priceCents: number | null;
    durationMin: number | null;
    maxGuests: number | null;
    avgRating: number | null;
    reviewCount: number;
    tags: string[];
    included: string[];
    images?: Array<{ url: string; order: number; displayUrl: string | null }>;
    createdBy: {
      id: string;
      name: string | null;
      email: string;
      image: string | null;
      bio: string | null;
    };
    reviews: Review[];
    hosts?: TourHost[];
    _count: {
      bookings: number;
      reviews: number;
    };
  };
  user: {
    id: string;
    name: string | null;
    email: string;
    role: string;
  } | null;
}

export function TourDetailClient({ tour, user }: TourDetailClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [showBookingDialog, setShowBookingDialog] = useState(false);
  const [showReviewDialog, setShowReviewDialog] = useState(false);
  const isAuthenticated = !!user;
  const isGuide = user?.id === tour.createdBy.id;

  // Check if review param is in URL
  useEffect(() => {
    const shouldShowReview = searchParams?.get("review") === "true" && isAuthenticated && !isGuide;
    if (shouldShowReview) {
      // Use setTimeout to avoid sync state update in effect
      const timer = setTimeout(() => setShowReviewDialog(true), 0);
      return () => clearTimeout(timer);
    }
  }, [searchParams, isAuthenticated, isGuide]);

  const formatPrice = (priceInCents: number | null) => {
    if (!priceInCents) return "Free";
    return `CHF ${(priceInCents / 100).toFixed(0)}`;
  };

  const formatDuration = (minutes: number | null) => {
    if (!minutes) return "N/A";
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (mins === 0) return `${hours}h`;
    return `${hours}h ${mins}m`;
  };

  const handleBookNow = () => {
    if (!isAuthenticated) {
      setShowAuthModal(true);
    } else {
      setShowBookingDialog(true);
    }
  };

  const handleAuthSuccess = () => {
    setShowAuthModal(false);
    setTimeout(() => {
      setShowBookingDialog(true);
    }, 300);
  };

  const handleBookingSuccess = () => {
    setShowBookingDialog(false);
    router.push("/bookings");
  };

  const handleReviewSuccess = () => {
    setShowReviewDialog(false);
    router.refresh();
  };

  return (
    <>
      <div className="min-h-screen bg-gray-50">
        {/* Hero Image Section */}
        <div className="relative h-[400px] bg-gray-200">
          {tour.images?.[0]?.displayUrl ? (
            <Image
              src={tour.images[0].displayUrl}
              alt={tour.title}
              fill
              className="object-cover"
            />
          ) : (
            <div className="flex items-center justify-center h-full bg-linear-to-br from-blue-100 to-blue-200">
              <MapPin className="h-24 w-24 text-blue-400" />
            </div>
          )}
          <div className="absolute inset-0 bg-linear-to-t from-black/60 to-transparent" />
          <div className="absolute bottom-0 left-0 right-0 p-8">
            <div className="container mx-auto">
              <Badge className="mb-2 bg-white/90 text-gray-900 hover:bg-white">
                {tour.city}
              </Badge>
              <h1 className="text-4xl font-bold text-white mb-2">
                {tour.title}
              </h1>
              <div className="flex items-center gap-4 text-white/90">
                <div className="flex items-center gap-1">
                  <Star className="h-5 w-5 fill-yellow-400 text-yellow-400" />
                  <span className="font-semibold">
                    {tour.avgRating?.toFixed(1) || "New"}
                  </span>
                  {tour._count.reviews > 0 && (
                    <span className="text-sm">({tour._count.reviews} {tour._count.reviews === 1 ? 'review' : 'reviews'})</span>
                  )}
                </div>
                <div className="flex items-center gap-1">
                  <Users className="h-5 w-5" />
                  <span>{tour._count.bookings} {tour._count.bookings === 1 ? 'booking' : 'bookings'}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="container mx-auto px-4 py-8">
          <div className="grid lg:grid-cols-3 gap-8">
            {/* Left Column - Tour Details */}
            <div className="lg:col-span-2 space-y-6">
              {/* Quick Info */}
              <Card>
                <CardContent className="p-6">
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                        <Clock className="h-5 w-5 text-blue-600" />
                      </div>
                      <div>
                        <p className="text-sm text-gray-500">Duration</p>
                        <p className="font-semibold">
                          {formatDuration(tour.durationMin)}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-green-100 flex items-center justify-center">
                        <Users className="h-5 w-5 text-green-600" />
                      </div>
                      <div>
                        <p className="text-sm text-gray-500">Group Size</p>
                        <p className="font-semibold">Max {tour.maxGuests}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-purple-100 flex items-center justify-center">
                        <MapPin className="h-5 w-5 text-purple-600" />
                      </div>
                      <div>
                        <p className="text-sm text-gray-500">Location</p>
                        <p className="font-semibold">{tour.city}</p>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Description */}
              <Card>
                <CardContent className="p-6">
                  <h2 className="text-2xl font-bold mb-4">About This Tour</h2>
                  <p className="text-gray-600 whitespace-pre-line">
                    {tour.description}
                  </p>
                </CardContent>
              </Card>

              {/* Tour Images Gallery */}
              {tour.images && tour.images.length > 1 && (
                <Card>
                  <CardContent className="p-6">
                    <h2 className="text-2xl font-bold mb-4">Tour Images</h2>
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                      {tour.images.map((image, index) => (
                        image.displayUrl && (
                          <div
                            key={index}
                            className="relative aspect-square rounded-lg overflow-hidden group cursor-pointer"
                          >
                            <Image
                              src={image.displayUrl}
                              alt={`Tour image ${index + 1}`}
                              fill
                              className="object-cover transition-transform group-hover:scale-110"
                            />
                          </div>
                        )
                      ))}
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* Meeting Point Map */}
              {tour.meetingPointLat && tour.meetingPointLng && (
                <Card>
                  <CardHeader>
                    <CardTitle>Meeting Point</CardTitle>
                    {tour.meetingPoint && (
                      <CardDescription>{tour.meetingPoint}</CardDescription>
                    )}
                  </CardHeader>
                  <CardContent className="p-0 pb-6 px-6">
                    <TourMap
                      latitude={tour.meetingPointLat}
                      longitude={tour.meetingPointLng}
                      height="400px"
                    />
                    <div className="mt-4">
                      <DirectionsButton
                        latitude={tour.meetingPointLat}
                        longitude={tour.meetingPointLng}
                        className="w-full"
                      />
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* What's Included */}
              {tour.included && tour.included.length > 0 && (
                <Card>
                  <CardContent className="p-6">
                    <h2 className="text-2xl font-bold mb-4">What&apos;s Included</h2>
                    <ul className="space-y-2">
                      {tour.included.map((item: string, index: number) => (
                        <li key={index} className="flex items-start gap-2">
                          <CheckCircle2 className="h-5 w-5 text-green-600 mt-0.5 shrink-0" />
                          <span className="text-gray-600">{item}</span>
                        </li>
                      ))}
                    </ul>
                  </CardContent>
                </Card>
              )}

              {/* Tags */}
              {tour.tags && tour.tags.length > 0 && (
                <Card>
                  <CardContent className="p-6">
                    <h2 className="text-2xl font-bold mb-4">Tags</h2>
                    <div className="flex flex-wrap gap-2">
                      {tour.tags.map((tag: string) => (
                        <Badge key={tag} variant="secondary">
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* Reviews Section */}
              {tour.reviews && tour.reviews.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle>Reviews</CardTitle>
                    <CardDescription>
                      {tour._count.reviews} {tour._count.reviews === 1 ? 'review' : 'reviews'}
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <ReviewList
                      reviews={tour.reviews}
                      avgRating={tour.avgRating || 0}
                      reviewCount={tour._count.reviews}
                    />
                  </CardContent>
                </Card>
              )}
            </div>

            {/* Right Column - Booking Card */}
            <div className="lg:col-span-1">
              <Card className="sticky top-4">
                <CardContent className="p-6">
                  <div className="mb-6">
                    <div className="flex items-baseline gap-2 mb-1">
                      <span className="text-3xl font-bold">
                        {formatPrice(tour.priceCents)}
                      </span>
                      <span className="text-gray-500">per person</span>
                    </div>
                    {tour.avgRating && (
                      <div className="flex items-center gap-1 text-sm">
                        <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                        <span className="font-semibold">
                          {tour.avgRating.toFixed(1)}
                        </span>
                        <span className="text-gray-500">
                          ({tour._count.reviews} {tour._count.reviews === 1 ? 'review' : 'reviews'})
                        </span>
                      </div>
                    )}
                  </div>

                  <Separator className="my-4" />

                  {/* Guide Info */}
                  <div className="mb-6">
                    <p className="text-sm text-gray-500 mb-2">Your Guide</p>
                    <Link 
                      href={`/users/${tour.createdBy.id}`}
                      className="flex items-center gap-3 hover:bg-gray-50 rounded-lg p-2 -ml-2 transition-colors"
                    >
                      <Avatar className="h-12 w-12">
                        <AvatarImage src={tour.createdBy.image || undefined} alt={tour.createdBy.name || "Guide"} />
                        <AvatarFallback className="bg-blue-100 text-blue-600">
                          {tour.createdBy.name?.charAt(0).toUpperCase() || "G"}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <p className="font-semibold text-blue-600 hover:underline">
                          {tour.createdBy.name}
                        </p>
                        <p className="text-sm text-gray-500">Local Expert</p>
                      </div>
                    </Link>

                    {/* Co-Hosts */}
                    {tour.hosts && tour.hosts.length > 0 && (
                      <div className="mt-4 pt-4 border-t">
                        <p className="text-sm text-gray-500 mb-2">
                          Co-Host{tour.hosts.length > 1 ? 's' : ''}
                        </p>
                        <div className="space-y-2">
                          {tour.hosts.map((host) => (
                            <Link
                              key={host.user.id}
                              href={`/users/${host.user.id}`}
                              className="flex items-center gap-2 text-sm hover:bg-gray-50 rounded-lg p-2 -ml-2 transition-colors"
                            >
                              <Avatar className="h-8 w-8">
                                <AvatarImage src={host.user.image || undefined} alt={host.user.name || "Co-host"} />
                                <AvatarFallback className="bg-gray-100 text-gray-600 text-xs">
                                  {host.user.name?.charAt(0).toUpperCase() || "C"}
                                </AvatarFallback>
                              </Avatar>
                              <span className="text-blue-600 hover:underline">
                                {host.user.name}
                              </span>
                            </Link>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>

                  <Button
                    className="w-full"
                    size="lg"
                    onClick={handleBookNow}
                  >
                    <Calendar className="h-5 w-5 mr-2" />
                    {isAuthenticated ? "Book This Tour" : "Book Now"}
                  </Button>

                  {!isAuthenticated && (
                    <p className="text-xs text-gray-500 text-center mt-3">
                      You&apos;ll need to sign in to book this tour
                    </p>
                  )}

                  <div className="mt-6 space-y-2 text-sm text-gray-600">
                    <div className="flex items-center gap-2">
                      <CheckCircle2 className="h-4 w-4 text-green-600" />
                      <span>Free cancellation up to 24h</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <CheckCircle2 className="h-4 w-4 text-green-600" />
                      <span>Instant confirmation</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <CheckCircle2 className="h-4 w-4 text-green-600" />
                      <span>Mobile ticket accepted</span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </div>

      {/* Auth Modal */}
      <AuthModal
        open={showAuthModal}
        onOpenChange={setShowAuthModal}
        defaultTab="signup"
        onSuccess={handleAuthSuccess}
      />

      {/* Booking Dialog */}
      <Dialog open={showBookingDialog} onOpenChange={setShowBookingDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Book This Tour</DialogTitle>
          </DialogHeader>
          <BookingForm
            tourId={tour.id}
            tourTitle={tour.title}
            pricePerPerson={tour.priceCents || 0}
            maxGuests={tour.maxGuests || 10}
            onSuccess={handleBookingSuccess}
          />
        </DialogContent>
      </Dialog>

      {/* Review Dialog */}
      <Dialog open={showReviewDialog} onOpenChange={setShowReviewDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Leave a Review</DialogTitle>
          </DialogHeader>
          <ReviewForm
            tourId={tour.id}
            tourTitle={tour.title}
            onSuccess={handleReviewSuccess}
          />
        </DialogContent>
      </Dialog>
    </>
  );
}
