import React, { useState } from 'react';
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useThemeStore } from '../../hooks/use-theme';
import { useAuthStore } from '../../hooks/use-auth';
import { Cpu, LogOut, CheckCircle, Clock, Menu, X, Sun, Moon, ChevronRight, ChevronLeft, Settings, Globe, Video } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

export const ClientLayout: React.FC = () => {
  const { user, logout } = useAuthStore();
  const { theme, toggleTheme } = useThemeStore();
  const location = useLocation();
  const navigate = useNavigate();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);

  const dynamicNavItems = [
    { name: 'Assets', path: '/client', icon: Cpu, label: 'Asset Explorer' },
    { name: 'Ecosystem', path: '/client/ecosystem', icon: Globe, label: 'Explore More' },
    { name: 'Showcase', path: '/client/showcase', icon: Video, label: 'Featured Content' }
  ];

  // Settings Modal State
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [defaultTheme, setDefaultTheme] = useState(user?.defaultTheme || 'dark');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [settingsError, setSettingsError] = useState('');
  const [settingsSuccess, setSettingsSuccess] = useState('');

  const openSettings = () => {
    setDefaultTheme(user?.defaultTheme || 'dark');
    setPassword('');
    setConfirmPassword('');
    setSettingsError('');
    setSettingsSuccess('');
    setSettingsOpen(true);
  };

  const handleSaveSettings = async (e: React.FormEvent) => {
    e.preventDefault();
    setSettingsError('');
    setSettingsSuccess('');

    if (password && password !== confirmPassword) {
      setSettingsError("Passwords do not match");
      return;
    }

    setIsSaving(true);
    try {
      const { updateProfile } = await import('../../services/auth-api');
      const updatedUser = await updateProfile({
        defaultTheme: defaultTheme || undefined,
        password: password || undefined
      });

      // Update auth store
      useAuthStore.getState().setAuth({
        user: updatedUser,
        accessToken: useAuthStore.getState().accessToken!
      });

      if (defaultTheme) {
        useThemeStore.getState().setTheme(defaultTheme as any);
      }

      setSettingsSuccess("Profile settings updated successfully!");
      setPassword('');
      setConfirmPassword('');
      
      setTimeout(() => {
        setSettingsOpen(false);
      }, 1500);
    } catch (err: any) {
      setSettingsError(err.response?.data?.error || err.message || "Failed to update profile settings");
    } finally {
      setIsSaving(false);
    }
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };
  const isApproved = user?.onboardingStatus === 'APPROVED';

  return (
    <div className="min-h-screen flex flex-col md:flex-row bg-ink-50 text-ink-900 font-sans transition-colors duration-500 selection:bg-ink-900/10 overflow-hidden">
      
      {/* ── Desktop Sidebar ── */}
      <aside className={`hidden md:flex md:flex-col md:sticky md:top-0 md:h-screen bg-ink-0 border-r border-ink-200 shrink-0 z-20 transition-all duration-300 relative ${isCollapsed ? 'md:w-[80px]' : 'md:w-[280px]'}`}>
        
        {/* Toggle Button Floating on the Border */}
        <button
          onClick={() => setIsCollapsed(!isCollapsed)}
          className="hidden md:flex absolute top-9 -right-3 w-6 h-6 rounded-full border border-ink-200 bg-ink-0 text-ink-500 hover:text-ink-900 hover:shadow-md items-center justify-center transition-all z-30 cursor-pointer shadow-sm"
          title={isCollapsed ? "Expand Sidebar" : "Collapse Sidebar"}
        >
          {isCollapsed ? <ChevronRight className="w-3.5 h-3.5" /> : <ChevronLeft className="w-3.5 h-3.5" />}
        </button>

        {/* Branding */}
        <div className={`h-24 flex items-center border-b border-ink-200 transition-all duration-300 ${isCollapsed ? 'justify-center px-4' : 'px-8'}`}>
          <Link to="/client" className="flex items-center gap-3 shrink-0 group">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center bg-ink-0 shadow-sm border border-ink-200 group-hover:scale-105 transition-all duration-300 p-1">
              <img src="/logo.png" alt="Tech4Biz" className="w-full h-full object-contain" />
            </div>
            {!isCollapsed && (
              <div className="flex flex-col animate-fade-in">
                <span className="text-lg font-extrabold tracking-tight leading-none text-ink-900">Tech4Biz</span>
                <span className="text-[10px] font-bold uppercase tracking-widest text-ink-900 mt-1">Client Portal</span>
              </div>
            )}
          </Link>
        </div>

        {/* Navigation */}
        <nav className={`flex-1 py-8 space-y-2 overflow-y-auto transition-all duration-300 ${isCollapsed ? 'px-2' : 'px-4'}`}>
          {dynamicNavItems.map(item => {
            const Icon = item.icon;
            const isActive = location.pathname === item.path;
            return (
              <Link
                key={item.path}
                to={item.path}
                className={`flex items-center gap-3 py-3 rounded-xl transition-all duration-300 font-semibold tracking-wide text-sm group relative ${
                  isCollapsed ? 'justify-center px-0' : 'px-4'
                } ${
                  isActive 
                  ? 'bg-ink-100 text-ink-900 border border-ink-300 shadow-sm' 
                  : 'text-ink-500 hover:text-ink-900 hover:bg-ink-100'
                }`}
                title={isCollapsed ? item.label : undefined}
              >
                <Icon className={`w-5 h-5 transition-transform group-hover:scale-110 ${isActive ? 'text-ink-900' : 'text-ink-400 group-hover:text-ink-900'}`} />
                {!isCollapsed && <span>{item.label}</span>}
                {!isCollapsed && isActive && <ChevronRight className="w-4 h-4 ml-auto opacity-50" />}
              </Link>
            );
          })}
          
          <button
            onClick={openSettings}
            className={`w-full flex items-center gap-3 py-3 rounded-xl transition-all duration-300 font-semibold tracking-wide text-sm group relative cursor-pointer ${
              isCollapsed ? 'justify-center px-0' : 'px-4'
            } text-ink-500 hover:text-ink-900 hover:bg-ink-100`}
            title={isCollapsed ? 'Profile Settings' : undefined}
          >
            <Settings className={`w-5 h-5 transition-transform group-hover:scale-110 ${settingsOpen ? 'text-ink-900' : 'text-ink-400 group-hover:text-ink-900'}`} />
            {!isCollapsed && <span>Profile Settings</span>}
          </button>
        </nav>

        {/* Footer */}
        <div className={`border-t border-ink-200 bg-ink-50 transition-all duration-300 ${isCollapsed ? 'p-3' : 'p-5'}`}>
          <div className={`flex items-center mb-4 transition-all duration-300 ${isCollapsed ? 'justify-center' : 'justify-between'}`}>
            {!isCollapsed && <p className="text-[10px] font-bold text-ink-400 uppercase tracking-widest">Appearance</p>}
            <button
              onClick={toggleTheme}
              className="p-2 rounded-lg bg-ink-0 border border-ink-200 text-ink-500 hover:text-ink-900 hover:shadow-sm transition-all group cursor-pointer"
            >
              {theme === 'dark' ? <Sun className="w-4 h-4 group-hover:rotate-90 transition-transform" /> : <Moon className="w-4 h-4 group-hover:-rotate-12 transition-transform" />}
            </button>
          </div>
          
          {!isCollapsed ? (
            <div className="flex flex-col gap-2 p-4 rounded-2xl bg-ink-0 border border-ink-200 mb-4 shadow-sm">
              <div className="flex items-center justify-between mb-1">
                <span className="text-[10px] font-bold uppercase tracking-widest text-ink-400">Status</span>
                <div className={`flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold border ${isApproved ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20' : 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20'}`}>
                  {isApproved ? <CheckCircle className="w-3 h-3" /> : <Clock className="w-3 h-3" />}
                  {isApproved ? 'Verified' : 'Pending'}
                </div>
              </div>
              <p className="text-xs font-bold text-ink-900 truncate" title={user?.email || ''}>{user?.email}</p>
            </div>
          ) : (
            <div className="w-9 h-9 rounded-full bg-ink-900 flex items-center justify-center text-ink-0 font-bold shadow-sm mx-auto mb-4 animate-fade-in relative" title={user?.email || ''}>
              {user?.email?.charAt(0).toUpperCase()}
              <span className={`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border border-ink-0 ${isApproved ? 'bg-emerald-500' : 'bg-amber-500'}`} />
            </div>
          )}
          
          {/* Profile Settings button removed from here */}

          <button
            onClick={handleLogout}
            className={`w-full flex items-center justify-center gap-2 rounded-xl text-sm font-bold tracking-wide text-red-650 hover:bg-red-500/10 transition-colors border border-transparent hover:border-red-200 cursor-pointer ${isCollapsed ? 'py-2 px-0' : 'px-4 py-2.5'}`}
            title={isCollapsed ? "Sign Out" : undefined}
          >
            <LogOut className="w-4 h-4" />
            {!isCollapsed && <span>Sign Out</span>}
          </button>
        </div>
      </aside>      {/* ── Main Content Area ── */}
      <main className="flex-1 flex flex-col relative w-full h-screen overflow-hidden bg-ink-50">
        
        {/* Ambient Glow */}
        <div className="fixed top-0 right-0 w-[500px] h-[500px] bg-ink-900/5 rounded-full blur-[150px] pointer-events-none -z-10" />
 
        {/* Mobile Header */}
        <header className="md:hidden sticky top-0 z-40 h-16 flex items-center justify-between px-4 bg-ink-0 border-b border-ink-200 shadow-sm shrink-0">
          <Link to="/client" className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center bg-ink-0 border border-ink-200 p-1 shadow-sm">
              <img src="/logo.png" alt="Tech4Biz" className="w-full h-full object-contain" />
            </div>
            <span className="text-sm font-extrabold tracking-tight text-ink-900">Tech4Biz</span>
          </Link>
          <button onClick={() => setMobileOpen(true)} className="p-2 rounded-lg border border-ink-200 text-ink-600">
            <Menu className="w-5 h-5" />
          </button>
        </header>
 
        {/* Mobile Menu Drawer */}
        <AnimatePresence>
          {mobileOpen && (
            <>
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => setMobileOpen(false)} className="fixed inset-0 bg-ink-900/40 backdrop-blur-sm z-50 md:hidden" />
              <motion.div initial={{ x: '100%' }} animate={{ x: 0 }} exit={{ x: '100%' }} transition={{ type: 'spring', damping: 25, stiffness: 200 }} className="fixed right-0 top-0 bottom-0 w-72 bg-ink-0 shadow-2xl z-50 border-l border-ink-200 flex flex-col md:hidden">
                <div className="p-4 border-b border-ink-200 flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-6 h-6 rounded-md flex items-center justify-center bg-ink-0 border border-ink-200 p-0.5 shadow-sm">
                      <img src="/logo.png" alt="Tech4Biz" className="w-full h-full object-contain" />
                    </div>
                    <span className="font-extrabold text-ink-900 text-sm">Tech4Biz</span>
                  </div>
                  <button onClick={() => setMobileOpen(false)} className="p-2 rounded-lg bg-ink-100">
                    <X className="w-4 h-4" />
                  </button>
                </div>
                <nav className="flex-1 overflow-y-auto p-4 space-y-2">
                  {dynamicNavItems.map(item => (
                    <Link key={item.path} to={item.path} onClick={() => setMobileOpen(false)} className={`flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold ${location.pathname === item.path ? 'bg-ink-100 text-ink-900 border border-ink-300' : 'text-ink-650'}`}>
                      <item.icon className="w-5 h-5" />
                      {item.label}
                    </Link>
                  ))}
                  <button
                    onClick={() => { setMobileOpen(false); openSettings(); }}
                    className="flex items-center gap-3 w-full px-4 py-3 rounded-xl text-sm font-semibold text-ink-650 hover:bg-ink-100 cursor-pointer animate-fade-in"
                  >
                    <Settings className="w-5 h-5 text-ink-400" />
                    Profile Settings
                  </button>
                </nav>
                <div className="p-4 border-t border-ink-200 space-y-4">
                  <button onClick={toggleTheme} className="flex items-center justify-between w-full p-3 rounded-xl bg-ink-50 border border-ink-200 text-sm font-bold text-ink-650">
                    Theme {theme === 'dark' ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
                  </button>
                  <button onClick={() => { setMobileOpen(false); handleLogout(); }} className="w-full py-3 rounded-xl bg-red-500/10 text-red-600 font-bold text-sm">Sign Out</button>
                </div>
              </motion.div>
            </>
          )}
        </AnimatePresence>
 
        <div className="flex-1 w-full max-w-[1600px] px-4 py-4 md:px-8 mx-auto relative z-10 overflow-hidden flex flex-col min-h-0">
          <Outlet />
        </div>
 
        {/* Footer */}
        <footer className="border-t border-ink-200 bg-ink-0/50 backdrop-blur-md shrink-0">
          <div className="max-w-[1600px] mx-auto px-4 md:px-8 py-3 flex flex-col md:flex-row justify-between items-center gap-4 text-xs font-medium text-ink-500">
            <p>© 2026 Tech4Biz Solutions Inc. All rights reserved.</p>
            <div className="flex gap-6">
              <span className="hover:text-ink-900 cursor-pointer transition-colors">Security</span>
              <span className="hover:text-ink-900 cursor-pointer transition-colors">Terms</span>
            </div>
          </div>
        </footer>
      </main>

      {/* Settings Modal */}
      <AnimatePresence>
        {settingsOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => !isSaving && setSettingsOpen(false)}
              className="fixed inset-0 bg-ink-900/60 backdrop-blur-md"
            />
            
            {/* Modal Body */}
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="relative w-full max-w-xl bg-ink-0 border border-ink-200 rounded-3xl shadow-2xl p-6 md:p-8 z-50 overflow-y-auto max-h-[90vh] text-ink-900 transition-colors duration-300"
            >
              <div className="flex justify-between items-start mb-6">
                <div>
                  <h3 className="text-xl font-black tracking-tight text-ink-900">Profile Settings</h3>
                  <p className="text-xs font-bold text-ink-500 mt-1">Refine your profile parameters and manage credentials.</p>
                </div>
                <button 
                  onClick={() => setSettingsOpen(false)}
                  disabled={isSaving}
                  className="p-1.5 rounded-lg bg-ink-50 border border-ink-200 text-ink-500 hover:text-ink-900 disabled:opacity-50 cursor-pointer"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              {settingsError && (
                <div className="mb-4 p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-xs font-bold text-red-600 dark:text-red-400">
                  {settingsError}
                </div>
              )}
              {settingsSuccess && (
                <div className="mb-4 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-xs font-bold text-emerald-600 dark:text-emerald-400">
                  {settingsSuccess}
                </div>
              )}

              <form onSubmit={handleSaveSettings} className="space-y-4">
                {/* Read-only Email Field */}
                <div>
                  <label className="block text-xs font-extrabold uppercase tracking-widest text-ink-500 mb-1.5">Email Address</label>
                  <input
                    type="email"
                    value={user?.email || ''}
                    disabled
                    className="w-full px-4 py-2.5 rounded-xl bg-ink-100 border border-ink-200 text-ink-450 text-sm font-bold cursor-not-allowed"
                  />
                  <p className="text-[10px] font-bold text-ink-400 mt-1">Email address cannot be changed.</p>
                </div>

                {/* Company Profile Fields Removed */}

                {/* Theme settings */}
                <div>
                  <label className="block text-xs font-extrabold uppercase tracking-widest text-ink-500 mb-1.5">Default Theme</label>
                  <select
                    value={defaultTheme}
                    onChange={(e) => setDefaultTheme(e.target.value)}
                    className="w-full px-4 py-2.5 rounded-xl bg-ink-50 border border-ink-200 focus:border-ink-400 focus:bg-ink-0 text-sm font-bold transition-all outline-none cursor-pointer text-ink-900"
                  >
                    <option value="dark">Dark Theme</option>
                    <option value="light">Light Theme</option>
                  </select>
                </div>

                {/* Security Fields */}
                <div className="border-t border-ink-200 pt-4 mt-2">
                  <h4 className="text-sm font-bold text-ink-900 mb-3">Change Password</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-extrabold uppercase tracking-widest text-ink-500 mb-1.5">New Password</label>
                      <input
                        type="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        className="w-full px-4 py-2.5 rounded-xl bg-ink-50 border border-ink-200 focus:border-ink-400 focus:bg-ink-0 text-sm font-bold transition-all outline-none"
                        placeholder="••••••••"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-extrabold uppercase tracking-widest text-ink-500 mb-1.5">Confirm New Password</label>
                      <input
                        type="password"
                        value={confirmPassword}
                        onChange={(e) => setConfirmPassword(e.target.value)}
                        className="w-full px-4 py-2.5 rounded-xl bg-ink-50 border border-ink-200 focus:border-ink-400 focus:bg-ink-0 text-sm font-bold transition-all outline-none"
                        placeholder="••••••••"
                      />
                    </div>
                  </div>
                </div>

                {/* Action Buttons */}
                <div className="flex justify-end gap-3 border-t border-ink-200 pt-5 mt-4">
                  <button
                    type="button"
                    disabled={isSaving}
                    onClick={() => setSettingsOpen(false)}
                    className="px-5 py-2.5 rounded-xl text-sm font-bold bg-ink-50 hover:bg-ink-100 border border-ink-200 text-ink-700 disabled:opacity-50 cursor-pointer"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={isSaving}
                    className="px-6 py-2.5 rounded-xl text-sm font-bold bg-ink-900 hover:bg-ink-900 text-ink-0 hover:shadow-lg transition-all disabled:opacity-50 cursor-pointer flex items-center justify-center gap-2"
                  >
                    {isSaving ? 'Saving Changes...' : 'Save Settings'}
                  </button>
                </div>
              </form>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
};
export default ClientLayout;
