'use client';

import { FaHeart, FaTrashAlt, FaSearch, FaGraduationCap, FaBook } from 'react-icons/fa';
import Button from '../../components/atoms/Button';
import Heading from '../../components/atoms/Heading';
import Container from '../../components/atoms/Container';
import { useWishlist } from '../../context/WishlistContext';
import Image from 'next/image';
import Link from 'next/link';
import { useState } from 'react';

const Wishlist = () => {
  const { wishlist, removeFromWishlist } = useWishlist();
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all'); // 'all', 'courses', 'universities'

  // Filter wishlist based on search and type
  const filteredWishlist = wishlist.filter(item => {
    const matchesSearch = (item.title || item.name || '').toLowerCase().includes(searchTerm.toLowerCase());
    const isCourse = item.id && !item.university_slug;
    const isUniversity = item.university_slug || item.slug;
    
    if (filterType === 'courses') return matchesSearch && isCourse;
    if (filterType === 'universities') return matchesSearch && isUniversity;
    return matchesSearch;
  });

  // Count items by type
const courseCount = wishlist.filter(item => item.type?.toLowerCase() === 'course').length;
const universityCount = wishlist.filter(item => item.type?.toLowerCase() === 'university').length;


  const getItemLink = (item) => {
    if (item.id) {
      return `/courses/${item.id}`;
    } else if (item.university_slug) {
      return `/university/${item.university_slug}`;
    } else if (item.slug) {
      return `/university/${item.slug}`;
    }
    return '/';
  };

  const getItemType = (item) => {
    if (item.id && !item.university_slug) return 'course';
    return 'university';
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
      {/* Header Section */}
      <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-16">
        <Container>
          <div className="text-center">
            <Heading level={4} className="text-4xl md:text-5xl text-white font-bold mb-4">
              ❤️ My Wishlist
            </Heading>
            <p className="text-xl opacity-90 max-w-2xl mx-auto">
              Keep track of your favorite courses and universities.
            </p>
          </div>
        </Container>
      </div>

      <Container className="py-12 -mt-8">
        {/* Stats & Search Section */}
        <div className="bg-white rounded-2xl shadow-xl p-6 mb-8">
          <div className="grid md:grid-cols-3 gap-6 mb-6">
            <div className="text-center p-4 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-lg">
              <div className="text-3xl font-bold text-[#0a306b]">{wishlist.length}</div>
              <div className="text-gray-600">Total Items</div>
            </div>
            <div className="text-center p-4 bg-gradient-to-r from-green-50 to-teal-50 rounded-lg">
              <div className="text-3xl font-bold text-[#0a306b]">{courseCount}</div>
              <div className="text-gray-600">Courses</div>
            </div>
            <div className="text-center p-4 bg-gradient-to-r from-purple-50 to-indigo-50 rounded-lg">
              <div className="text-3xl font-bold text-[#0a306b]">{universityCount}</div>
              <div className="text-gray-600">Universities</div>
            </div>
          </div>

          {/* Search and Filter */}
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 relative">
              <FaSearch className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                placeholder="Search in your wishlist..."
                className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#0B6F78]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <div className="flex gap-2">
              <Button
                className={`px-4 py-3 rounded-lg transition-all ${
                  filterType === 'all' 
                    ? 'bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white' 
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
                onClick={() => setFilterType('all')}
              >
                All
              </Button>
              <Button
                className={`px-4 py-3 rounded-lg transition-all flex items-center gap-2 ${
                  filterType === 'courses' 
                    ? 'bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white' 
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
                onClick={() => setFilterType('courses')}
              >
                <FaBook /> Courses
              </Button>
              <Button
                className={`px-4 py-3 rounded-lg transition-all flex items-center gap-2 ${
                  filterType === 'universities' 
                    ? 'bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white' 
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
                onClick={() => setFilterType('universities')}
              >
                <FaGraduationCap /> Universities
              </Button>
            </div>
          </div>
        </div>

        {/* Empty State */}
        {wishlist.length === 0 ? (
          <div className="bg-white rounded-2xl shadow-lg p-12 text-center">
            <div className="max-w-md mx-auto">
              <div className="w-24 h-24 mx-auto mb-6 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-full flex items-center justify-center">
                <FaHeart className="text-4xl text-white" />
              </div>
              <Heading level={3} className="text-2xl font-bold text-gray-800 mb-4">
                Your wishlist is empty
              </Heading>
              <p className="text-gray-600 mb-8">
                Start building your educational journey! Save courses and universities that interest you.
              </p>
              <div className="flex gap-4 justify-center">
                <Link href="/courses">
                  <Button className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white px-6 py-3 rounded-lg hover:shadow-lg transition-all">
                    Browse Courses
                  </Button>
                </Link>
                <Link href="/universities">
                  <Button className="bg-gray-100 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-200 transition-all">
                    Explore Universities
                  </Button>
                </Link>
              </div>
            </div>
          </div>
        ) : filteredWishlist.length === 0 ? (
          <div className="bg-white rounded-2xl shadow-lg p-12 text-center">
            <div className="max-w-md mx-auto">
              <FaSearch className="text-6xl text-gray-300 mx-auto mb-6" />
              <Heading level={3} className="text-2xl font-bold text-gray-800 mb-4">
                No items found
              </Heading>
              <p className="text-gray-600">
                Try adjusting your search terms or filter criteria.
              </p>
            </div>
          </div>
        ) : (
          <>
            {/* Results Count */}
            <div className="flex justify-between items-center mb-6">
              <p className="text-gray-600">
                Showing {filteredWishlist.length} of {wishlist.length} items
              </p>
              {searchTerm && (
                <Button
                  className="text-[#0B6F78] hover:text-[#0a306b]"
                  onClick={() => setSearchTerm('')}
                >
                  Clear search
                </Button>
              )}
            </div>

            {/* Wishlist Grid */}
            <div className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3">
              {filteredWishlist.map((item) => (
                <div
                  key={item.key}
                  className="group bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 border border-gray-100 overflow-hidden transform hover:-translate-y-1"
                >
                  {/* Type Badge */}
                  <div className="absolute top-4 left-4 z-10">
                    <span className={`px-3 py-1 rounded-full text-xs font-semibold ${
                      getItemType(item) === 'course' 
                        ? 'bg-blue-100 text-blue-800' 
                        : 'bg-purple-100 text-purple-800'
                    }`}>
                      {getItemType(item) === 'course' ? 'Course' : 'University'}
                    </span>
                  </div>

                  {/* Image Section */}
                  <Link href={getItemLink(item)}>
                    <div className="relative overflow-hidden cursor-pointer h-48">
                      <Image
                      src={
                        item.image && item.image.trim() !== ""
                          ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${item.image.replace(/^\/+/, "")}`
                          : getItemType(item) === "course"
                            ? "/assets/default-course.webp"
                            : "/assets/default-university.webp"
                      }
                      alt={item.title || item.name || "Image"}
                      width={800}
                      height={600}
                      className="w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-500"
                    />

                                          <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                      <div className="absolute top-3 right-3 bg-white/90 rounded-full p-2 shadow-lg backdrop-blur-sm">
                        <FaHeart className="text-red-500 text-lg" />
                      </div>
                    </div>
                  </Link>

                  {/* Content Section */}
                  <div className="p-6">
                    <Link href={getItemLink(item)}>
                      <h3 className="text-lg font-bold text-gray-800 hover:text-[#0B6F78] transition-colors line-clamp-2 mb-2">
                        {item.title || item.name}
                      </h3>
                    </Link>
                    
                    <div className="flex items-center text-sm text-gray-500 mb-3">
                      {getItemType(item) === 'course' ? (
                        <FaBook className="mr-2 text-[#0B6F78]" />
                      ) : (
                        <FaGraduationCap className="mr-2 text-[#0a306b]" />
                      )}
                      <span>{item.type || (getItemType(item) === 'course' ? 'Course' : 'University')}</span>
                    </div>

                    {item.subtitle && (
                      <p className="text-gray-600 text-sm mb-4 line-clamp-2">{item.subtitle}</p>
                    )}

                    {/* Action Button */}
                    <Button
                      className="w-full bg-gradient-to-r from-red-50 to-red-100 text-red-600 hover:from-red-100 hover:to-red-200 border border-red-200 flex items-center justify-center gap-3 py-3 rounded-lg transition-all group/btn"
                      onClick={() => removeFromWishlist(item)}
                    >
                      <FaTrashAlt className="group-hover/btn:scale-110 transition-transform" />
                      Remove from Wishlist
                    </Button>
                  </div>
                </div>
              ))}
            </div>

          </>
        )}
      </Container>
    </div>
  );
};

export default Wishlist;