import React, { useMemo } from 'react';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import { 
  LogOut,
  Zap,
  ChevronDown,
  ChevronRight,
  AlertCircle
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { PerspectiveSwitcher } from './PerspectiveSwitcher';
import { NAVIGATION_CONFIG } from '../config/navigation';
import type { NavItem } from '../config/navigation';
import { logout } from '../utils/auth';

export const Sidebar: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();

  // Safely parse user data
  const user = useMemo(() => {
    try {
      const stored = localStorage.getItem('teleems_user');
      if (!stored || stored === 'undefined' || stored === 'null') return { roles: [] };
      const parsed = JSON.parse(stored);
      if (parsed && typeof parsed === 'object') {
        parsed.roles = Array.isArray(parsed.roles) 
          ? parsed.roles.map((r: any) => String(r).toUpperCase().replace(/\s+/g, '_')) 
          : [];
        return parsed;
      }
      return { roles: [] };
    } catch (err) {
      console.error('Failed to parse user data from localStorage', err);
      return { roles: [] };
    }
  }, []);

  const handleLogout = () => {
    logout();
  };

  const handleRoleSwitch = (role: string) => {
    const updatedUser = { ...user, roles: [role.toUpperCase()] };
    localStorage.setItem('teleems_user', JSON.stringify(updatedUser));
    window.location.reload();
  };

  const currentRole = user.roles?.[0] || 'CURESELECT_ADMIN';
  const displayName = String(user.username || (currentRole === 'CURESELECT_ADMIN' ? 'CureSelect Admin' : 'Admin User'));
  const displayId = user.id ? `#${String(user.id).substring(0, 6)}` : '#789022';
  const initials = currentRole === 'CURESELECT_ADMIN' ? 'CA' : (displayName.substring(0, 2).toUpperCase() || 'AU');

  const filteredNavItems = useMemo(() => {
    const userRoles = Array.isArray(user.roles) ? user.roles : [];
    const adminRoles = ['CURESELECT_ADMIN', 'ADMIN', 'SUPER_ADMIN', 'SUPERADMIN'];
    const hasAdminRole = userRoles.some((r: string) => adminRoles.includes(r));

    const filterItems = (items: NavItem[]): NavItem[] => {
      return items.filter(item => {
        const hasItemRole = item.roles.some(role => userRoles.includes(role.toUpperCase()));
        return hasAdminRole || hasItemRole;
      }).map(item => ({
        ...item,
        subItems: item.subItems ? filterItems(item.subItems) : undefined
      }));
    };

    const result = filterItems(NAVIGATION_CONFIG);
    console.log('[DEBUG] userRoles:', userRoles, 'filteredItems:', result);
    return result;
  }, [user.roles]);

  const renderNavItem = (item: NavItem, isSubItem = false) => {
    const Icon = item.icon || AlertCircle;
    const isActive = location.pathname === item.path || (item.path.includes('?') && location.pathname + location.search === item.path);
    const hasSubItems = item.subItems && item.subItems.length > 0;
    const isParentActive = hasSubItems && (isActive || item.subItems?.some(sub => location.pathname === sub.path.split('?')[0]));

    return (
      <div key={item.id} style={{ display: 'flex', flexDirection: 'column' }}>
        <NavLink
          to={item.path}
          className={({ isActive: linkActive }) => 
            `${isSubItem ? 'sidebar-sub-item' : 'sidebar-nav-item'} ${(linkActive || isActive) ? 'active' : ''}`
          }
        >
          {!isSubItem && <Icon size={18} style={{ flexShrink: 0 }} />}
          <span className="sidebar-label" style={{ 
            flex: 1,
            whiteSpace: 'nowrap', 
            overflow: 'hidden', 
            textOverflow: 'ellipsis'
          }}>
            {item.label}
          </span>
          {hasSubItems && (
             <span className="sidebar-label">
                {isParentActive ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
             </span>
          )}
        </NavLink>

        <AnimatePresence>
          {hasSubItems && isParentActive && (
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{ height: 'auto', opacity: 1 }}
              exit={{ height: 0, opacity: 0 }}
              transition={{ duration: 0.3, ease: 'easeInOut' }}
              style={{ overflow: 'hidden', background: 'transparent' }}
            >
              {item.subItems?.map(sub => renderNavItem(sub, true))}
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    );
  };

  return (
    <aside className="sidebar-premium" style={{
      width: 'var(--sidebar-width)',
      minWidth: 'var(--sidebar-width)',
      flexBasis: 'var(--sidebar-width)',
      flexShrink: 0,
      height: '100vh',
      display: 'flex',
      flexDirection: 'column',
      zIndex: 1100,
      position: 'relative'
    }}>
      <div style={{
        padding: '16px 20px',
        borderBottom: '1px solid #edf2f7',
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
        flexShrink: 0,
      }}>
        <div style={{
          width: '28px',
          height: '28px',
          background: 'linear-gradient(135deg, #0ea5e9, #3b82f6)',
          borderRadius: '7px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexShrink: 0,
        }}>
          <Zap size={16} color="#ffffff" />
        </div>
        <h2 className="sidebar-label sidebar-logo-text" style={{ fontSize: '1.1rem', margin: 0 }}>CureSelect</h2>
      </div>

      <nav style={{ flex: 1, padding: '12px 0', overflowY: 'auto', minHeight: 0 }} className="no-scrollbar">
        {filteredNavItems.map(item => renderNavItem(item))}
      </nav>

      <div style={{
        padding: '12px 16px',
        borderTop: '1px solid #edf2f7',
        display: 'flex',
        flexDirection: 'column',
        gap: '10px',
        flexShrink: 0,
      }}>
        {/* Perspective Switcher */}
        {(user.roles?.includes('CURESELECT_ADMIN') || user.roles?.includes('ADMIN')) && (
          <PerspectiveSwitcher 
            currentRole={currentRole} 
            onSwitch={handleRoleSwitch} 
          />
        )}

        {/* User row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px', minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px', minWidth: 0, overflow: 'hidden' }}>
            <div style={{
              width: '30px',
              height: '30px',
              borderRadius: '8px',
              background: 'linear-gradient(135deg, var(--accent-cyan), #3b82f6)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '0.7rem',
              fontWeight: 700,
              color: '#fff',
              flexShrink: 0,
            }}>{initials}</div>
            <div className="sidebar-label" style={{ minWidth: 0, overflow: 'hidden' }}>
              <div style={{ fontSize: '0.8rem', fontWeight: 600, color: '#1e293b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{displayName}</div>
              <div style={{ fontSize: '0.68rem', color: '#94a3b8', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>ID: {displayId}</div>
            </div>
          </div>
          <button
            onClick={handleLogout}
            style={{
              background: '#fef2f2',
              border: '1px solid #fecaca',
              borderRadius: '7px',
              padding: '6px',
              color: '#ef4444',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.15s',
              flexShrink: 0,
            }}
            title="Sign Out"
          >
            <LogOut size={14} />
          </button>
        </div>
      </div>
    </aside>
  );
};
