'use client';

import React, { useEffect, useState } from 'react';
import { 
  FiHeart, 
  FiFileText, 
  FiBell, 
  FiTrendingUp, 
  FiUsers, 
  FiSearch,
  FiTarget,
  FiCalendar,
  FiDollarSign,
  FiActivity
} from 'react-icons/fi';
import { 
  MdOutlineSchool, 
  MdOutlineVerified, 
  MdOutlineInsights,
  MdOutlineRocketLaunch
} from 'react-icons/md';
import { HiOutlineChartBar } from 'react-icons/hi';
import { useUserStore } from '../../../../store/useUserStore';
import { useWishlist } from '../../../context/WishlistContext';
import { motion } from 'framer-motion';

const ConsultantDashboardHome = () => {
  const { user } = useUserStore();
  const { wishlist } = useWishlist();
  const [wishlistCount, setWishlistCount] = useState(0);
  const [stats, setStats] = useState({
    total_students: 0,
    active_students: 0,
    total_notifications: 0,
    success_rate: '0%',
    unread_notifications: 0,
    recent_activity: []
  });
  const [loading, setLoading] = useState(true);

  // Profile status
  const profileStatus = user?.consultant_profile?.profile_status || 'incomplete';
  const isProfileApproved = profileStatus === 'approved';
  const isProfilePending = profileStatus === 'pending';

  // Fetch wishlist count
  useEffect(() => {
    const fetchWishlist = async () => {
      try {
        const res = await fetch('/api/frontend/wishlist', { method: "GET" });
        if (!res.ok) return;
        const data = await res.json();
        setWishlistCount(data.data.length);
      } catch (error) {
        console.error('Error fetching wishlist:', error);
      }
    };
    fetchWishlist();
  }, []);

  // Fetch consultant statistics
  useEffect(() => {
    const fetchStats = async () => {
      setLoading(true);
      try {
        if (!user?.id) return;
        
        const res = await fetch(`/api/frontend/consultant/consultantdashboard/stats?consultant_id=${user.id}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          }
        });
        
        if (res.ok) {
          const data = await res.json();
          if (data.success) {
            setStats(data.data);
          }
        }
      } catch (error) {
        console.error('Error fetching stats:', error);
      } finally {
        setLoading(false);
      }
    };
    
    if (user?.id) {
      fetchStats();
    }
  }, [user?.id]);

  // Keep wishlist count in sync
  useEffect(() => {
    setWishlistCount(Array.isArray(wishlist) ? wishlist.length : 0);
  }, [wishlist]);

  // Stats cards with different themes
  const statCards = [
    {
      label: 'Total Students',
      count: stats.total_students,
      icon: <FiFileText className="text-2xl" />,
      color: 'from-blue-500 to-cyan-500',
      bgColor: 'bg-gradient-to-br from-blue-50 to-cyan-50',
      borderColor: 'border-blue-200',
      description: 'All registered students'
    },
    {
      label: 'Unread Notifications',
      count: stats.unread_notifications,
      icon: <FiBell className="text-2xl" />,
      color: 'from-orange-500 to-red-500',
      bgColor: 'bg-gradient-to-br from-orange-50 to-red-50',
      borderColor: 'border-orange-200',
      description: 'Pending notifications'
    },
    {
      label: 'Active Students',
      count: stats.active_students,
      icon: <FiUsers className="text-2xl" />,
      color: 'from-purple-500 to-violet-500',
      bgColor: 'bg-gradient-to-br from-purple-50 to-violet-50',
      borderColor: 'border-purple-200',
      description: 'Students with progress'
    },
    {
      label: 'Success Rate',
      count: stats.success_rate,
      icon: <FiTrendingUp className="text-2xl" />,
      color: 'from-emerald-500 to-green-500',
      bgColor: 'bg-gradient-to-br from-emerald-50 to-green-50',
      borderColor: 'border-emerald-200',
      description: 'Case completion rate'
    }
  ];

  // Status indicator
  const getStatusBadge = () => {
    const statusConfig = {
      approved: {
        bg: 'bg-gradient-to-r from-emerald-500 to-green-600',
        text: 'text-white',
        icon: <MdOutlineVerified className="text-lg" />,
        label: '✓ Verified Consultant'
      },
      pending: {
        bg: 'bg-gradient-to-r from-amber-500 to-orange-500',
        text: 'text-white',
        icon: <FiActivity className="text-lg animate-pulse" />,
        label: '⏳ Under Review'
      },
      incomplete: {
        bg: 'bg-gradient-to-r from-blue-500 to-cyan-600',
        text: 'text-white',
        icon: <MdOutlineRocketLaunch className="text-lg" />,
        label: '📝 Complete Profile'
      },
      rejected: {
        bg: 'bg-gradient-to-r from-rose-500 to-pink-600',
        text: 'text-white',
        icon: <FiTarget className="text-lg" />,
        label: '⚠️ Needs Revision'
      }
    };

    const config = statusConfig[profileStatus] || statusConfig.incomplete;
    return (
      <div className={`inline-flex items-center gap-2 px-4 py-2 rounded-full ${config.bg} ${config.text} shadow-lg font-medium text-sm`}>
        {config.icon}
        <span>{config.label}</span>
      </div>
    );
  };

  // Activity items for recent activity
  const activityItems = stats.recent_activity.map(activity => ({
    id: activity.id,
    title: activity.title || `New ${activity.type}`,
    message: activity.message || 'New notification',
    time: activity.time_ago,
    isUnread: !activity.is_read,
    icon: getActivityIcon(activity.type)
  }));

  return (
    <div className="space-y-8">

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {statCards.map((card, index) => (
          <motion.div
            key={index}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: index * 0.1 }}
            className={`${card.bgColor} rounded-2xl p-5 border ${card.borderColor} shadow-sm hover:shadow-md transition-all duration-300 group`}
          >
            <div className="flex items-center justify-between mb-4">
              <div className={`p-3 rounded-xl bg-gradient-to-r ${card.color} shadow-md`}>
                <div className="text-white">{card.icon}</div>
              </div>
              <div className="text-sm font-medium text-gray-500">
                {card.description}
              </div>
            </div>
            
            <div className="space-y-1">
              <h3 className="text-3xl font-bold text-gray-900 group-hover:text-gray-800 transition-colors">
                {card.count}
              </h3>
              <p className="text-gray-600 font-medium">{card.label}</p>
            </div>
            
            <div className="mt-4 pt-4 border-t border-gray-200/50">
              <div className="flex items-center text-xs text-gray-500">
                <FiActivity className="mr-1" />
                <span>Updated today</span>
              </div>
            </div>
          </motion.div>
        ))}
      </div>

      {/* Recent Activity Section */}
      {stats.recent_activity.length > 0 && (
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white rounded-2xl border border-gray-200 shadow-sm"
        >
          <div className="p-6 border-b border-gray-200">
            <h3 className="text-xl font-bold text-gray-900 flex items-center gap-2">
              <FiBell className="text-blue-500" />
              Recent Activity
            </h3>
          </div>
          <div className="divide-y divide-gray-100">
            {activityItems.map((activity, index) => (
              <div key={activity.id || index} className="p-4 hover:bg-gray-50 transition-colors">
                <div className="flex items-start gap-3">
                  <div className={`p-2 rounded-lg ${activity.isUnread ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-600'}`}>
                    {activity.icon}
                  </div>
                  <div className="flex-1">
                    <div className="flex justify-between items-start">
                      <h4 className={`font-medium ${activity.isUnread ? 'text-gray-900' : 'text-gray-700'}`}>
                        {activity.title}
                      </h4>
                      <span className="text-xs text-gray-500">{activity.time}</span>
                    </div>
                    <p className="text-sm text-gray-600 mt-1">{activity.message}</p>
                  </div>
                  {activity.isUnread && (
                    <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
                  )}
                </div>
              </div>
            ))}
          </div>
          {activityItems.length > 5 && (
            <div className="p-4 border-t border-gray-200 text-center">
              <button className="text-blue-600 hover:text-blue-700 font-medium text-sm">
                View all activity
              </button>
            </div>
          )}
        </motion.div>
      )}


      {/* Loading State */}
      {loading && (
        <div className="text-center py-12">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-[#0B6D76]"></div>
          <p className="mt-4 text-gray-600">Loading dashboard data...</p>
        </div>
      )}

      {/* Footer CTA */}
      {!isProfileApproved && (
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-gradient-to-r from-blue-500 to-cyan-600 rounded-2xl p-8 text-white text-center shadow-xl"
        >
          <div className="max-w-2xl mx-auto">
            <h3 className="text-2xl font-bold mb-3">Unlock Your Full Potential</h3>
            <p className="text-blue-100 mb-6">
              Complete your profile to appear in AI-powered searches, receive 3x more client inquiries, 
              and get verified consultant status.
            </p>
          </div>
        </motion.div>
      )}
    </div>
  );
};

// Helper function to get activity icon based on type - FIXED: Removed TypeScript syntax
function getActivityIcon(type) {
  switch (type?.toLowerCase()) {
    case 'student':
    case 'application':
      return <FiUsers className="text-sm" />;
    case 'notification':
    case 'message':
      return <FiBell className="text-sm" />;
    case 'update':
    case 'alert':
      return <FiActivity className="text-sm" />;
    default:
      return <FiBell className="text-sm" />;
  }
}

export default ConsultantDashboardHome;