'use client';

import React, { useState, useEffect } from 'react';
import { 
  Home, User, Users, UserPlus, Heart, Lock, Bell,
  Menu, X, ChevronRight, LogOut, BarChart3, Settings,
  CheckCircle, AlertCircle, Upload, FileText, GraduationCap,
  Globe, Building, MapPin, Phone, Mail, Briefcase, Clock,
  Shield, Star, Award, TrendingUp, ChevronLeft, Search
} from 'lucide-react';
import { useUserStore } from '../../../../store/useUserStore';
import ConsultantDashboardHome from '../../organisms/consultant/ConsultantDashboardHome';
import ConsultantProfile from '../../organisms/consultant/ConsultantProfile';
import StudentApplication from '../../organisms/StudentApplication';
import NewStudentForm from '../../molecules/NewStudentForm';
import ConsultantWishlist from '../../organisms/consultant/ConsultantWishlist';
import ConsultantPassword from '../../organisms/consultant/ConsultantPassword';
import ConsultantNotification from '../../organisms/consultant/ConsultantNotification';
import { LucideIcon } from 'lucide-react';

interface MenuItem {
  name: string;
  icon: LucideIcon;
  category: 'main' | 'students' | 'settings';
  requiresApproval?: boolean;
}

interface ProfileStatusEventDetail {
  profile_status: 'incomplete' | 'pending' | 'approved' | 'rejected';
}

const ConsultantDashboard = () => {
  const { user, fetchUser, logout, isLoggedIn } = useUserStore();
  const [activeTab, setActiveTab] = useState<string>('Dashboard');
  const [isSidebarOpen, setIsSidebarOpen] = useState<boolean>(false);
  const [isMobile, setIsMobile] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  // Event listener for profile status updates
  useEffect(() => {
    const handleProfileUpdate = (event: CustomEvent<ProfileStatusEventDetail>) => {
      const { profile_status } = event.detail;
      console.log('Profile status updated to:', profile_status);
      fetchUser();
    };

    window.addEventListener('profileStatusUpdated', handleProfileUpdate as EventListener);
    return () => {
      window.removeEventListener('profileStatusUpdated', handleProfileUpdate as EventListener);
    };
  }, [fetchUser]);

  // Profile status checks
  const isProfileApproved = user?.consultant_profile?.profile_status === 'approved';
  const isProfileIncomplete = user?.consultant_profile?.profile_status === 'incomplete';
  const isProfilePending = user?.consultant_profile?.profile_status === 'pending';
  const isProfileRejected = user?.consultant_profile?.profile_status === 'rejected';

  // Fetch user data on mount
  useEffect(() => {
    const loadUserData = async () => {
      setIsLoading(true);
      try {
        await fetchUser();
      } catch (error) {
        console.error('Failed to fetch user data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    if (isLoggedIn) {
      loadUserData();
    }
  }, [fetchUser, isLoggedIn]);

  // AUTO-SHOW PROFILE PAGE if not approved
useEffect(() => {
  if (!isLoading && user) {
    // If profile is not approved, default to Profile
    if (!isProfileApproved && activeTab === 'Dashboard') {
      setActiveTab('Profile');
    }
    // If approved, keep whatever tab is active or default to Dashboard
  }
}, [isLoading, user, isProfileApproved]);

  // Check for mobile screen
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 1024);
      if (window.innerWidth >= 1024) {
        setIsSidebarOpen(false);
      }
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // Menu items configuration
  const menuItems: MenuItem[] = [
    { 
      name: 'Dashboard', 
      icon: Home,
      category: 'main',
      requiresApproval: true // Changed to true so it's hidden when not approved
    },
    { 
      name: 'Profile', 
      icon: User,
      category: 'main',
      requiresApproval: false
    },
    { 
      name: 'All Students', 
      icon: Users,
      category: 'students',
      requiresApproval: true
    },
    { 
      name: 'Add New Student', 
      icon: UserPlus,
      category: 'students',
      requiresApproval: true
    },
    { 
      name: 'Wishlist', 
      icon: Heart,
      category: 'students',
      requiresApproval: true
    },
    { 
      name: 'Notifications', 
      icon: Bell,
      category: 'settings',
      requiresApproval: true // Changed to true
    },
    { 
      name: 'Security', 
      icon: Lock,
      category: 'settings',
      requiresApproval: true // Changed to true
    },
  ];

  // Filter menu items based on approval status
  const getFilteredMenuItems = (items: MenuItem[]) => {
    if (isProfileApproved) return items;
    // Only show Profile when not approved
    return items.filter(item => item.name === 'Profile');
  };

  const mainItems = getFilteredMenuItems(menuItems.filter(item => item.category === 'main'));
  const studentItems = getFilteredMenuItems(menuItems.filter(item => item.category === 'students'));
  const settingsItems = getFilteredMenuItems(menuItems.filter(item => item.category === 'settings'));

  const handleTabClick = (tabName: string) => {
    // If not approved, only allow Profile tab
    if (!isProfileApproved && tabName !== 'Profile') {
      setActiveTab('Profile');
      if (isMobile) setIsSidebarOpen(false);
      return;
    }
    
    setActiveTab(tabName);
    if (isMobile) {
      setIsSidebarOpen(false);
    }
  };

  const renderComponent = () => {
    // Force profile page if not approved for any tab
    if (!isProfileApproved) {
      return <ConsultantProfile />;
    }

    switch (activeTab) {
      case 'Dashboard': return <ConsultantDashboardHome />;
      case 'Profile': return <ConsultantProfile />;
      case 'All Students': return <StudentApplication />;
      case 'Add New Student': return <NewStudentForm />;
      case 'Wishlist': return <ConsultantWishlist />;
      case 'Security': return <ConsultantPassword />;
      case 'Notifications': return <ConsultantNotification />;
      default: return <ConsultantDashboardHome />;
    }
  };

  // Profile status badge with visual indicator
  const renderProfileStatusBadge = () => {
    if (!user?.consultant_profile) return null;

    const status = user.consultant_profile.profile_status;
    const statusConfig = {
      'approved': { 
        bg: 'bg-gradient-to-r from-emerald-500 to-green-600', 
        text: 'text-white',
        icon: <CheckCircle size={16} className="text-white" />,
        label: '✓ Verified Consultant',
        shadow: 'shadow-emerald-200'
      },
      'pending': { 
        bg: 'bg-gradient-to-r from-amber-500 to-orange-500', 
        text: 'text-white',
        icon: <Clock size={16} className="text-white" />,
        label: '⏳ Under Review',
        shadow: 'shadow-amber-200'
      },
      'rejected': { 
        bg: 'bg-gradient-to-r from-rose-500 to-pink-600', 
        text: 'text-white',
        icon: <AlertCircle size={16} className="text-white" />,
        label: '⚠️ Needs Revision',
        shadow: 'shadow-rose-200'
      },
      'incomplete': { 
        bg: 'bg-gradient-to-r from-blue-500 to-cyan-600', 
        text: 'text-white',
        icon: <Upload size={16} className="text-white" />,
        label: '📝 Complete Profile',
        shadow: 'shadow-blue-200'
      }
    };

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.incomplete;

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

  // User stats for sidebar
  const renderUserStats = () => {
    if (!isProfileApproved) {
      return (
        <div className="mb-6 p-4 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-2xl border border-blue-200">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-cyan-600 rounded-xl flex items-center justify-center shadow-lg">
              <User size={24} className="text-white" />
            </div>
            <div className="flex-1">
              <h3 className="font-bold text-gray-900 text-lg">{user?.name || 'Consultant'}</h3>
              <p className="text-sm text-gray-600">{user?.email || 'consultant@email.com'}</p>
            </div>
          </div>
          
          <div className="space-y-3">
            <div className="bg-white rounded-xl p-3 border border-blue-100">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700">Profile Status</span>
                <span className={`text-xs font-bold px-2 py-1 rounded-full ${
                  isProfileIncomplete ? 'bg-blue-100 text-blue-700' :
                  isProfilePending ? 'bg-amber-100 text-amber-700' :
                  isProfileRejected ? 'bg-rose-100 text-rose-700' : 'bg-emerald-100 text-emerald-700'
                }`}>
                  {user?.consultant_profile?.profile_status?.toUpperCase()}
                </span>
              </div>
              <div className="text-xs text-gray-600">
                {isProfileIncomplete && 'Complete your profile to unlock all features'}
                {isProfilePending && 'Your profile is under admin review (24-48 hours)'}
                {isProfileRejected && 'Please address the feedback and resubmit'}
                {isProfileApproved && 'Your profile is live and searchable'}
              </div>
            </div>
            
            {!isProfileApproved && (
              <button
                onClick={() => handleTabClick('Profile')}
                className="w-full bg-gradient-to-r from-blue-600 to-cyan-600 text-white font-semibold py-3 rounded-xl hover:shadow-lg transition-all duration-300 flex items-center justify-center gap-2"
              >
                <Upload size={18} />
                Complete Profile Now
              </button>
            )}
          </div>
        </div>
      );
    }

    return (
      <div>
       
      </div>
    );
  };

  // Loading state
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-[#0B6D76] border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600 font-medium">Loading your dashboard...</p>
          <p className="text-gray-400 text-sm mt-2">Preparing your consultant workspace</p>
        </div>
      </div>
    );
  }

  // ================================================================
  // IF PROFILE IS NOT APPROVED - SHOW PROFILE PAGE ONLY
  // ================================================================
  if (!isProfileApproved) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
        {/* Simple Header for Profile Completion */}
        <header className="bg-white/95 backdrop-blur-lg border-b border-gray-200/80 shadow-sm">
          <div className="max-w-7xl mx-auto px-4 py-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-3">
                <div className="p-2.5 bg-gradient-to-r from-blue-500 to-cyan-600 rounded-xl shadow-lg">
                  <User size={24} className="text-white" />
                </div>
                <div>
                  <h1 className="text-xl font-bold text-gray-900">Complete Your Profile</h1>
                  <p className="text-sm text-gray-600">Finish setup to access your consultant dashboard</p>
                </div>
              </div>
              {renderProfileStatusBadge()}
            </div>
          </div>
        </header>

        {/* Profile Completion Content */}
        <main className="max-w-6xl mx-auto px-4 py-8">
          <div className="bg-white rounded-3xl shadow-lg border border-gray-200/50 p-6">
            {/* Welcome Message */}
            <div className="mb-8">
              <div className="bg-gradient-to-r from-blue-500 to-cyan-600 rounded-2xl p-6 text-white shadow-lg">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-white/20 rounded-xl">
                    <UserPlus size={28} />
                  </div>
                  <div className="flex-1">
                    <h2 className="text-2xl font-bold mb-2">Welcome, {user?.name?.split(' ')[0] || 'Consultant'}! 👋</h2>
                    <p className="text-blue-100">
                      {isProfileIncomplete && 'Please complete your profile information to start using the consultant portal.'}
                      {isProfilePending && 'Your profile is under review. You can update your information while waiting.'}
                      {isProfileRejected && 'Please update your profile based on the feedback received.'}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* Status Card */}
            <div className="mb-8">
              <div className="bg-gradient-to-r from-blue-50 to-cyan-50 rounded-2xl p-5 border border-blue-200">
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                  <div>
                    <h3 className="font-bold text-gray-900 text-lg mb-2">Profile Status</h3>
                    <div className="flex items-center gap-3">
                      <div className={`w-3 h-3 rounded-full ${
                        isProfileIncomplete ? 'bg-blue-500' :
                        isProfilePending ? 'bg-amber-500' :
                        'bg-rose-500'
                      }`}></div>
                      <p className="text-gray-700">
                        {isProfileIncomplete && 'Your profile is incomplete. Please fill all required information.'}
                        {isProfilePending && 'Your profile is under admin review (24-48 hours).'}
                        {isProfileRejected && 'Your profile needs revision. Please update based on feedback.'}
                      </p>
                    </div>
                  </div>
                  <div className="text-sm text-gray-600 bg-white px-4 py-2 rounded-xl border border-gray-200">
                    <span className="font-medium">Next Step: </span>
                    Complete all profile sections
                  </div>
                </div>
              </div>
            </div>

            {/* Profile Component */}
            <ConsultantProfile />
          </div>

          {/* Footer Note */}
          <div className="mt-6 text-center text-gray-500 text-sm">
            <p>Once your profile is approved, you will get full access to the consultant dashboard.</p>
          </div>
        </main>
      </div>
    );
  }

  // ================================================================
  // IF PROFILE IS APPROVED - SHOW FULL DASHBOARD
  // ================================================================
  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
      {/* Desktop Header */}
      <header className="hidden lg:block top-0 z-40 bg-white/95 backdrop-blur-lg border-b border-gray-200/80 shadow-sm">
        <div className="flex items-center justify-between px-8 py-4">
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-3">
              <div className="p-2.5 bg-gradient-to-r from-[#0B6D76] to-teal-600 rounded-xl shadow-lg">
                <BarChart3 size={28} className="text-white" />
              </div>
              <div>
                <h1 className="text-2xl font-bold text-gray-900">Consultant Portal</h1>
                <p className="text-sm text-gray-600">Professional Immigration Consultant Dashboard</p>
              </div>
            </div>
          </div>
          
          <div className="flex items-center space-x-6">
            {renderProfileStatusBadge()}
            
            <div className="flex items-center space-x-4 bg-white/50 rounded-2xl px-4 py-2 border border-gray-200">
              <div className="w-10 h-10 bg-gradient-to-br from-[#0B6D76] to-teal-600 rounded-xl flex items-center justify-center shadow-md">
                <span className="text-white font-bold text-sm">
                  {user?.name?.[0] || 'C'}
                </span>
              </div>
              <div className="text-left">
                <p className="text-sm font-semibold text-gray-900">{user?.name || 'John Consultant'}</p>
                <p className="text-xs text-gray-500">Verified Consultant</p>
              </div>
              <ChevronRight size={20} className="text-gray-400" />
            </div>
          </div>
        </div>
      </header>

      <div className="flex pt-0">
        {/* Sidebar - Only shown when approved */}
        <aside className="sticky top-0 left-0 h-screen z-50 translate-x-0 transition-all duration-300 ease-in-out w-72 bg-gradient-to-b from-white to-gray-50 border-r border-gray-200/80 hidden lg:block">
          <div className="h-[calc(100vh-80px)] pb-20">
            <div className="p-5">
              {/* User Stats */}
              {renderUserStats()}

              <nav className="space-y-2">
                {/* Main Navigation */}
                {mainItems.length > 0 && (
                  <div className="mb-6">
                    <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3 px-2">
                      Navigation
                    </p>
                    {mainItems.map((item) => (
                      <button
                        key={item.name}
                        onClick={() => handleTabClick(item.name)}
                        className={`
                          w-full flex items-center justify-start px-4 
                          py-3.5 rounded-2xl mb-2 transition-all duration-300
                          ${activeTab === item.name 
                            ? 'bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white shadow-lg scale-[1.02]' 
                            : 'text-gray-700 hover:bg-gray-100/80 hover:shadow-md hover:scale-[1.01]'
                          }
                        `}
                      >
                        <div className={`p-2 rounded-lg ${activeTab === item.name ? 'bg-white/20' : 'bg-gray-100'}`}>
                          {React.createElement(item.icon, {
                            size: 22,
                            className: activeTab === item.name ? 'text-white' : 'text-[#0B6D76]',
                          })}
                        </div>
                        <span className="ml-3 font-medium">{item.name}</span>
                        {activeTab === item.name && (
                          <ChevronRight size={18} className="ml-auto animate-pulse" />
                        )}
                      </button>
                    ))}
                  </div>
                )}

                {/* Student Management */}
                {studentItems.length > 0 && (
                  <div className="mb-6">
                    <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3 px-2">
                      Student Management
                    </p>
                    {studentItems.map((item) => (
                      <button
                        key={item.name}
                        onClick={() => handleTabClick(item.name)}
                        className={`
                          w-full flex items-center justify-start px-4 
                          py-3.5 rounded-2xl mb-2 transition-all duration-300
                          ${activeTab === item.name 
                            ? 'bg-gradient-to-r from-blue-600 to-cyan-600 text-white shadow-lg scale-[1.02]' 
                            : 'text-gray-700 hover:bg-blue-50/80 hover:shadow-md hover:scale-[1.01]'
                          }
                        `}
                      >
                        <div className={`p-2 rounded-lg ${activeTab === item.name ? 'bg-white/20' : 'bg-blue-100'}`}>
                          {React.createElement(item.icon, {
                            size: 22,
                            className: activeTab === item.name ? 'text-white' : 'text-blue-600',
                          })}
                        </div>
                        <span className="ml-3 font-medium">{item.name}</span>
                        {activeTab === item.name && (
                          <ChevronRight size={18} className="ml-auto animate-pulse" />
                        )}
                      </button>
                    ))}
                  </div>
                )}

                {/* Settings */}
                {settingsItems.length > 0 && (
                  <div>
                    <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3 px-2">
                      Account
                    </p>
                    {settingsItems.map((item) => (
                      <button
                        key={item.name}
                        onClick={() => handleTabClick(item.name)}
                        className={`
                          w-full flex items-center justify-start px-4 
                          py-3.5 rounded-2xl mb-2 transition-all duration-300
                          ${activeTab === item.name 
                            ? 'bg-gradient-to-r from-gray-700 to-gray-900 text-white shadow-lg scale-[1.02]' 
                            : 'text-gray-700 hover:bg-gray-100/80 hover:shadow-md hover:scale-[1.01]'
                          }
                        `}
                      >
                        <div className={`p-2 rounded-lg ${activeTab === item.name ? 'bg-white/20' : 'bg-gray-100'}`}>
                          {React.createElement(item.icon, {
                            size: 22,
                            className: activeTab === item.name ? 'text-white' : 'text-gray-600',
                          })}
                        </div>
                        <span className="ml-3 font-medium">{item.name}</span>
                        {activeTab === item.name && (
                          <ChevronRight size={18} className="ml-auto animate-pulse" />
                        )}
                      </button>
                    ))}
                  </div>
                )}
              </nav>
            </div>
          </div>
        </aside>

        {/* Main Content */}
        <main className="flex-1 lg:ml-0">
          <div className="p-4 lg:p-8 max-w-7xl mx-auto">
            {/* Dashboard Header */}
            {activeTab === 'Dashboard' && (
              <div className="mb-6 lg:mb-8">
                <div className="bg-gradient-to-r from-white to-gray-50 rounded-3xl p-5 lg:p-8 shadow-lg border border-gray-200/50">
                  <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-3">
                        <div className="p-2.5 bg-gradient-to-r from-[#0B6D76] to-teal-600 rounded-xl shadow-lg">
                          <TrendingUp size={28} className="text-white" />
                        </div>
                        <div>
                          <h1 className="text-2xl lg:text-3xl font-bold text-gray-900">Welcome back, {user?.name?.split(' ')[0] || 'Consultant'}!</h1>
                          <p className="text-gray-600 mt-2">
                            Your dashboard is fully activated. Start managing students now.
                          </p>
                        </div>
                      </div>
                      
                      {/* Quick Stats */}
                      <div className="flex flex-wrap gap-4 mt-4">
                        <div className="px-4 py-2.5 bg-white rounded-xl border border-gray-200 shadow-sm">
                          <span className="text-gray-600 text-sm">Today: </span>
                          <span className="font-bold text-gray-900">
                            {new Date().toLocaleDateString('en-US', { 
                              weekday: 'short', 
                              month: 'short', 
                              day: 'numeric' 
                            })}
                          </span>
                        </div>
                        <div className="px-4 py-2.5 bg-gradient-to-r from-emerald-500 to-green-600 text-white rounded-xl font-semibold shadow-lg">
                          ✓ Profile Verified
                        </div>
                      </div>
                    </div>
                    
                    {/* Quick Actions */}
                    <div className="flex flex-col sm:flex-row gap-3">
                      <button 
                        onClick={() => handleTabClick('Add New Student')}
                        className="px-5 py-3.5 bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white rounded-xl hover:shadow-xl transition-all hover:scale-105 font-semibold flex items-center gap-2 justify-center"
                      >
                        <UserPlus size={20} />
                        Add New Student
                      </button>
                      <button 
                        onClick={() => handleTabClick('All Students')}
                        className="px-5 py-3.5 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 transition-all font-medium flex items-center gap-2 justify-center"
                      >
                        <Users size={20} />
                        View Students
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Page Header for other tabs */}
            {activeTab !== 'Dashboard' && activeTab !== 'Profile' && (
              <div className="mb-6 lg:mb-8">
                <div className="bg-gradient-to-r from-white to-gray-50 rounded-3xl p-5 lg:p-6 shadow-lg border border-gray-200/50">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="p-3 bg-gradient-to-r from-blue-500 to-cyan-600 rounded-xl shadow-lg">
                        {React.createElement(
                          menuItems.find(item => item.name === activeTab)?.icon || Home,
                          { size: 24, className: 'text-white' }
                        )}
                      </div>
                      <div>
                        <h1 className="text-2xl lg:text-3xl font-bold text-gray-900">{activeTab}</h1>
                        <p className="text-gray-600 mt-1">
                          {activeTab === 'All Students' && 'Manage and track all student applications in one place'}
                          {activeTab === 'Add New Student' && 'Add new student information to your portfolio'}
                          {activeTab === 'Wishlist' && 'Save and organize your preferred student applications'}
                          {activeTab === 'Security' && 'Update your password and security preferences'}
                          {activeTab === 'Notifications' && 'Configure your notification settings'}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Content Area */}
            <div className="bg-white rounded-3xl shadow-lg border border-gray-200/50 overflow-hidden">
              <div className="p-4 lg:p-6">
                {renderComponent()}
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
};

export default ConsultantDashboard;