'use client';

import { useEffect, useState } from 'react';
import { 
  Home, User, Calendar, Globe, FileText, 
  Heart, Lock, Bell, ChevronRight, Settings, LogOut,
  Menu, X, Sparkles, UserCircle, Shield, BookOpen
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useUserStore } from '../../../store/useUserStore'; // Adjust path as needed

import StudentDashboardHome from '../organisms/StudentDashboardHome';
import Container from '../atoms/Container';
import StudentProfile from '../organisms/StudentProfile';
import AppliedApplications from '../organisms/AppliedApplications';
import StudentWishlist from '../organisms/StudentWishlist';
import StudentPassword from '../organisms/StudentPassword';
import StudentNotifications from '../organisms/StudentNotifications';
import ForeignStudentsList from '../organisms/ForeignStudentsList';
import StudentAppointments from '../organisms/StudentAppointments';

const NewDashboard = () => {
  const [activeTab, setActiveTab] = useState('Dashboard');
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  
  const { user, setUser, isLoggedIn } = useUserStore();

  useEffect(() => {
    if (!isLoggedIn) {
      const loadUser = async () => {
        const res = await fetch('/api/frontend/check-auth', { method: 'POST' });
        if (res.ok) {
          const data = await res.json();
          setUser(data.data); // ✅ setUser called here after Google redirect
        }
      };
      loadUser();
    }
  }, [isLoggedIn, setUser]);

  // Helper function to get initials from name
  const getUserInitials = (name: string): string => {
    if (!name) return 'S';
    
    const nameParts = name.trim().split(' ');
    
    if (nameParts.length === 1) {
      return nameParts[0].substring(0, 2).toUpperCase();
    }
    
    return `${nameParts[0][0]}${nameParts[nameParts.length - 1][0]}`.toUpperCase();
  };

  const renderComponent = () => {
    switch (activeTab) {
      case 'Dashboard': return <StudentDashboardHome />;
      case 'Profile': return <StudentProfile />;
      case 'Applied List': return <AppliedApplications />;
      case 'Appointment List': return <StudentAppointments />;
      case 'Foreign Students': return <ForeignStudentsList />;
      case 'Wishlist': return <StudentWishlist />;
      case 'Password': return <StudentPassword />;
      case 'Notifications': return <StudentNotifications />;
      default: return <StudentDashboardHome />;
    }
  };

  const menuItems = [
    { 
      name: 'Dashboard', 
      icon: <Home size={22} />, 
      color: 'text-blue-500',
      bgColor: 'bg-blue-500/10',
    },
    { 
      name: 'Profile', 
      icon: <UserCircle size={22} />, 
      color: 'text-emerald-500',
      bgColor: 'bg-emerald-500/10',
    },
    { 
      name: 'Appointment List', 
      icon: <Calendar size={22} />, 
      color: 'text-purple-500',
      bgColor: 'bg-purple-500/10',
    },
    { 
      name: 'Foreign Students', 
      icon: <Globe size={22} />, 
      color: 'text-amber-500',
      bgColor: 'bg-amber-500/10',
    },
    { 
      name: 'Applied List', 
      icon: <FileText size={22} />, 
      color: 'text-indigo-500',
      bgColor: 'bg-indigo-500/10',
    },
    { 
      name: 'Wishlist', 
      icon: <Heart size={22} />, 
      color: 'text-rose-500',
      bgColor: 'bg-rose-500/10',
    },
    { 
      name: 'Password', 
      icon: <Shield size={22} />, 
      color: 'text-cyan-500',
      bgColor: 'bg-cyan-500/10',
    },
    { 
      name: 'Notifications', 
      icon: <Bell size={22} />, 
      color: 'text-orange-500',
      bgColor: 'bg-orange-500/10',
      badge: '5'
    },
  ];

  const getTabDescription = () => {
    switch (activeTab) {
      case 'Dashboard': return 'Overview of your student activities and progress';
      case 'Profile': return 'Manage your personal information and settings';
      case 'Appointment List': return 'View and manage your scheduled appointments';
      case 'Foreign Students': return 'Connect with international students';
      case 'Applied List': return 'Track your submitted applications';
      case 'Wishlist': return 'Manage your saved items and favorites';
      case 'Password': return 'Update your security and password settings';
      case 'Notifications': return 'View and manage your notifications';
      default: return 'Overview of your student activities';
    }
  };

  return (
    <Container>
      <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-blue-50/20">
        {/* Mobile Menu Button */}
        <button
          onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          className="lg:hidden fixed top-6 left-6 z-50 p-3 bg-white rounded-2xl shadow-lg border border-gray-200 hover:shadow-md transition-shadow"
        >
          {mobileMenuOpen ? <X size={22} /> : <Menu size={22} />}
        </button>
        
        <div className="flex">
          {/* Sidebar - Desktop */}
          <motion.aside
            initial={false}
            animate={{ 
              width: sidebarCollapsed ? '88px' : '300px'
            }}
            className="hidden lg:flex flex-col h-screen sticky top-0
              bg-gradient-to-b from-white via-white to-gray-50/50
              border-r border-gray-200 shadow-sm transition-all duration-300 ease-in-out"
          >

            {/* User Profile */}
            {!sidebarCollapsed && (
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                className="p-6 border-b border-gray-200"
              >
                <div className="flex items-center gap-4">
                  <div className="relative">
                    <div className="w-14 h-14 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-2xl flex items-center justify-center text-white font-bold text-lg shadow-sm">
                      {getUserInitials(user?.name || 'Student User')}
                    </div>
                    <div className="absolute -bottom-1 -right-1 w-5 h-5 bg-emerald-500 rounded-full border-3 border-white shadow-sm"></div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="font-bold text-gray-800 truncate">
                      {user?.name || 'Student User'}
                    </h3>
                    <p className="text-sm text-gray-500 mt-1 truncate">Student Account</p>
                    <div className="flex items-center gap-2 mt-2">
                      <div className="w-2 h-2 bg-emerald-500 rounded-full"></div>
                      <span className="text-xs font-medium text-emerald-600">Active</span>
                    </div>
                  </div>
                </div>
              </motion.div>
            )}

            {/* Navigation Menu */}
            <nav className="flex-1 p-4 space-y-1.5 overflow-y-auto">
              {menuItems.map((item) => (
                <button
                  key={item.name}
                  onClick={() => setActiveTab(item.name)}
                  className={`w-full flex items-center gap-3 px-4 py-3.5 rounded-xl transition-all duration-200 relative group
                    ${activeTab === item.name 
                      ? 'bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-200 shadow-sm text-blue-700' 
                      : 'text-gray-700 hover:bg-gray-100 hover:shadow-sm'
                    }`}
                >
                  <div className={`p-2.5 rounded-xl ${item.color} ${item.bgColor} ${activeTab === item.name ? 'shadow-sm' : ''}`}>
                    {item.icon}
                  </div>
                  
                  {!sidebarCollapsed && (
                    <>
                      <span className="font-medium text-sm">
                        {item.name}
                      </span>
                      {item.badge && (
                        <span className={`ml-auto px-2 py-1 text-xs font-medium rounded-full 
                          ${activeTab === item.name 
                            ? 'bg-blue-100 text-blue-700' 
                            : 'bg-gray-200 text-gray-700'
                          }`}>
                          {item.badge}
                        </span>
                      )}
                    </>
                  )}

                  {/* Hover indicator */}
                  {!sidebarCollapsed && activeTab !== item.name && (
                    <div className="absolute right-3 top-1/2 transform -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <ChevronRight size={16} className="text-gray-400" />
                    </div>
                  )}

                  {/* Active tab indicator */}
                  {activeTab === item.name && !sidebarCollapsed && (
                    <motion.div 
                      layoutId="activeTab"
                      className="absolute right-3 top-1/2 transform -translate-y-1/2"
                    >
                      <ChevronRight size={16} className="text-blue-500" />
                    </motion.div>
                  )}
                </button>
              ))}
            </nav>

            {/* Sidebar Footer */}
            {!sidebarCollapsed && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="p-4 border-t border-gray-200 space-y-1.5"
              >
                <button className="w-full flex items-center gap-3 px-4 py-3.5 text-rose-600 hover:bg-rose-50 hover:shadow-sm rounded-xl transition-all duration-200">
                  <div className="p-2.5 rounded-xl bg-rose-100 text-rose-600">
                    <LogOut size={20} />
                  </div>
                  <span className="font-medium text-sm">Logout</span>
                </button>
              </motion.div>
            )}
          </motion.aside>

          {/* Mobile Sidebar Overlay */}
          {mobileMenuOpen && (
            <div 
              className="lg:hidden fixed inset-0 bg-black/40 backdrop-blur-sm z-40"
              onClick={() => setMobileMenuOpen(false)}
            />
          )}
          
          {/* Mobile Sidebar */}
          <motion.aside
            initial={{ x: -300 }}
            animate={{ x: mobileMenuOpen ? 0 : -300 }}
            className="lg:hidden fixed left-0 top-0 h-full w-80 z-50 flex flex-col
              bg-gradient-to-b from-white via-white to-gray-50/50
              border-r border-gray-200 shadow-2xl transition-transform duration-300 ease-in-out"
          >
            <div className="p-6 border-b border-gray-200">
              <div className="flex items-center gap-3">
                <div className="p-3 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-xl">
                  <Sparkles size={24} className="text-white" />
                </div>
                <div>
                  <h1 className="text-xl font-bold text-gray-800">
                    Student Portal
                  </h1>
                  <p className="text-xs text-gray-500">Dashboard</p>
                </div>
              </div>
            </div>

            <div className="p-6 border-b border-gray-200">
              <div className="flex items-center gap-4">
                <div className="relative">
                  <div className="w-14 h-14 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-2xl flex items-center justify-center text-white font-bold text-lg">
                    {getUserInitials(user?.name || 'Student User')}
                  </div>
                  <div className="absolute -bottom-1 -right-1 w-5 h-5 bg-emerald-500 rounded-full border-3 border-white"></div>
                </div>
                <div>
                  <h3 className="font-bold text-gray-800">{user?.name || 'Student User'}</h3>
                  <p className="text-sm text-gray-500 mt-1">Student Account</p>
                  <div className="flex items-center gap-2 mt-2">
                    <div className="w-2 h-2 bg-emerald-500 rounded-full"></div>
                    <span className="text-xs font-medium text-emerald-600">Active</span>
                  </div>
                </div>
              </div>
            </div>

            <nav className="flex-1 p-4 space-y-1.5 overflow-y-auto">
              {menuItems.map((item) => (
                <button
                  key={item.name}
                  onClick={() => {
                    setActiveTab(item.name);
                    setMobileMenuOpen(false);
                  }}
                  className={`w-full flex items-center gap-3 px-4 py-3.5 rounded-xl transition-all duration-200
                    ${activeTab === item.name 
                      ? 'bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-200 text-blue-700' 
                      : 'text-gray-700 hover:bg-gray-100'
                    }`}
                >
                  <div className={`p-2.5 rounded-xl ${item.color} ${item.bgColor}`}>
                    {item.icon}
                  </div>
                  <span className="font-medium text-sm">
                    {item.name}
                  </span>
                  {item.badge && (
                    <span className={`ml-auto px-2 py-1 text-xs font-medium rounded-full 
                      ${activeTab === item.name 
                        ? 'bg-blue-100 text-blue-700' 
                        : 'bg-gray-200 text-gray-700'
                      }`}>
                      {item.badge}
                    </span>
                  )}
                </button>
              ))}
            </nav>

            <div className="p-4 border-t border-gray-200 space-y-1.5">
              <button className="w-full flex items-center gap-3 px-4 py-3.5 text-gray-600 hover:bg-gray-100 rounded-xl transition-all duration-200">
                <div className="p-2.5 rounded-xl bg-gray-100">
                  <Settings size={20} />
                </div>
                <span className="font-medium text-sm">Settings</span>
              </button>
              <button className="w-full flex items-center gap-3 px-4 py-3.5 text-rose-600 hover:bg-rose-50 rounded-xl transition-all duration-200">
                <div className="p-2.5 rounded-xl bg-rose-100">
                  <LogOut size={20} />
                </div>
                <span className="font-medium text-sm">Logout</span>
              </button>
            </div>
          </motion.aside>

          {/* Main Content Area */}
          <main className={`flex-1 min-h-screen transition-all duration-300 ${sidebarCollapsed ? 'lg:pl-0' : 'lg:pl-0'}`}>
            <div className="p-4 md:p-6 lg:p-8">
              {/* Content Header */}
              <div className="mb-6 md:mb-8">
                <div className="flex items-start justify-between">
                  <div>
                    <div className="flex items-center gap-3 mb-3">
                      <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
                        {activeTab}
                      </h1>
                      {activeTab === 'Notifications' && (
                        <span className="px-3 py-1 bg-rose-100 text-rose-700 text-sm font-medium rounded-full">
                          {menuItems.find(item => item.name === 'Notifications')?.badge} New
                        </span>
                      )}
                    </div>
                    <p className="text-gray-600 text-sm md:text-base max-w-2xl">
                      {getTabDescription()}
                    </p>
                  </div>
                  
                  {/* Desktop Collapse Button */}
                  <button
                    onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
                    className="hidden lg:flex items-center gap-2 px-4 py-2.5 bg-white border border-gray-200 rounded-xl hover:shadow-sm transition-all duration-200 hover:border-gray-300"
                  >
                    <Menu size={20} className="text-gray-600" />
                    <span className="text-sm font-medium text-gray-700">
                      {sidebarCollapsed ? 'Expand Menu' : 'Collapse Menu'}
                    </span>
                  </button>
                </div>
              </div>

              {/* Content Area */}
              <AnimatePresence mode="wait">
                <motion.div
                  key={activeTab}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  transition={{ duration: 0.3 }}
                  className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden"
                >
                  <div className="p-4 md:p-6 lg:p-8">
                    {renderComponent()}
                  </div>
                </motion.div>
              </AnimatePresence>
            </div>
          </main>
        </div>
      </div>
    </Container>
  );
};

export default NewDashboard;