'use client'
import { useState, useEffect } from "react";
import {
  MapPin,
  Clock,
  Star,
  Users,
  FileText,
  Shield,
  TrendingUp,
  ChevronDown,
  Mail,
  Phone,
  Globe,
  Sparkles
} from "lucide-react";
import Link from "next/link";
import ModernCard from '../../components/shared/ModernCard';

export default function VisitVisaDetailPage({visaData}) {

  const [country, setCountry] = useState(null);
  const [visaRequirements, setVisaRequirements] = useState([]);
  const [adminVisaTypes, setAdminVisaTypes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedVisaType, setSelectedVisaType] = useState('');

  const safeImage = (url) => {
    if (!url) return '/assets/visit.webp';
    const str = url.toString();
    if (str.startsWith('/')) return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com${str}`;
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${str}`;
  };

  useEffect(() => {
    try
    {
      setLoading(true);

      if(!visaData.success){
        throw new Error(visaData.message);
      }

      if(visaData.success){
        setCountry(visaData.country_details);
        setAdminVisaTypes(visaData.visa_types)
        setVisaRequirements(visaData.visa_requirements)
        // Set default selected visa type
        if (visaData.visa_types && visaData.visa_types.length > 0) {
          setSelectedVisaType(visaData.visa_types[0].name);
        }
      } else {
        console.log(data.message);
        setError(data.message);
        router.push('/404');
      }

    } catch (error){
      console.log(error.message);
      setError(error.message);
      setLoading(false)
    } finally{
      setLoading(false);
    }
  }, [visaData]);

  const [openVisaTypeIndex, setOpenVisaTypeIndex] = useState(null);
  const [openRequirementIndex, setOpenRequirementIndex] = useState(null);

  const toggleAccordionType = (index, visaTypeName) => {
    setOpenVisaTypeIndex(openVisaTypeIndex === index ? null : index);
    setSelectedVisaType(visaTypeName);
  };

  const toggleAccordionRequirement = (index) => {
    setOpenRequirementIndex(openRequirementIndex === index ? null : index);
  };

  // Calculate discounted price
  const calculateDiscountedPrice = () => {
    if (!country) return 0;
    return country.price - (country.price * (country.discount_price / 100));
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="text-red-500 text-2xl mb-4">Error</div>
          <div className="text-gray-600">{error}</div>
        </div>
      </div>
    );
  }

  if (!country) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="text-gray-600 text-xl">Country not found</div>
        </div>
      </div>
    );
  }

  const discountedPrice = calculateDiscountedPrice();

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <section className="relative h-64 md:h-80 overflow-hidden">
        <div
          className="absolute inset-0 bg-cover bg-center bg-no-repeat"
          style={{ backgroundImage: `url('${safeImage(country.banner_image) || '/assets/default-banner.jpg'}')` }}
        >
          <div className="absolute inset-0 bg-linear-to-r from-teal-600 via-teal-600/80 to-transparent"></div>
        </div>
        <div className="relative h-full flex items-center">
          <div className="container mx-auto px-4">
            <div className="max-w-2xl text-white">
              <h1 className="text-3xl md:text-5xl font-bold mb-3">
                {country.country_name}
                <span className="block text-white/90 text-xl md:text-2xl mt-2">Visit Visa Guide</span>
              </h1>
              <p className="text-base md:text-lg opacity-90 leading-relaxed">
                {country.description || `Complete visa requirements and application process for ${country.country_name}`}
              </p>
            </div>
          </div>
        </div>
      </section>

      <div className="container mx-auto px-4 py-6 md:py-8 -mt-12 md:-mt-16 relative z-10">
        <div className="grid lg:grid-cols-4 gap-6 md:gap-8">
          {/* Main Content */}
          <div className="lg:col-span-3 space-y-6 md:space-y-8">
            {/* Rating Card */}
            <ModernCard className="bg-linear-to-r from-teal-600 to-blue-500 p-6 md:p-8 text-white">
              <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4 md:mb-6">
                <div className="flex items-center gap-4">
                  <div className="bg-white/20 p-2 md:p-3 rounded-xl">
                    <Star className="h-5 w-5 md:h-6 md:w-6 fill-white" />
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-2xl md:text-3xl font-bold">4.5</span>
                      <div className="flex gap-1">
                        {[...Array(5)].map((_, i) => (
                          <Star key={i} className="h-3 w-3 md:h-4 md:w-4 fill-yellow-400" />
                        ))}
                      </div>
                    </div>
                    <span className="text-white/80 text-xs md:text-sm">
                      Based on {country.visa_details?.[0]?.review_count || '156'} reviews
                    </span>
                  </div>
                </div>
                <div className="bg-white/20 px-3 py-1 md:px-4 md:py-2 rounded-lg text-xs md:text-sm">
                  Trusted Service
                </div>
              </div>
              <p className="text-white/90 leading-relaxed text-sm md:text-lg">
                {country.visa_details?.[0]?.visa_description || 
                  `Everything you need to know about ${country.country_name} visit visa requirements, documents, and application process.`}
              </p>
            </ModernCard>

            {/* Visa Types */}
            <ModernCard className="overflow-hidden">
              <div className="bg-linear-to-r from-teal-600 to-blue-500 p-4 md:p-6 text-white">
                <div className="flex items-center gap-3">
                  <div className="bg-white/20 p-1 md:p-2 rounded-lg">
                    <FileText className="h-4 w-4 md:h-5 md:w-5" />
                  </div>
                  <div>
                    <h2 className="text-lg md:text-xl font-bold">Visa Types & Requirements</h2>
                    <p className="text-white/80 text-xs md:text-sm">Available visa options for {country.country_name}</p>
                  </div>
                </div>
              </div>

              <div className="p-4 md:p-6 space-y-4">
                {adminVisaTypes.map((type, idx1) => {
                  const isOpen = openVisaTypeIndex === idx1;
                  const filteredRequirements = visaRequirements.filter(req => req.visa_type_id === type.id);

                  return (
                    <div key={idx1} className="border-2 border-gray-100 rounded-xl hover:border-teal-200 transition-all duration-300">
                      <button
                        onClick={() => toggleAccordionType(idx1, type.name)}
                        className="w-full text-left flex items-center justify-between p-4 md:p-6 hover:bg-gray-50 rounded-xl"
                      >
                        <div className="flex items-center gap-3 md:gap-4">
                          <div className="bg-linear-to-r from-teal-600 to-blue-500 p-1 md:p-2 rounded-lg">
                            <FileText className="h-4 w-4 md:h-5 md:w-5 text-white" />
                          </div>
                          <h3 className="font-semibold text-base md:text-lg text-gray-800">{type.name}</h3>
                        </div>
                        <ChevronDown
                          className={`h-4 w-4 md:h-5 md:w-5 text-gray-500 transition-transform duration-300 ${isOpen ? 'rotate-180 text-teal-600' : ''}`}
                        />
                      </button>

                      {isOpen && (
                        <div className="px-4 md:px-6 pb-4 md:pb-6 space-y-4">
                          {filteredRequirements.map((req, idx2) => {
                            const isOpen = openRequirementIndex === idx2;
                            return (
                              <div key={idx2} className="bg-gray-50 rounded-lg overflow-hidden">
                                <button
                                  onClick={() => toggleAccordionRequirement(idx2)}
                                  className="w-full flex items-center justify-between p-3 md:p-4 text-left font-medium text-gray-800 hover:text-teal-600 text-sm md:text-base"
                                >
                                  <span className="flex items-center gap-2 md:gap-3">
                                    <div className="w-1.5 h-1.5 md:w-2 md:h-2 bg-linear-to-r from-teal-600 to-blue-500 rounded-full"></div>
                                    {req.title}
                                  </span>
                                  <ChevronDown
                                    className={`h-3 w-3 md:h-4 md:w-4 text-gray-500 transition-transform duration-300 ${isOpen ? 'rotate-180 text-teal-600' : ''}`}
                                  />
                                </button>
                                <div
                                  className={`overflow-hidden transition-all duration-300 ${isOpen ? 'max-h-[1000px] p-3 md:p-4' : 'max-h-0'}`}
                                >
                                  <div
                                    className="bg-linear-to-r from-teal-600 to-blue-500 rounded-lg p-3 md:p-4 text-white text-sm md:text-base"
                                    dangerouslySetInnerHTML={{ __html: req.description.replace(/\n/g, "<br/>") }}
                                  />
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </ModernCard>

            {/* Features Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 md:gap-6">
              {[
                { icon: Clock, title: "Fast Processing", desc: "Quick visa processing with expert guidance", color: "teal" },
                { icon: Shield, title: "Secure Process", desc: "Your documents and information are completely secure", color: "blue" },
                { icon: Users, title: "Expert Support", desc: "Dedicated team throughout your visa journey", color: "emerald" },
                { icon: TrendingUp, title: "High Success Rate", desc: "Over 95% success rate in visa approvals", color: "amber" },
              ].map((feat, i) => (
                <ModernCard key={i} className="p-4 md:p-6 hover:shadow-xl transition-shadow">
                  <div className="flex items-center gap-3 md:gap-4 mb-3 md:mb-4">
                    <div className={`p-2 md:p-3 rounded-xl bg-linear-to-r from-${feat.color}-50 to-${feat.color}-100 border border-${feat.color}-200`}>
                      <feat.icon className={`h-4 w-4 md:h-6 md:w-6 text-${feat.color}-600`} />
                    </div>
                    <h3 className="text-base md:text-lg font-semibold text-gray-800">{feat.title}</h3>
                  </div>
                  <p className="text-gray-600 leading-relaxed text-sm md:text-base">{feat.desc}</p>
                </ModernCard>
              ))}
            </div>
          </div>

          {/* Sidebar - Hidden on mobile, shown on desktop */}
          <div className="hidden lg:block space-y-6">
            {/* Pricing Card */}
            <ModernCard className="overflow-hidden">
              <div className="bg-linear-to-r from-teal-600 to-blue-500 p-6 text-white text-center">
                <MapPin className="h-8 w-8 mx-auto mb-2" />
                <h3 className="text-xl font-bold">{country.country_name}</h3>
                <p className="text-white/80">Consultation Fee</p>
              </div>

              <div className="p-6 text-center">
                {country.discount_price && (
                  <span className="inline-block bg-green-100 text-green-600 px-3 py-1 rounded-full text-sm font-medium mb-4">
                    🎉 {country.discount_price}% Discount
                  </span>
                )}
                
                <div className="mb-4">
                  <p className="text-sm text-gray-500">Discounted Fee</p>
                  <p className="text-3xl font-bold text-gray-800">
                    {country.currency} {discountedPrice.toLocaleString()}
                  </p>
                </div>
                
                {country.discount_price && (
                  <p className="text-sm text-gray-400 line-through mb-6">
                    Original: {country.currency} {country.price.toLocaleString()}
                  </p>
                )}
                
                <Link href={`/visa-apply-now/${country.slug || slug}`}>
                  <button 
                    className="w-full py-3 rounded-xl font-semibold text-white bg-linear-to-r from-teal-600 to-blue-500 hover:opacity-90 transition-all duration-300 transform hover:-translate-y-1"
                  >
                    Apply Now
                  </button>
                </Link>
              </div>
            </ModernCard>

            {/* Contact Card */}
            <ModernCard className="bg-linear-to-r from-teal-600 to-blue-500 p-6 text-white">
              <h3 className="font-bold text-lg mb-4">Need Help?</h3>
              <div className="space-y-3">
                <div className="flex items-center gap-3">
                  <Phone className="h-4 w-4" />
                  <span>+92 310 6225405</span>
                </div>
                <div className="flex items-center gap-3">
                  <Mail className="h-4 w-4" />
                  <span>info@universitiespage.com</span>
                </div>
                <div className="flex items-center gap-3">
                  <Globe className="h-4 w-4" />
                  <span>24/7 Support</span>
                </div>
              </div>
            </ModernCard>
          </div>
        </div>
      </div>

      {/* Sticky Bottom Apply Now Bar - Mobile Optimized with Visa Type */}
      <div className="fixed bottom-0 left-0 right-0 bg-white shadow-2xl border-t border-gray-200 py-3 z-50">
        <div className="container mx-auto px-4">
          <div className="flex items-center justify-between gap-3">
            {/* Visa Type and Price Info */}
            <div className="flex-1 min-w-0">
              <div className="flex flex-col">
                {/* Visa Type Name */}
                <p className="text-lg text-black font-bold truncate">
                  {country.country_name} Visit Visa
                </p>
                {/* Price Info */}
                <div className="flex items-center gap-2 mt-1">
                  {country.discount_price && (
                    <span className="bg-green-100 text-green-600 px-2 py-0.5 rounded-full text-xs font-medium whitespace-nowrap">
                      {country.discount_price}% OFF
                    </span>
                  )}
                  <div className="flex items-baseline gap-1">
                    <p className="text-lg font-bold text-gray-800 whitespace-nowrap">
                      {country.currency} {discountedPrice.toLocaleString()}
                    </p>
                    {country.discount_price && (
                      <p className="text-xs text-gray-400 line-through whitespace-nowrap">
                        {country.currency} {country.price.toLocaleString()}
                      </p>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Apply Now Button */}
            <Link href={`/visa-apply-now/${country.slug || slug}`} className="flex-shrink-0">
              <button 
                className="px-4 py-3 rounded-xl font-semibold text-white bg-linear-to-r from-teal-600 to-blue-500 hover:opacity-90 transition-all duration-300 text-sm whitespace-nowrap min-w-[100px]"
              >
                Apply Now
              </button>
            </Link>
          </div>
        </div>
      </div>

      {/* Add padding to bottom to account for sticky bar */}
      <div className="h-16 md:h-20"></div>
    </div>
  );
}