import { NavLink, useNavigate } from 'react-router-dom';
import {
  Home,
  Settings,
  Activity,
  FileText,
  TrendingUp,
  ChevronLeft,
  Play,
  Pause,
  CheckCircle,
  Clock,
  Zap,
  Terminal,
  Eye
} from 'lucide-react';
import clsx from 'clsx';
import { useStudy } from '../../context/StudyContext';
import { useClaudeTerminal } from '../../context/ClaudeTerminalContext';

export const Sidebar = () => {
  const { selectedStudy, clearStudy } = useStudy();
  const { isConnected: claudeConnected, setIsOpen: setClaudeTerminalOpen } = useClaudeTerminal();
  const navigate = useNavigate();

  const handleBackToHome = () => {
    clearStudy();
    navigate('/');
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'running':
        return <Play className="w-3 h-3 text-green-400" />;
      case 'paused':
        return <Pause className="w-3 h-3 text-orange-400" />;
      case 'completed':
        return <CheckCircle className="w-3 h-3 text-blue-400" />;
      case 'not_started':
        return <Clock className="w-3 h-3 text-dark-400" />;
      default:
        return <Clock className="w-3 h-3 text-dark-400" />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'running':
        return 'text-green-400';
      case 'paused':
        return 'text-orange-400';
      case 'completed':
        return 'text-blue-400';
      case 'not_started':
        return 'text-dark-400';
      default:
        return 'text-dark-400';
    }
  };

  // Navigation items depend on whether a study is selected
  const navItems = selectedStudy
    ? [
        { to: '/setup', icon: Settings, label: 'Setup' },
        { to: '/dashboard', icon: Activity, label: 'Live Tracker' },
        { to: '/analysis', icon: TrendingUp, label: 'Analysis' },
        { to: '/insights', icon: Eye, label: 'Insights' },
        { to: '/results', icon: FileText, label: 'Results' },
      ]
    : [
        { to: '/', icon: Home, label: 'Select Study' },
      ];

  return (
    <aside className="w-64 bg-dark-800 border-r border-dark-600 flex flex-col h-screen fixed left-0 top-0">
      {/* Header */}
      <div className="p-6 border-b border-dark-600">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-primary-600 rounded-lg flex items-center justify-center">
            <Zap className="w-5 h-5 text-white" />
          </div>
          <h1 className="text-xl font-bold text-white tracking-tight">Atomizer</h1>
        </div>
        <p className="text-xs text-dark-300 mt-1 ml-11">Optimization Platform</p>
      </div>

      {/* Selected Study Info */}
      {selectedStudy && (
        <div className="p-4 border-b border-dark-600">
          <button
            onClick={handleBackToHome}
            className="flex items-center gap-2 text-sm text-dark-400 hover:text-white
                       transition-colors mb-3 group"
          >
            <ChevronLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
            Change Study
          </button>

          <div className="bg-dark-700 rounded-lg p-3">
            <div className="text-xs font-medium text-dark-400 uppercase mb-1">Active Study</div>
            <div className="text-white font-medium truncate">{selectedStudy.name}</div>
            <div className="flex items-center gap-2 mt-2">
              <span className={`flex items-center gap-1 text-xs ${getStatusColor(selectedStudy.status)}`}>
                {getStatusIcon(selectedStudy.status)}
                {selectedStudy.status}
              </span>
              <span className="text-dark-500">|</span>
              <span className="text-xs text-dark-400">
                {selectedStudy.progress.current}/{selectedStudy.progress.total}
              </span>
            </div>
          </div>
        </div>
      )}

      {/* Navigation */}
      <nav className="flex-1 p-4 space-y-1">
        {navItems.map((item) => (
          <NavLink
            key={item.to}
            to={item.to}
            end={item.to === '/'}
            className={({ isActive }) =>
              clsx(
                'flex items-center gap-3 px-4 py-3 rounded-lg transition-colors duration-200',
                isActive
                  ? 'bg-primary-900/50 text-primary-100 border border-primary-700/50'
                  : 'text-dark-300 hover:bg-dark-700 hover:text-white'
              )
            }
          >
            <item.icon className="w-5 h-5" />
            <span className="font-medium">{item.label}</span>
          </NavLink>
        ))}
      </nav>

      {/* Footer Status */}
      <div className="p-4 border-t border-dark-600">
        <div className="bg-dark-700 rounded-lg p-4">
          <div className="text-xs font-medium text-dark-400 uppercase mb-2">System Status</div>
          <div className="flex items-center gap-2 text-sm text-green-400">
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
            Backend Online
          </div>
          {selectedStudy && selectedStudy.status === 'running' && (
            <div className="flex items-center gap-2 text-sm text-green-400 mt-1">
              <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
              Optimization Running
            </div>
          )}
          {selectedStudy && selectedStudy.status === 'paused' && (
            <div className="flex items-center gap-2 text-sm text-orange-400 mt-1">
              <div className="w-2 h-2 bg-orange-500 rounded-full" />
              Optimization Paused
            </div>
          )}
          {/* Claude Terminal Status */}
          <button
            onClick={() => setClaudeTerminalOpen(true)}
            className={clsx(
              'flex items-center gap-2 text-sm mt-1 w-full text-left hover:opacity-80 transition-opacity',
              claudeConnected ? 'text-green-400' : 'text-dark-400'
            )}
          >
            <Terminal className="w-3 h-3" />
            {claudeConnected ? 'Claude Connected' : 'Claude Disconnected'}
          </button>
        </div>
      </div>
    </aside>
  );
};
