// src/app/(root)/packages/PackagesClient.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Package, 
  Filter, 
  ChevronDown,
  Star,
  Zap,
  Crown,
  Shield,
  Clock,
  CreditCard,
  ArrowRight
} from 'lucide-react';
import PackageCard from '@/app/components/Frontend/PackageCard';
import PageHero from '@/app/components/Frontend/PageHero';

interface Website {
  id: string;
  name: string;
  slug: string;
  domain: string;
  da: number;
  dr: number;
  traffic: string;
  spam_score: number;
  backlinks: number;
  link_type: string;
  base_price: number;
  sale_price: number | null;
  featured_image: string | null;
  status: string;
}

interface Package {
  id: string;
  name: string;
  slug: string;
  description: string;
  package_type: 'standard' | 'special_niche' | 'custom';
  base_price: number;
  sale_price: number | null;
  features: string[];
  is_popular: boolean;
  is_featured: boolean;
  meta_title: string | null;
  meta_description: string | null;
  schemas: unknown[];
  websites: Website[];
  created_at: string;
  updated_at: string;
}

interface PackagesClientProps {
  initialPackages: Package[];
}

export default function PackagesClient({ initialPackages }: PackagesClientProps) {
  const [packages, setPackages] = useState<Package[]>(initialPackages);
  const [filteredPackages, setFilteredPackages] = useState<Package[]>(initialPackages);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedType, setSelectedType] = useState<string>('all');
  const [isFilterOpen, setIsFilterOpen] = useState(false);

  // Define filterPackages with useCallback to prevent unnecessary re-renders
  const filterPackages = useCallback(() => {
    if (selectedType === 'all') {
      setFilteredPackages(packages);
    } else {
      setFilteredPackages(packages.filter(pkg => pkg.package_type === selectedType));
    }
  }, [packages, selectedType]);

  // Only fetch if no initial packages
  useEffect(() => {
    if (initialPackages.length === 0) {
      fetchPackages();
    }
  }, [initialPackages]);

  // Run filter when packages or selectedType changes
  useEffect(() => {
    filterPackages();
  }, [filterPackages]);

  const fetchPackages = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/frontend/allpackages');
      const data = await response.json();

      if (data.success) {
        setPackages(data.packages);
        setFilteredPackages(data.packages);
      } else {
        setError(data.error || 'Failed to fetch packages');
      }
    } catch (err) {
      setError('An error occurred while fetching packages');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // Group packages by type for display
  const standardPackages = filteredPackages.filter(pkg => pkg.package_type === 'standard');
  const specialNichePackages = filteredPackages.filter(pkg => pkg.package_type === 'special_niche');
  const customPackages = filteredPackages.filter(pkg => pkg.package_type === 'custom');

  const filterOptions = [
    { value: 'all', label: 'All Packages', icon: Package },
    { value: 'standard', label: 'Standard', icon: Zap },
    { value: 'special_niche', label: 'Special Niche', icon: Crown },
    { value: 'custom', label: 'Custom', icon: Star },
  ];

  const fadeInUp = {
    initial: { opacity: 0, y: 20 },
    animate: { opacity: 1, y: 0 },
    transition: { duration: 0.5 },
  };

  const staggerContainer = {
    animate: {
      transition: {
        staggerChildren: 0.1,
      },
    },
  };

  if (loading && packages.length === 0) {
    return (
      <div className="min-h-screen bg-linear-to-br from-slate-50 via-white to-blue-50/30">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-28 pb-12">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            <p className="mt-4 text-slate-600">Loading packages...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error && packages.length === 0) {
    return (
      <div className="min-h-screen bg-linear-to-br from-slate-50 via-white to-blue-50/30">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-28 pb-12">
          <div className="bg-red-50 rounded-2xl shadow-lg p-8 text-center">
            <p className="text-red-600">{error}</p>
            <button
              onClick={() => fetchPackages()}
              className="mt-4 px-6 py-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition-colors"
            >
              Try again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-linear-to-br from-slate-50 via-white to-blue-50/30">
      {/* Hero Section */}
      <PageHero
        title="{gradient}Guest Posting | Packages"
        subtitle="Choose the perfect package for your needs"
        description="Get high-quality backlinks from authoritative websites with our carefully curated guest posting packages."
        icon={<Package className="h-4 w-4" />}
        badge="Curated Packages"
        breadcrumbs={[
          { name: 'Home', href: '/' },
          { name: 'Packages', href: '/packages' },
        ]}
        stats={[
          { icon: <Shield className="h-4 w-4" />, label: '100% Safe Links' },
          { icon: <Clock className="h-4 w-4" />, label: 'Fast Delivery' },
          { icon: <CreditCard className="h-4 w-4" />, label: 'Secure Payment' },
        ]}
      />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">
        {/* Filter Section - Desktop */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.1 }}
          className="hidden md:block mb-12"
        >
          <div className="flex flex-wrap gap-3 justify-center">
            {filterOptions.map((option) => {
              const Icon = option.icon;
              return (
                <button
                  key={option.value}
                  onClick={() => setSelectedType(option.value)}
                  className={`group flex items-center gap-2 px-6 py-2.5 rounded-full font-medium transition-all duration-300 ${
                    selectedType === option.value
                      ? 'bg-linear-to-r from-blue-600 to-cyan-600 text-white shadow-lg shadow-blue-200'
                      : 'bg-white text-slate-700 hover:shadow-md hover:scale-105'
                  }`}
                >
                  <Icon className={`h-4 w-4 ${
                    selectedType === option.value ? 'text-white' : 'text-slate-500 group-hover:text-blue-600'
                  }`} />
                  {option.label}
                </button>
              );
            })}
          </div>
        </motion.div>

        {/* Mobile Filter Dropdown */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.1 }}
          className="md:hidden mb-8"
        >
          <div className="relative">
            <button
              onClick={() => setIsFilterOpen(!isFilterOpen)}
              className="w-full flex items-center justify-between gap-2 px-6 py-3 bg-white rounded-xl shadow-md"
            >
              <div className="flex items-center gap-2">
                <Filter className="h-4 w-4 text-blue-600" />
                <span className="font-medium text-slate-700">
                  {filterOptions.find(opt => opt.value === selectedType)?.label || 'Filter Packages'}
                </span>
              </div>
              <ChevronDown className={`h-4 w-4 text-slate-500 transition-transform duration-300 ${isFilterOpen ? 'rotate-180' : ''}`} />
            </button>
            
            <AnimatePresence>
              {isFilterOpen && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="absolute top-full left-0 right-0 mt-2 bg-white rounded-xl shadow-lg overflow-hidden z-10"
                >
                  {filterOptions.map((option) => {
                    const Icon = option.icon;
                    return (
                      <button
                        key={option.value}
                        onClick={() => {
                          setSelectedType(option.value);
                          setIsFilterOpen(false);
                        }}
                        className={`w-full flex items-center gap-3 px-6 py-3 text-left transition-colors ${
                          selectedType === option.value
                            ? 'bg-blue-50 text-blue-600'
                            : 'text-slate-700 hover:bg-slate-50'
                        }`}
                      >
                        <Icon className="h-4 w-4" />
                        {option.label}
                      </button>
                    );
                  })}
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </motion.div>

        {/* Packages Grid */}
        <AnimatePresence mode="wait">
          {filteredPackages.length === 0 ? (
            <motion.div
              key="empty"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="text-center py-12"
            >
              <div className="bg-white rounded-2xl shadow-lg p-12">
                <Package className="h-16 w-16 text-slate-400 mx-auto mb-4" />
                <p className="text-slate-500 text-lg">No packages found in this category.</p>
                <button
                  onClick={() => setSelectedType('all')}
                  className="mt-4 text-blue-600 hover:text-blue-700 font-medium"
                >
                  View all packages
                </button>
              </div>
            </motion.div>
          ) : (
            <motion.div
              key={selectedType}
              variants={staggerContainer}
              initial="initial"
              animate="animate"
              className="space-y-12"
            >
              {/* Standard Packages */}
              {standardPackages.length > 0 && (
                <div>
                  <motion.div variants={fadeInUp} className="mb-6">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-linear-to-r from-blue-600 to-cyan-600 rounded-xl">
                        <Zap className="h-5 w-5 text-white" />
                      </div>
                      <h2 className="text-2xl font-bold text-slate-800">Standard Packages</h2>
                    </div>
                    <p className="text-slate-600 mt-2 ml-11">
                      Perfect for businesses looking for quality backlinks at affordable prices
                    </p>
                  </motion.div>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    {standardPackages.map((pkg, index) => (
                      <motion.div
                        key={pkg.id}
                        variants={fadeInUp}
                        custom={index}
                      >
                        <PackageCard package={pkg} showWebsites={false} />
                      </motion.div>
                    ))}
                  </div>
                </div>
              )}

              {/* Special Niche Packages */}
              {specialNichePackages.length > 0 && (
                <div>
                  <motion.div variants={fadeInUp} className="mb-6">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-linear-to-r from-purple-600 to-pink-600 rounded-xl">
                        <Crown className="h-5 w-5 text-white" />
                      </div>
                      <h2 className="text-2xl font-bold text-slate-800">Special Niche Packages</h2>
                    </div>
                    <p className="text-slate-600 mt-2 ml-11">
                      Targeted packages for specific niches with higher authority websites
                    </p>
                  </motion.div>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    {specialNichePackages.map((pkg, index) => (
                      <motion.div
                        key={pkg.id}
                        variants={fadeInUp}
                        custom={index}
                      >
                        <PackageCard package={pkg} showWebsites={false} />
                      </motion.div>
                    ))}
                  </div>
                </div>
              )}

              {/* Custom Packages */}
              {customPackages.length > 0 && (
                <div>
                  <motion.div variants={fadeInUp} className="mb-6">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-linear-to-r from-orange-600 to-red-600 rounded-xl">
                        <Star className="h-5 w-5 text-white" />
                      </div>
                      <h2 className="text-2xl font-bold text-slate-800">Custom Packages</h2>
                    </div>
                    <p className="text-slate-600 mt-2 ml-11">
                      Tailored solutions designed to meet your specific requirements
                    </p>
                  </motion.div>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    {customPackages.map((pkg, index) => (
                      <motion.div
                        key={pkg.id}
                        variants={fadeInUp}
                        custom={index}
                      >
                        <PackageCard package={pkg} showWebsites={false} />
                      </motion.div>
                    ))}
                  </div>
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>

        {/* CTA Section */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.3 }}
          className="mt-16 bg-linear-to-r from-blue-600 to-cyan-600 rounded-2xl shadow-xl overflow-hidden"
        >
          <div className="px-6 py-12 md:px-12 text-center">
            <h3 className="text-2xl md:text-3xl font-bold text-white mb-3">
              Need a Custom Package?
            </h3>
            <p className="text-blue-100 mb-6 max-w-2xl mx-auto">
              Don`t see what you`re looking for? Contact our team to create a custom package tailored to your specific needs and budget.
            </p>
            <Link
              href="/contact"
              className="inline-flex items-center gap-2 px-6 py-3 bg-white text-blue-600 rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform hover:scale-105"
            >
              Contact Us
              <ArrowRight className="h-5 w-5" />
            </Link>
          </div>
        </motion.div>
      </div>
    </div>
  );
}