'use client';

import React, { useState, useEffect } from 'react';
import { 
  Heart, HeartOff, Trash2, Eye, 
  Building2, BookOpen, Filter, Search,
  ExternalLink, X, Calendar, DollarSign,
  MapPin, Clock, ChevronDown, Star,
  GraduationCap
} from 'lucide-react';
import Heading from '../../atoms/Heading';
import Link from 'next/link';
import Image from 'next/image';
import { useWishlist } from '../../../context/WishlistContext';

const ConsultantWishlist = () => {
  const { wishlist, removeFromWishlist } = useWishlist();
  
  const [filter, setFilter] = useState('all'); // 'all', 'courses', 'universities'
  const [searchTerm, setSearchTerm] = useState('');
  const [isFilterOpen, setIsFilterOpen] = useState(false);

  // Process wishlist items
  const processedWishlist = wishlist.map(item => {
    // Determine item type
    const isCourse = item.type?.toLowerCase() === 'course' || item.course_id;
    const isUniversity = item.type?.toLowerCase() === 'university' || item.university_id;
    
    return {
      ...item,
      isCourse,
      isUniversity,
      displayType: isCourse ? 'Course' : isUniversity ? 'University' : 'Unknown',
      icon: isCourse ? BookOpen : isUniversity ? Building2 : Building2,
      color: isCourse ? 'blue' : isUniversity ? 'purple' : 'gray'
    };
  });

  // Filter logic
  const filteredWishlist = processedWishlist.filter(item => {
    // Filter by type
    if (filter === 'courses' && !item.isCourse) return false;
    if (filter === 'universities' && !item.isUniversity) return false;
    
    // Search term
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      const name = item.title || item.name || '';
      const university = item.university_name || '';
      
      return (
        name.toLowerCase().includes(searchLower) ||
        university.toLowerCase().includes(searchLower)
      );
    }
    
    return true;
  });

  // Counts
  const courseCount = processedWishlist.filter(item => item.isCourse).length;
  const universityCount = processedWishlist.filter(item => item.isUniversity).length;

  const handleRemove = async (item) => {
    try {
      await removeFromWishlist(item);
    } catch (error) {
      console.error('Error removing item:', error);
    }
  };

  const clearSearch = () => {
    setSearchTerm('');
    setFilter('all');
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white py-8">
      <div className="max-w-7xl mx-auto px-4">
        {/* Header */}
        <div className="mb-10">
          <div className="flex items-center justify-between gap-6 mb-6">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-gradient-to-r from-[#0B6D76] to-teal-600 rounded-xl shadow-lg">
                <Heart size={28} className="text-white" />
              </div>
              <div>
                <Heading level={5} className="text-3xl font-bold text-gray-900">
                  Saved Items
                </Heading>
                <p className="text-gray-600 mt-2">
                  Your collection of favorite courses and universities
                </p>
              </div>
            </div>
            
            {/* Stats */}
            <div className="hidden md:flex items-center gap-4">
              <div className="px-4 py-2 bg-white rounded-xl border border-gray-200 shadow-sm">
                <div className="flex items-center gap-2">
                  <BookOpen size={16} className="text-blue-500" />
                  <span className="font-medium text-gray-700">{courseCount}</span>
                  <span className="text-gray-500">Courses</span>
                </div>
              </div>
              
              <div className="px-4 py-2 bg-white rounded-xl border border-gray-200 shadow-sm">
                <div className="flex items-center gap-2">
                  <Building2 size={16} className="text-purple-500" />
                  <span className="font-medium text-gray-700">{universityCount}</span>
                  <span className="text-gray-500">Universities</span>
                </div>
              </div>
            </div>
          </div>

          {/* Filters Bar */}
          <div className="bg-white rounded-2xl shadow-lg p-5 border border-gray-200 mb-6">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              {/* Search */}
              <div className="relative flex-1 max-w-lg">
                <Search size={20} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search saved items..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-10 py-2.5 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6D76] focus:border-[#0B6D76] text-gray-700"
                />
                {searchTerm && (
                  <button
                    onClick={() => setSearchTerm('')}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    <X size={18} />
                  </button>
                )}
              </div>

              {/* Filter Buttons */}
              <div className="flex flex-wrap gap-2">
                <button
                  onClick={() => setFilter('all')}
                  className={`px-4 py-2.5 rounded-xl transition-all flex items-center gap-2 ${
                    filter === 'all'
                      ? 'bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  <Heart size={16} />
                  All Items ({wishlist.length})
                </button>
                
                <button
                  onClick={() => setFilter('courses')}
                  className={`px-4 py-2.5 rounded-xl transition-all flex items-center gap-2 ${
                    filter === 'courses'
                      ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white'
                      : 'bg-blue-50 text-blue-700 hover:bg-blue-100'
                  }`}
                >
                  <BookOpen size={16} />
                  Courses ({courseCount})
                </button>
                
                <button
                  onClick={() => setFilter('universities')}
                  className={`px-4 py-2.5 rounded-xl transition-all flex items-center gap-2 ${
                    filter === 'universities'
                      ? 'bg-gradient-to-r from-purple-500 to-purple-600 text-white'
                      : 'bg-purple-50 text-purple-700 hover:bg-purple-100'
                  }`}
                >
                  <Building2 size={16} />
                  Universities ({universityCount})
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Content */}
        {filteredWishlist.length === 0 ? (
          <div className="bg-white rounded-2xl shadow-lg p-12 text-center">
            <div className="max-w-md mx-auto">
              <div className="w-20 h-20 bg-gradient-to-r from-gray-100 to-gray-200 rounded-full flex items-center justify-center mx-auto mb-6">
                <HeartOff size={32} className="text-gray-400" />
              </div>
              <h3 className="text-2xl font-bold text-gray-900 mb-3">
                {searchTerm || filter !== 'all'
                  ? 'No matching items found'
                  : 'Your wishlist is empty'}
              </h3>
              <p className="text-gray-600 mb-8">
                {searchTerm || filter !== 'all'
                  ? 'Try adjusting your search or filter criteria'
                  : 'Start saving courses and universities you\'re interested in'}
              </p>
              <button
                onClick={clearSearch}
                className="px-6 py-3 bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white font-semibold rounded-xl hover:shadow-lg transition-all hover:scale-105"
              >
                {searchTerm || filter !== 'all' ? 'Clear Filters' : '0 Items'}
              </button>
            </div>
          </div>
        ) : (
          <>
            {/* Results Header */}
            <div className="flex items-center justify-between mb-6">
              <div>
                <h3 className="text-xl font-bold text-gray-900">
                  {filteredWishlist.length} {filteredWishlist.length === 1 ? 'Item' : 'Items'}
                </h3>
                <p className="text-gray-500 text-sm">
                  Showing {filter === 'all' ? 'all' : filter} items
                </p>
              </div>
              
              <div className="text-sm text-gray-500">
                Sorted by recently added
              </div>
            </div>

            {/* Wishlist Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredWishlist.map((item, index) => (
                <div
                  key={item.key || index}
                  className="group relative bg-white rounded-2xl shadow-lg border border-gray-200 transition-all hover:shadow-xl hover:-translate-y-1"
                >
                  {/* Type Badge */}
                  <div className="absolute top-4 right-4 z-10">
                    <span className={`px-3 py-1.5 rounded-full text-xs font-bold ${
                      item.isCourse
                        ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white'
                        : 'bg-gradient-to-r from-purple-500 to-purple-600 text-white'
                    }`}>
                      {item.displayType}
                    </span>
                  </div>

                  {/* Image */}
                  <div className="relative h-48 w-full overflow-hidden rounded-t-2xl">
                    <Image
                      src={item.imageSrc || (item.isCourse ? '/assets/default-course.png' : '/assets/default-university.png')}
                      alt={item.title || item.name}
                      fill
                      className="object-cover transition-transform group-hover:scale-105"
                      onError={(e) => {
                        e.target.src = item.isCourse ? '/assets/default-course.png' : '/assets/default-university.png';
                      }}
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/30 to-transparent" />
                  </div>

                  {/* Content */}
                  <div className="p-5">
                    {/* Title */}
                    <h3 className="text-lg font-bold text-gray-900 mb-2 line-clamp-1">
                      {item.title || item.name}
                    </h3>
                    
                    {/* University Info */}
                    {item.university_name && (
                      <div className="flex items-center gap-2 mb-3">
                        <Building2 size={14} className="text-gray-400" />
                        <span className="text-sm text-gray-600">
                          {item.university_name}
                        </span>
                      </div>
                    )}
                    
                    {/* Subtitle */}
                    {item.subtitle && (
                      <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                        {item.subtitle}
                      </p>
                    )}

                    {/* Actions */}
                    <div className="flex items-center justify-between pt-4 border-t border-gray-100">
                      <Link href={item.slug ? `/university/${item.slug}` : item.id ? `/courses/${item.id}` : '#'}>
                        <button className="px-4 py-2 bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white rounded-xl hover:shadow-md transition-all flex items-center gap-2">
                          <Eye size={16} />
                          View Details
                        </button>
                      </Link>
                      
                      <button
                        onClick={() => handleRemove(item)}
                        className="p-2 text-gray-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-colors"
                        title="Remove from wishlist"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* Footer */}
            <div className="mt-8 flex items-center justify-between">
              <div className="text-sm text-gray-500">
                {filteredWishlist.length} of {wishlist.length} items shown
              </div>
              
              {searchTerm && (
                <button
                  onClick={clearSearch}
                  className="text-sm text-[#0B6D76] hover:text-teal-700 font-medium"
                >
                  Clear search & filters
                </button>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default ConsultantWishlist;