import { useEffect, useState } from 'react';
import { motion } from 'motion/react';
import { Search, Star, Clock } from 'lucide-react';
import { useNavigate, useParams } from 'react-router-dom';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Card, CardContent } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Checkbox } from '../components/ui/checkbox';
import { ImageWithFallback } from '../components/figma/ImageWithFallback';
import { Layout } from '../Layout';
import { useGetAttractionFiltersQuery, useGetCustomerAttractionsQuery } from '../Redux/services/attractions.service';
import LoadingSpinner from '../components/LoadingSpinner';
interface User {
  email: string;
  name: string;
}
interface Attraction {
  id: string;
  name: string;
  description: string;
  image: string;
  location: string;
  duration: string;
  rating: number;
  price: number;
  category: string;
  hasReservation: boolean;
  reviewCount: number;
  passType: string;
}

interface AttractionsPageProps {
  onSignInClick: () => void;
  onSignOutClick?: () => void;
  user?: User | null;
}

export function AttractionsPage({
  onSignInClick,
  onSignOutClick,
  user
}: AttractionsPageProps) {

  const navigate = useNavigate();

  const [search, setSearch] = useState("");
  const [isBookingRequired, setIsBookingRequired] = useState<boolean | undefined>(undefined)
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [selectedPassType, setSelectedPassType] = useState<string | null>(null);

  const cityId = localStorage.getItem("cityId") 
  const cityName = localStorage.getItem("cityName")

  console.log(cityName)

  const { data: filterData, isLoading } = useGetAttractionFiltersQuery(cityId)
  const { data: attractions } = useGetCustomerAttractionsQuery({
    cityId, // required
    categoryId: selectedCategory, // optional
    isBookingRequired, // optional
    cardType: selectedPassType, // optional
    search, // optional
  });

  if (isLoading) {
    return (
    <LoadingSpinner/>
    );
  }

  const handleAttractionClick = (attractionId: string) => {
    navigate(`/attractions/${attractionId}`);
  };
  const handleCheckoutClick = () => {
    navigate('/checkout');
  };

  const showingFrom = 1;
  const showingTo = Math.min(12, attractions?.length);
  const totalItems = attractions?.length;

  function handlePassTypeSelection(key: string, checked: boolean) {
    if (checked) {
      setSelectedPassType(key);  // only keep the newly selected one
    } else {
      setSelectedPassType(null);  // reset if unchecked
    }
  }

  function handleCategorySelection(id: number, checked: boolean) {
    if (checked) {
      if (id === 50) {
        setIsBookingRequired(true);
        setSelectedCategory(null); // clear normal category
      } else if (id === 51) {
        setIsBookingRequired(false);
        setSelectedCategory(null); // clear normal category
      } else {
        setSelectedCategory(id);
        setIsBookingRequired(undefined); // clear booking filter
      }
    } else {
      // reset if unchecked
      if (id === 50 || id === 51) {
        setIsBookingRequired(undefined);
      } else {
        setSelectedCategory(null);
      }
    }
  }

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value)
  }

  return (
    <Layout
      activeCity="Melbourne"
      onSignInClick={onSignInClick}
      onSignOutClick={onSignOutClick}
      user={user}
    >
      <div className="container mx-auto px-4 pt-56 pb-16">
        {/* Page Header */}
        <div className="text-center mb-12">
          <h1 className="font-merchant text-2xl md:text-3xl lg:text-4xl leading-tight text-gray-900 mb-4">
            <span className="font-light">Discover</span>{' '}
            <span className="font-bold italic text-gradient-primary pr-1">{cityName}'s</span>{' '}
            <span className="font-normal">Best</span>{' '}
            <span className="font-semibold text-emphasis">Attractions</span>
          </h1>
          <p className="font-poppins text-xl leading-relaxed font-normal text-gray-600 max-w-3xl mx-auto">
            Skip the lines and explore {cityName}'s most iconic destinations with your CityCard pass
          </p>
        </div>
        {/* City Card Promotional Banner */}
        <div className="mb-8">
          <Card className="bg-gradient-to-r from-primary to-primary/80 text-white p-8 rounded-xl border-none shadow-lg overflow-hidden relative">
            <div className="flex flex-col gap-6">
              <h2 className="font-merchant text-2xl leading-tight font-bold text-white">
                Find Your Perfect Adventure
              </h2>
              {/* Search Bar and Button Container */}
              <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center">
                {/* Search Bar */}
                <div className="relative flex-1 max-w-lg">
                  <Input
                    placeholder="Search An Attraction"
                    value={search}
                    onChange={handleSearchChange}
                    className="pl-4 pr-12 h-[44px] bg-white/95 backdrop-blur-sm border-0 rounded-lg text-gray-800 placeholder:text-gray-500 font-poppins shadow-lg"
                  />
                  <Search className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-500 w-5 h-5" />
                </div>
                {/* Call-to-Action Button */}
                <Button
                  className="bg-white/90 hover:bg-white text-primary border-2 border-primary hover:border-primary/80 px-8 h-[44px] rounded-lg font-semibold transition-all duration-200 hover:scale-105 font-poppins shadow-lg"
                  onClick={handleCheckoutClick}
                >
                  Buy Now
                </Button>
              </div>
            </div>
            {/* Decorative background elements */}
            <div className="absolute top-0 right-0 w-32 h-32 bg-white/5 rounded-full -translate-y-16 translate-x-16"></div>
            <div className="absolute bottom-0 left-0 w-24 h-24 bg-white/5 rounded-full translate-y-12 -translate-x-12"></div>
          </Card>
        </div>
        <div className="flex gap-8">
          {/* Left Sidebar */}
          <div className="w-64 flex-shrink-0">
            <Card className="p-8 sticky top-32">
              <div className="space-y-6">
                {/* Search by header */}
                <div className="flex items-center gap-4">
                  <div className="h-0 w-6 border-t-[3px] border-[#2d2d2d] rotate-90"></div>
                  <h3 className="font-merchant text-[22px] text-[#2d2d2d] font-normal">Search by</h3>
                </div>
                {/* Filter categories */}
                <div className="space-y-4">
                  {filterData && filterData.categories.map((category: any) => (
                    <div key={category.id} className="flex items-center gap-3">
                      <Checkbox
                        id={String(category.id)}
                        checked={
                          category.id === 50
                            ? isBookingRequired === true
                            : category.id === 51
                              ? isBookingRequired === false
                              : selectedCategory === category.id
                        }
                        onCheckedChange={(checked: boolean) =>
                          handleCategorySelection(category.id, checked)
                        }
                        className="border-[#bebebe]"
                      />
                      <label
                        htmlFor={String(category.id)}
                        className="font-poppins text-sm text-[#414141] cursor-pointer flex-1 font-normal"
                      >
                        {category.categoryName} ({category.count})
                      </label>
                    </div>
                  ))}
                </div>

                {/* Divider */}
                <div className="border-t border-[#e5e5e5]"></div>
                {/* Pass Type header */}
                <div className="flex items-center gap-4">
                  <div className="h-0 w-6 border-t-[3px] border-[#2d2d2d] rotate-90"></div>
                  <h3 className="font-merchant text-[22px] text-[#2d2d2d] font-normal">Pass Type</h3>
                </div>
                {/* Pass Type filters */}
                <div className="space-y-4">
                  {filterData && Object.entries(filterData.passType).map(([key, count]) => (
                    <div key={key} className="flex items-center gap-3">
                      <Checkbox
                        id={key}
                        checked={selectedPassType === key}
                        onCheckedChange={(checked: boolean) =>
                          handlePassTypeSelection(key, checked as boolean)
                        }
                        className="border-[#bebebe]"
                      />
                      <label
                        htmlFor={key}
                        className="font-poppins text-sm text-[#414141] cursor-pointer flex-1 font-normal"
                      >
                        {key === "selective_pass" ? "Selective" : "Unlimited"} ({count as number})
                      </label>
                    </div>
                  ))}
                </div>

              </div>
            </Card>
          </div>
          {/* Main Content */}
          <div className="flex-1">
            {/* Header */}
            <div className="mb-8">
              <h1 className="text-[48px] font-medium text-[#2d2d2d] mb-6">Attractions in {cityName}</h1>
              {/* Results count */}
              <p className="text-[16px] text-[#414141] mb-2">
                Showing {showingFrom}-{showingTo} of {totalItems} Item(s)
              </p>
            </div>
            {/* Attractions Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 auto-rows-fr">
              {attractions && attractions.map((attraction: any) => (
                <motion.div
                  key={attraction.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3 }}
                  className="h-full"
                >
                  <Card
                    className="overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer h-full flex flex-col group hover:border-primary/20"
                    onClick={() => handleAttractionClick(attraction.id)}
                  >
                    <div className="aspect-[4/3] relative bg-gray-200 overflow-hidden">
                      <ImageWithFallback
                        src={attraction.image}
                        alt={attraction.name}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
                      />
                      {/* Pass Type Badge */}
                      <div className="absolute top-3 left-3 flex flex-col gap-2">
                        {attraction.price === 0 ? (
                          <Badge className="bg-primary text-white px-3 py-1 font-poppins font-semibold shadow-lg">
                            FREE
                          </Badge>
                        ) : attraction.cards[0].cardType.cardTypeDisplayName === "Flexi card" ? (
                          <Badge className="bg-gradient-to-r from-blue-500 to-cyan-500 text-white px-3 py-1 font-poppins font-semibold shadow-lg border-0">
                            Flexi Pass
                          </Badge>
                        ) : (
                          <Badge className="bg-gradient-to-r from-amber-500 to-orange-500 text-white px-3 py-1 font-poppins font-semibold shadow-lg border-0">
                            Unlimited Pass Exclusive
                          </Badge>
                        )}
                      </div>
                    </div>
                    <CardContent className="p-4 flex-1 flex flex-col">
                      {/* <div className="text-sm text-muted-foreground mb-2 font-medium font-poppins">
                        {attraction.location}
                      </div> */}
                      <h3 className="font-semibold text-foreground mb-3 line-clamp-2 leading-tight min-h-[2.5rem] font-poppins">
                        {attraction.title}
                      </h3>
                      {/* Pricing and Pass Info */}
                      <div className="mt-auto pt-2 space-y-3">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-1 text-sm text-muted-foreground">
                            <Clock className="w-4 h-4 text-primary" />
                            <span className="font-poppins">{attraction.durations} minutes</span>
                          </div>
                          <div className="text-right">
                            <div className="text-xs text-muted-foreground font-poppins font-normal">Normal visit price</div>
                            <div className="text-lg font-bold text-gray-400 line-through font-poppins">
                              ${attraction.ticketPriceAdult}
                            </div>
                          </div>
                        </div>
                        {/* Included with Pass CTA */}
                        <div className="bg-gradient-to-r from-primary/10 to-secondary/10 border border-primary/20 rounded-lg p-2.5">
                          <div className="flex items-center justify-between gap-2">
                            <div className="flex-1">
                              <p className="text-xs font-poppins font-semibold text-primary uppercase">
                                ✓ Included with {attraction.cards[0].cardType.cardTypeDisplayName === "Flexi card" ? 'Flexi' : 'Unlimited'} Pass
                              </p>
                              <p className="text-xs font-poppins font-normal text-gray-600 mt-0.5">
                                Save ${attraction.cards[0].adultPrice}
                              </p>
                            </div>
                            <Button
                              className="bg-primary hover:bg-primary/90 text-white font-poppins font-semibold text-xs px-4 min-h-[44px] min-w-[44px] h-[44px] whitespace-nowrap"
                              onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
                                e.stopPropagation();
                                handleCheckoutClick();
                              }}
                            >
                              Get Pass
                            </Button>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
}