'use client';

import { useState } from 'react';
import { 
  LayoutDashboard, CalendarDays, Clock, UserCog, KeyRound,
  ChevronRight, Sparkles, Settings, LogOut, Menu, X
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

import ForeignStudentDashboardHome from '../../organisms/foreignstudent/ForeignStudentDashboardHome';
import Container from '../../atoms/Container';
import ForeignStudentAppointments from '../../organisms/foreignstudent/ForeignStudentAppointments';
import ForeignStudentProfile from '../../organisms/foreignstudent/ForeignStudentProfile';
import PasswordChange from '../../organisms/foreignstudent/PasswordChange';
import AvailabilitySchedule from '../../organisms/foreignstudent/AvailabilitySchedule';
import { useUserStore } from '../../../../store/useUserStore';

const ForeignStudentDashboard = () => {
  const [activeTab, setActiveTab] = useState('Dashboard');
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  const { user } = useUserStore();

  // Helper function to get initials from name
const getUserInitials = (name: string): string => {
  if (!name) return 'U';
  
  const nameParts = name.trim().split(' ');
  
  if (nameParts.length === 1) {
    // If only one name, return first 2 letters
    return nameParts[0].substring(0, 2).toUpperCase();
  }
  
  // Get first letter of first name and first letter of last name
  return `${nameParts[0][0]}${nameParts[nameParts.length - 1][0]}`.toUpperCase();
};
  

  const renderComponent = () => {
    switch (activeTab) {
      case 'Dashboard': return <ForeignStudentDashboardHome />;
      case 'Appointments': return <ForeignStudentAppointments />;
      case 'Availability': return <AvailabilitySchedule />;
      case 'Security': return <PasswordChange />;
      case 'Profile': return <ForeignStudentProfile />;
      default: return <ForeignStudentDashboardHome />;
    }
  };

  const menuItems = [
    { 
      name: 'Dashboard', 
      icon: <LayoutDashboard size={22} />, 
      color: 'text-blue-500',
      bgColor: 'bg-blue-500/10'
    },
    { 
      name: 'Appointments', 
      icon: <CalendarDays size={22} />, 
      color: 'text-purple-500',
      bgColor: 'bg-purple-500/10'
    },
    { 
      name: 'Availability', 
      icon: <Clock size={22} />, 
      color: 'text-emerald-500',
      bgColor: 'bg-emerald-500/10'
    },
    { 
      name: 'Profile', 
      icon: <UserCog size={22} />, 
      color: 'text-amber-500',
      bgColor: 'bg-amber-500/10'
    },
    { 
      name: 'Security', 
      icon: <KeyRound size={22} />, 
      color: 'text-rose-500',
      bgColor: 'bg-rose-500/10'
    },
  ];

  return (
    <Container>
      <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
        {/* Mobile Menu Button */}
        <button
          onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          className="lg:hidden fixed top-4 left-4 z-50 p-2 bg-white rounded-xl shadow-lg border border-gray-200"
        >
          {mobileMenuOpen ? <X size={24} /> : <Menu size={24} />}
        </button>
        
        <div className="flex">
          {/* Sidebar - Desktop */}
          <motion.aside
            initial={false}
            animate={{ 
              width: sidebarCollapsed ? '80px' : '280px'
            }}
            className="hidden lg:flex flex-col h-screen sticky top-0
              bg-white 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-12 h-12 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)}
                    </div>
                    <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-emerald-500 rounded-full border-3 border-white"></div>
                  </div>
                  <div>
                    <h3 className="font-bold text-gray-800">{user?.name}</h3>
                    <p className="text-sm text-gray-500 mt-1">{user?.role}</p>
                  </div>
                </div>
              </motion.div>
            )}

            {/* Navigation Menu */}
            <nav className="flex-1 p-4 space-y-2">
              {menuItems.map((item) => (
                <button
                  key={item.name}
                  onClick={() => setActiveTab(item.name)}
                  className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-200
                    ${activeTab === item.name 
                      ? 'bg-blue-50 border border-blue-200 text-blue-600' 
                      : 'text-gray-700 hover:bg-gray-100'
                    }`}
                >
                  <div className={`p-2 rounded-lg ${item.color} ${item.bgColor}`}>
                    {item.icon}
                  </div>
                  {!sidebarCollapsed && (
                    <span className="font-medium">
                      {item.name}
                    </span>
                  )}
                </button>
              ))}
            </nav>

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

          {/* Mobile Sidebar Overlay */}
          {mobileMenuOpen && (
            <div 
              className="lg:hidden fixed inset-0 bg-black/50 z-40"
              onClick={() => setMobileMenuOpen(false)}
            />
          )}
          
          <motion.aside
            initial={{ x: -280 }}
            animate={{ x: mobileMenuOpen ? 0 : -280 }}
            className="lg:hidden fixed left-0 top-0 h-full w-72 z-50 flex flex-col
              bg-white border-r border-gray-200
              shadow-xl transition-transform duration-300 ease-in-out"
          >
            {/* Mobile Sidebar Content - Same as desktop but without collapse */}
            <div className="p-6 border-b border-gray-200">
              <div className="flex items-center gap-3">
                <div className="p-2 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-12 h-12 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-2xl flex items-center justify-center text-white font-bold text-lg">
                    {user?.id}
                  </div>
                  <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-emerald-500 rounded-full border-3 border-white"></div>
                </div>
                <div>
                  <h3 className="font-bold text-gray-800">{user?.name}</h3>
                  <p className="text-sm text-gray-500 mt-1">{user?.role}</p>
                </div>
              </div>
            </div>

            <nav className="flex-1 p-4 space-y-2">
              {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 rounded-lg transition-all duration-200
                    ${activeTab === item.name 
                      ? 'bg-blue-50 border border-blue-200 text-blue-600' 
                      : 'text-gray-700 hover:bg-gray-100'
                    }`}
                >
                  <div className={`p-2 rounded-lg ${item.color} ${item.bgColor}`}>
                    {item.icon}
                  </div>
                  <span className="font-medium">
                    {item.name}
                  </span>
                </button>
              ))}
            </nav>

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

          {/* Main Content Area - Fixed to properly adjust with sidebar */}
          <main className={`flex-1 min-h-screen transition-all duration-300`}>
            <div className="p-4 md:p-6 lg:p-8">
              {/* Content Header */}
              <div className="mb-6 md:mb-8">
                <div className="flex items-center justify-between">
                  <div>
                    <h1 className="text-2xl md:text-3xl font-bold text-gray-800">
                      {activeTab}
                    </h1>
                    <p className="text-gray-500 mt-2 text-sm md:text-base">
                      {activeTab === 'Dashboard' && 'Welcome back! Manage your student dashboard.'}
                      {activeTab === 'Appointments' && 'View and manage all your appointments.'}
                      {activeTab === 'Availability' && 'Set your available time slots.'}
                      {activeTab === 'Profile' && 'Update your personal profile.'}
                      {activeTab === 'Security' && 'Change password and security settings.'}
                    </p>
                  </div>
                  
                  <button
                    onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
                    className="hidden lg:flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-lg hover:shadow-sm transition-all duration-200"
                  >
                    <Menu size={20} className="text-gray-600" />
                    <span className="text-sm font-medium text-gray-700">
                      {sidebarCollapsed ? 'Expand' : 'Collapse'}
                    </span>
                  </button>
                </div>
              </div>

              {/* Content Area */}
              <AnimatePresence mode="wait">
                <motion.div
                  key={activeTab}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  transition={{ duration: 0.2 }}
                  className="bg-white rounded-xl 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 ForeignStudentDashboard;