import React, { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  ShieldAlert, 
  Hospital, 
  Monitor, 
  HeartPulse, 
  Truck, 
  Zap, 
  Activity,
  ChevronDown,
  ChevronUp,
  LayoutDashboard,
  Navigation,
  User
} from 'lucide-react';

interface Perspective {
  id: string;
  label: string;
  group: string;
  icon: React.ElementType;
  description: string;
}

const perspectives: Perspective[] = [
  { id: 'CURESELECT_ADMIN', label: 'CureSelect Admin', group: 'System Access', icon: LayoutDashboard, description: 'Full Platform Access' },
  { id: 'HOSPITAL_ADMIN', label: 'Hospital Admin', group: 'Hospital Scope', icon: Hospital, description: 'Manage Hospital Assets' },
  { id: 'COORDINATOR', label: 'Hospital Coordinator', group: 'Hospital Scope', icon: Monitor, description: 'Manage Operations' },
  { id: 'ED_DOCTOR', label: 'Emergency Doctor', group: 'Hospital Scope', icon: HeartPulse, description: 'Clinical Intelligence' },
  { id: 'FLEET_OPERATOR', label: 'Fleet Operator', group: 'Fleet Scope', icon: Truck, description: 'Dispatch & Logistics' },
  { id: 'STATION_INCHARGE', label: 'Station Incharge', group: 'Fleet Scope', icon: Zap, description: 'Node Management' },
  { id: 'PILOT', label: 'Ambulance Pilot', group: 'Fleet Scope', icon: Navigation, description: 'Trip Management' },
  { id: 'EMT', label: 'EMT/Paramedic', group: 'Fleet Scope', icon: Activity, description: 'Patient Care' },
  { id: 'HOSPITAL_GROUP', label: 'Hospital Group', group: 'Regional Scope', icon: ShieldAlert, description: 'Regional Management' },
  { id: 'PROVIDER', label: 'Provider Portal', group: 'Clinical Scope', icon: Activity, description: 'Healthcare Provider' },
  { id: 'PATIENT', label: 'Patient Portal', group: 'Patient Scope', icon: User, description: 'Personal Health' },
  { id: 'SCAN_CENTRE', label: 'Scan Centre', group: 'Diagnostic Scope', icon: Monitor, description: 'Imaging & Diagnostics' },
  { id: 'CART', label: 'Mobile Cart', group: 'Field Scope', icon: Truck, description: 'Mobile Response' },
];

export const PerspectiveSwitcher: React.FC<{ currentRole: string; onSwitch: (role: string) => void }> = ({ 
  currentRole, 
  onSwitch 
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const currentPerspective = perspectives.find(p => p.id === currentRole) || perspectives[0];
  const Icon = currentPerspective.icon;

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const groupedPerspectives = perspectives.reduce((acc, p) => {
    if (!acc[p.group]) acc[p.group] = [];
    acc[p.group].push(p);
    return acc;
  }, {} as Record<string, Perspective[]>);

  return (
    <div ref={containerRef} style={{ position: 'relative', width: '100%' }}>
      <span style={{ 
        fontSize: '0.6rem', 
        color: 'var(--text-secondary)', 
        textTransform: 'uppercase', 
        fontWeight: 800, 
        letterSpacing: '0.1em',
        marginBottom: '6px',
        display: 'block',
        marginLeft: '4px'
      }}>
        Perspective Switcher
      </span>
      
      <motion.button
        whileHover={{ scale: 1.01 }}
        whileTap={{ scale: 0.98 }}
        onClick={() => setIsOpen(!isOpen)}
        style={{
          width: '100%',
          padding: '10px 12px',
          background: 'rgba(59, 130, 246, 0.05)',
          border: '1px solid var(--card-border)',
          borderRadius: '10px',
          display: 'flex',
          alignItems: 'center',
          gap: '10px',
          cursor: 'pointer',
          color: 'var(--text-primary)',
          textAlign: 'left',
          transition: 'border-color 0.2s',
          outline: 'none',
        }}
      >
        <div style={{
          width: '24px',
          height: '24px',
          borderRadius: '6px',
          background: 'rgba(59, 130, 246, 0.1)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: 'var(--accent-cyan)',
        }}>
          <Icon size={14} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: '0.75rem', fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {currentPerspective.label}
          </div>
        </div>
        {isOpen ? <ChevronUp size={14} color="var(--text-secondary)" /> : <ChevronDown size={14} color="var(--text-secondary)" />}
      </motion.button>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: -10, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -10, scale: 0.95 }}
            transition={{ duration: 0.15, ease: 'easeOut' }}
            className="glass"
            style={{
              position: 'absolute',
              bottom: '100%',
              left: 0,
              width: '240px',
              marginBottom: '12px',
              padding: '8px',
              zIndex: 2000,
              boxShadow: '0 10px 40px rgba(0,0,0,0.15)',
              border: '1px solid var(--card-border)',
              background: 'rgba(255, 255, 255, 0.95)',
              backdropFilter: 'blur(16px)',
              maxHeight: '400px',
              overflowY: 'auto'
            }}
          >
            {Object.entries(groupedPerspectives).map(([group, items]) => (
              <div key={group} style={{ marginBottom: '8px' }}>
                <div style={{ 
                  fontSize: '0.55rem', 
                  fontWeight: 800, 
                  color: 'var(--text-secondary)', 
                  textTransform: 'uppercase', 
                  padding: '4px 8px',
                  letterSpacing: '0.05em'
                }}>
                  {group}
                </div>
                {items.map((p) => {
                  const ItemIcon = p.icon;
                  const isActive = p.id === currentRole;
                  return (
                    <button
                      key={p.id}
                      onClick={() => {
                        onSwitch(p.id);
                        setIsOpen(false);
                      }}
                      style={{
                        width: '100%',
                        padding: '8px',
                        borderRadius: '6px',
                        border: 'none',
                        background: isActive ? 'rgba(59, 130, 246, 0.08)' : 'transparent',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '10px',
                        cursor: 'pointer',
                        textAlign: 'left',
                        transition: 'all 0.2s',
                        color: isActive ? 'var(--accent-cyan)' : 'var(--text-primary)',
                        marginBottom: '2px'
                      }}
                      className={isActive ? '' : 'table-row-hover'}
                    >
                      <div style={{
                        width: '22px',
                        height: '22px',
                        borderRadius: '5px',
                        background: isActive ? 'rgba(59, 130, 246, 0.15)' : 'rgba(0,0,0,0.03)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}>
                        <ItemIcon size={12} />
                      </div>
                      <div>
                        <div style={{ fontSize: '0.72rem', fontWeight: isActive ? 700 : 600 }}>{p.label}</div>
                        <div style={{ fontSize: '0.58rem', color: 'var(--text-secondary)', opacity: 0.8 }}>{p.description}</div>
                      </div>
                    </button>
                  );
                })}
              </div>
            ))}

            <div style={{ 
              marginTop: '8px', 
              paddingTop: '8px', 
              borderTop: '1px solid rgba(0,0,0,0.05)',
              display: 'flex',
              flexDirection: 'column',
              gap: '4px'
            }}>
              <button
                onClick={() => {
                  window.location.href = '/launcher';
                }}
                style={{
                  width: '100%',
                  padding: '10px',
                  borderRadius: '6px',
                  border: '1px dashed var(--accent-cyan)',
                  background: 'rgba(59, 130, 246, 0.03)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '10px',
                  cursor: 'pointer',
                  color: 'var(--accent-cyan)',
                  fontSize: '0.7rem',
                  fontWeight: 700,
                  transition: 'all 0.2s'
                }}
                className="table-row-hover"
              >
                <LayoutDashboard size={14} />
                SWITCH SYSTEM PORTAL
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};
