"use client";

import { getDetailToursId } from "@/pages/tours/lib/api";
import formatPrice from "@/shared/lib/formatPrice";
import { Badge } from "@/shared/ui/badge";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/shared/ui/tabs";
import { useQuery } from "@tanstack/react-query";
import {
  AlertTriangle,
  ArrowLeft,
  CheckCircle2,
  Clock,
  DollarSign,
  Globe,
  Hotel,
  Loader2,
  MapPin,
  Star,
  Users,
  Utensils,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";

export default function TourDetailPage() {
  const { t } = useTranslation();

  const params = useParams();
  const router = useNavigate();
  const {
    data: tour,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["tours_detail", params.id],
    queryFn: () => getDetailToursId({ id: Number(params.id) }),
    select(data) {
      return data.data.data;
    },
  });

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 text-white gap-4 w-full">
        <Loader2 className="w-10 h-10 animate-spin text-cyan-400" />
        <p className="text-slate-400">{t("Ma'lumotlar yuklanmoqda...")}</p>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 w-full text-center text-white gap-4">
        <AlertTriangle className="w-10 h-10 text-red-500" />
        <p className="text-lg">
          {t("Ma'lumotlarni yuklashda xatolik yuz berdi.")}
        </p>
        <Button
          onClick={() => refetch()}
          className="bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-lg px-5 py-2 hover:opacity-90"
        >
          {t("Qayta urinish")}
        </Button>
      </div>
    );
  }

  const renderStars = (rating: number) => {
    return Array.from({ length: 5 }).map((_, i) => (
      <Star
        key={i}
        className={`w-4 h-4 ${i < rating ? "fill-yellow-400 text-yellow-400" : "text-gray-600"}`}
      />
    ));
  };

  return (
    <div className="min-h-screen bg-gray-900 w-full">
      {tour && (
        <div className="container mx-auto px-4 py-8 max-w-full">
          <div className="flex items-center gap-4 mb-8">
            <Button
              variant="outline"
              size="icon"
              onClick={() => router(-1)}
              className="rounded-full border-gray-700 bg-gray-800 hover:bg-gray-700"
            >
              <ArrowLeft className="w-5 h-5 text-gray-300" />
            </Button>
            <div className="flex-1">
              <div className="flex items-center gap-3 mb-2">
                <h1 className="text-4xl font-bold text-white">{tour.title}</h1>
              </div>
              <div className="flex items-center gap-4 text-gray-400">
                <div className="flex items-center gap-1">
                  {renderStars(tour.rating)}
                  <span className="ml-2 font-semibold">{tour.rating}</span>
                </div>
                <span>•</span>
                <span>{tour.ticket_comments.length} sharh</span>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
            {tour.ticket_images.map((img, idx) => (
              <div
                key={idx}
                className="relative aspect-video rounded-lg overflow-hidden group"
              >
                <img
                  src={img.image || "/placeholder.svg"}
                  alt={`${tour.title} ${idx + 1}`}
                  className="w-full h-full object-cover transition-transform group-hover:scale-110"
                />
              </div>
            ))}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-8">
            <Card className="border-gray-700 shadow-lg bg-gray-800">
              <CardContent className="p-6">
                <div className="flex items-center gap-3 mb-2">
                  <DollarSign className="w-5 h-5 text-green-400" />
                  <p className="text-sm text-gray-400">{t("Narxi")}</p>
                </div>
                <p className="text-2xl font-bold text-white">
                  {formatPrice(tour.price, true)}
                </p>
              </CardContent>
            </Card>

            <Card className="border-gray-700 shadow-lg bg-gray-800">
              <CardContent className="p-6">
                <div className="flex items-center gap-3 mb-2">
                  <Clock className="w-5 h-5 text-blue-400" />
                  <p className="text-sm text-gray-400">{t("Davomiyligi")}</p>
                </div>
                <p className="text-2xl font-bold text-white">
                  {tour.duration_days} {t("kun")}
                </p>
              </CardContent>
            </Card>

            <Card className="border-gray-700 shadow-lg bg-gray-800">
              <CardContent className="p-6">
                <div className="flex items-center gap-3 mb-2">
                  <Users className="w-5 h-5 text-purple-400" />
                  <p className="text-sm text-gray-400">{t("Yo'lovchilar")}</p>
                </div>
                <p className="text-2xl font-bold text-white">
                  {tour.passenger_count} {t("kishi")}
                </p>
              </CardContent>
            </Card>

            {/* <Card className="border-gray-700 shadow-lg bg-gray-800">
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-2">
                <Calendar className="w-5 h-5 text-yellow-400" />
                <p className="text-sm text-gray-400">{t("Jo'nash sanasi")}</p>
              </div>
              <p className="text-xl font-bold text-white">
                {new Date(tour.departure_time).toLocaleDateString("uz-UZ")}
              </p>
            </CardContent>
          </Card> */}
          </div>

          <Tabs defaultValue="overview" className="space-y-6">
            <TabsList className="grid w-full grid-cols-2 md:grid-cols-5 lg:w-auto bg-gray-800 border-gray-700">
              <TabsTrigger
                value="overview"
                className="data-[state=active]:bg-gray-700 data-[state=active]:text-white text-gray-400"
              >
                {t("Umumiy")}
              </TabsTrigger>
              <TabsTrigger
                value="itinerary"
                className="data-[state=active]:bg-gray-700 data-[state=active]:text-white text-gray-400"
              >
                {t("Marshshrut")}
              </TabsTrigger>
              <TabsTrigger
                value="services"
                className="data-[state=active]:bg-gray-700 data-[state=active]:text-white text-gray-400"
              >
                {t("Xizmatlar")}
              </TabsTrigger>
              <TabsTrigger
                value="hotel"
                className="data-[state=active]:bg-gray-700 data-[state=active]:text-white text-gray-400"
              >
                {t("Mehmonxona")}
              </TabsTrigger>
              <TabsTrigger
                value="reviews"
                className="data-[state=active]:bg-gray-700 data-[state=active]:text-white text-gray-400"
              >
                {t("Sharhlar")}
              </TabsTrigger>
            </TabsList>

            <TabsContent value="overview" className="space-y-6">
              <Card className="border-gray-700 shadow-lg bg-gray-800">
                <CardHeader>
                  <CardTitle className="text-2xl text-white">
                    {t("Tur haqida ma'lumot")}
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-4">
                      <div className="flex items-start gap-3">
                        <MapPin className="w-5 h-5 text-green-400 mt-1" />
                        <div>
                          <p className="text-sm text-gray-400">
                            {t("Jo'nash joyi")}
                          </p>
                          <p className="font-semibold text-white">
                            {tour.departure}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-start gap-3">
                        <MapPin className="w-5 h-5 text-blue-400 mt-1" />
                        <div>
                          <p className="text-sm text-gray-400">
                            {t("Yo'nalish")}
                          </p>
                          <p className="font-semibold text-white">
                            {tour.destination}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-start gap-3">
                        <Globe className="w-5 h-5 text-purple-400 mt-1" />
                        <div>
                          <p className="text-sm text-gray-400">{t("Tillar")}</p>
                          <p className="font-semibold text-white">
                            {tour.languages}
                          </p>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-4">
                      <div className="flex items-start gap-3">
                        <Hotel className="w-5 h-5 text-yellow-400 mt-1" />
                        <div>
                          <p className="text-sm text-gray-400">
                            {t("Mehmonxona")}
                          </p>
                          <p className="font-semibold text-white">
                            {tour.hotel_info}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-start gap-3">
                        <Utensils className="w-5 h-5 text-green-400 mt-1" />
                        <div>
                          <p className="text-sm text-gray-400">
                            {t("Ovqatlanish")}
                          </p>
                          <p className="font-semibold text-white">
                            {tour.hotel_meals}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-start gap-3">
                        <CheckCircle2 className="w-5 h-5 text-blue-400 mt-1" />
                        <div>
                          <p className="text-sm text-gray-400">{t("Tarif")}</p>
                          {tour.tariff.map((e) => (
                            <p
                              key={e.tariff.name}
                              className="font-semibold text-white capitalize"
                            >
                              {e.tariff.name}
                            </p>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="pt-6 border-t border-gray-700">
                    <h3 className="text-lg font-semibold mb-4 text-white">
                      {t("Qulayliklar")}
                    </h3>
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                      {tour.ticket_amenities.map((amenity, idx) => (
                        <div
                          key={idx}
                          className="flex flex-col items-center gap-2 p-4 bg-gray-700/50 rounded-lg"
                        >
                          <CheckCircle2 className="w-6 h-6 text-green-400" />
                          <p className="text-sm text-center font-medium text-white">
                            {amenity.name}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="itinerary" className="space-y-6">
              <Card className="border-gray-700 shadow-lg bg-gray-800">
                <CardHeader>
                  <CardTitle className="text-2xl text-white">
                    {t("Sayohat marshshruti")}
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                  {tour.ticket_itinerary.map((day, idx) => (
                    <div
                      key={idx}
                      className="border-l-4 border-green-400 pl-6 pb-6 last:pb-0"
                    >
                      <div className="flex items-center gap-3 mb-3">
                        <Badge
                          variant="outline"
                          className="text-base border-gray-600 text-gray-300"
                        >
                          {day.duration}-{t("kun")}
                        </Badge>
                        <h3 className="text-xl font-semibold text-white">
                          {day.title}
                        </h3>
                      </div>

                      {day.ticket_itinerary_image.length > 0 && (
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                          {day.ticket_itinerary_image.map((img, imgIdx) => (
                            <div
                              key={imgIdx}
                              className="relative aspect-video rounded-lg overflow-hidden"
                            >
                              <img
                                src={img.image || "/placeholder.svg"}
                                alt={day.title}
                                className="w-full h-full object-cover"
                              />
                            </div>
                          ))}
                        </div>
                      )}

                      <div className="flex flex-wrap gap-2">
                        {day.ticket_itinerary_destinations.map(
                          (dest, destIdx) => (
                            <Badge
                              key={destIdx}
                              variant="secondary"
                              className="text-sm bg-gray-700 text-gray-300"
                            >
                              <MapPin className="w-3 h-3 mr-1" />
                              {dest.name}
                            </Badge>
                          ),
                        )}
                      </div>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="services" className="space-y-6">
              <Card className="border-gray-700 shadow-lg bg-gray-800">
                <CardHeader>
                  <CardTitle className="text-2xl text-white">
                    {t("Narxga kiritilgan xizmatlar")}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {tour.ticket_included_services.map((service, idx) => (
                      <div
                        key={idx}
                        className="border border-gray-700 rounded-lg overflow-hidden hover:shadow-xl transition-shadow bg-gray-800"
                      >
                        <div className="relative aspect-video">
                          <img
                            src={service.image || "/placeholder.svg"}
                            alt={service.title}
                            className="w-full h-full object-cover"
                          />
                        </div>
                        <div className="p-4">
                          <h3 className="text-lg font-semibold mb-2 text-white">
                            {service.title}
                          </h3>
                          <p className="text-gray-400 text-sm">
                            {service.desc}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="hotel" className="space-y-6">
              <Card className="border-gray-700 shadow-lg bg-gray-800">
                <CardHeader>
                  <CardTitle className="text-2xl text-white">
                    {t("Mehmonxona va ovqatlanish")}
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="p-6 bg-gray-700/50 rounded-lg">
                    <div className="flex items-center gap-3 mb-2">
                      <Hotel className="w-6 h-6 text-yellow-400" />
                      <h3 className="text-xl font-semibold text-white">
                        {tour.hotel_info}
                      </h3>
                    </div>
                    <p className="text-gray-400">{tour.hotel_meals}</p>
                  </div>

                  <div>
                    <h3 className="text-lg font-semibold mb-4 text-white">
                      {t("Ovqatlanish tafsilotlari")}
                    </h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      {tour.ticket_hotel_meals.map((meal, idx) => (
                        <div
                          key={idx}
                          className="border border-gray-700 rounded-lg overflow-hidden bg-gray-800"
                        >
                          <div className="relative aspect-video">
                            <img
                              src={meal.image || "/placeholder.svg"}
                              alt={meal.name}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          <div className="p-4">
                            <h4 className="text-lg font-semibold mb-2 text-white">
                              {meal.name}
                            </h4>
                            <p className="text-gray-400 text-sm">{meal.desc}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="reviews" className="space-y-6">
              <Card className="border-gray-700 shadow-lg bg-gray-800">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-2xl text-white">
                      {t("Mijozlar sharhlari")}
                    </CardTitle>
                    <div className="flex items-center gap-2">
                      <div className="flex items-center gap-1">
                        {renderStars(Math.floor(tour.rating))}
                      </div>
                      <span className="text-2xl font-bold text-white">
                        {tour.rating}
                      </span>
                      <span className="text-gray-400">
                        ({tour.ticket_comments.length} {t("sharh")})
                      </span>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-6">
                  {tour.ticket_comments.map((comment, idx) => (
                    <div
                      key={idx}
                      className="border-b border-gray-700 pb-6 last:border-0 last:pb-0"
                    >
                      <div className="flex items-start justify-between mb-3">
                        <div>
                          <p className="font-semibold text-lg text-white">
                            {comment.user.username}
                          </p>
                          <div className="flex items-center gap-1 mt-1">
                            {renderStars(comment.rating)}
                          </div>
                        </div>
                      </div>
                      <p className="text-gray-300 leading-relaxed">
                        {comment.text}
                      </p>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>

          {/* <Card className="border-gray-700 shadow-lg mt-8 bg-gray-800">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-400 mb-1">{t("Tur firmasi")}</p>
                <p className="text-xl font-semibold text-white">
                  {t("Firma ID")}: {tour.travel_agency_id}
                </p>
              </div>
              <Button
                variant="outline"
                onClick={() => router(`/agencies/${tour.id}`)}
                className="border-gray-700 bg-gray-800 hover:bg-gray-700 text-gray-300"
              >
                {t("Firma sahifasiga o'tish")}
              </Button>
            </div>
          </CardContent>
        </Card> */}
        </div>
      )}
    </div>
  );
}
