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()) 
          : [];
        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 => 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
      }));
    };

    return filterItems(NAVIGATION_CONFIG);
  }, [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}
          style={({ isActive: linkActive }) => ({
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            padding: isSubItem ? '8px 20px 8px 48px' : '10px 20px',
            textDecoration: 'none',
            color: (linkActive || isActive) ? 'var(--accent-cyan)' : 'var(--text-secondary)',
            borderLeft: !isSubItem && (linkActive || isActive) ? '3px solid var(--accent-cyan)' : '3px solid transparent',
            background: (linkActive || isActive) ? 'rgba(59, 130, 246, 0.08)' : 'transparent',
            transition: 'all 0.25s ease',
            textShadow: (linkActive || isActive) ? '0 0 10px rgba(59, 130, 246, 0.4)' : 'none',
            minWidth: 0,
            position: 'relative'
          })}
        >
          {!isSubItem && <Icon size={18} style={{ flexShrink: 0 }} />}
          <span style={{ 
            fontWeight: (isActive || isParentActive) ? 700 : 500, 
            fontSize: isSubItem ? '0.8rem' : '0.875rem', 
            whiteSpace: 'nowrap', 
            overflow: 'hidden', 
            textOverflow: 'ellipsis',
            flex: 1
          }}>
            {item.label}
          </span>
          {hasSubItems && (
            isParentActive ? <ChevronDown size={14} /> : <ChevronRight size={14} />
          )}
        </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: 'rgba(255,255,255,0.02)' }}
            >
              {item.subItems?.map(sub => renderNavItem(sub, true))}
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    );
  };

  return (
    <aside className="glass" style={{
      width: 'var(--sidebar-width)',
      minWidth: 'var(--sidebar-width)',
      flexBasis: 'var(--sidebar-width)',
      flexShrink: 0,
      height: '100vh',
      display: 'flex',
      flexDirection: 'column',
      borderRight: '1px solid var(--card-border)',
      background: 'var(--glass-bg)',
      zIndex: 1100,
      position: 'relative'
    }}>
      <div style={{
        padding: '20px 20px',
        borderBottom: '1px solid var(--card-border)',
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
        flexShrink: 0,
      }}>
        <div style={{
          width: '30px',
          height: '30px',
          background: 'var(--accent-cyan)',
          borderRadius: '6px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          boxShadow: '0 0 12px var(--accent-cyan)',
          flexShrink: 0,
        }}>
          <Zap size={18} color="#000" />
        </div>
        <h2 style={{ fontSize: '1.1rem', fontWeight: 800, color: 'var(--accent-cyan)', margin: 0, letterSpacing: '-0.3px' }}>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 var(--card-border)',
        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: '32px',
              height: '32px',
              borderRadius: '50%',
              background: 'linear-gradient(135deg, var(--accent-cyan), var(--accent-green))',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '0.75rem',
              fontWeight: 700,
              color: '#000',
              flexShrink: 0,
            }}>{initials}</div>
            <div style={{ minWidth: 0, overflow: 'hidden' }}>
              <div style={{ fontSize: '0.78rem', fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{displayName}</div>
              <div style={{ fontSize: '0.62rem', color: 'var(--text-secondary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>ID: {displayId}</div>
            </div>
          </div>
          <button
            onClick={handleLogout}
            className="hover-glow"
            style={{
              background: 'rgba(239, 68, 68, 0.1)',
              border: '1px solid rgba(239, 68, 68, 0.2)',
              borderRadius: '8px',
              padding: '7px',
              color: 'var(--alert-red)',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.2s',
              flexShrink: 0,
            }}
            title="Sign Out"
          >
            <LogOut size={15} />
          </button>
        </div>
      </div>
    </aside>
  );
};
