'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import {
  LayoutDashboard, FolderKanban, PlusCircle, Settings, LogOut,
  GitBranch, Workflow, SplitSquareHorizontal, FileCode2, ShieldCheck, Download,
  Sun, Moon, ChevronDown, ChevronUp, Search, X, Activity, Network,
  CheckCircle2, Lock, Circle, Shield, Users, Rocket, Cpu, DollarSign,
  Building2, Coins, Clock, Receipt,
} from 'lucide-react';
import type { Project } from '../data/projectsData';
import { useSession } from '../lib/session-context';

interface SidebarProps {
  activeSection: string;
  projectId?: string;
  onNavigate: (section: string, projectId?: string) => void;
  maxReachedStep?: number;
  projects?: Project[];
  currentProject?: Project | null;
  companyRefreshKey?: number;
}

const globalSections = [
  { id: 'dashboard', label: 'Global Dashboard', icon: LayoutDashboard },
  { id: 'conversions', label: 'All Conversions', icon: FolderKanban },
  { id: 'new-conversion', label: 'New Conversion', icon: PlusCircle },
  { id: 'settings', label: 'Settings', icon: Settings },
  { id: 'usage', label: 'Usage', icon: Cpu },
  { id: 'pilot', label: 'Plans & Programs', icon: Rocket },
];

const projectSections = [
  { id: 'conversion-dashboard', label: 'Overview', icon: LayoutDashboard, step: 0 },
  { id: 'repository', label: 'Repository', icon: GitBranch, step: 1 },
  { id: 'migration-strategy', label: 'Migration Strategy', icon: Workflow, step: 1 },
  { id: 'pre-analysis', label: 'Pre-Analysis', icon: Activity, step: 2 },
  { id: 'dep-mapping', label: 'Dependency Mapping', icon: Network, step: 2 },
  { id: 'cost-estimation', label: 'Cost Estimation', icon: DollarSign, step: 2 },
  { id: 'migration-flow', label: 'Migration', icon: Workflow, step: 3 },
  { id: 'comparison', label: 'Code Review', icon: SplitSquareHorizontal, step: 4 },
  { id: 'verification', label: 'Verification', icon: ShieldCheck, step: 5 },
  { id: 'security', label: 'Security', icon: Shield, step: 6 },
  { id: 'artifacts', label: 'Artifacts', icon: FileCode2, step: 7 },
  { id: 'export', label: 'Export', icon: Download, step: 8 },
];

const getStepStatus = (step: number, projectStatus: string, maxReached: number = 0): 'completed' | 'active' | 'locked' => {
  const statusStepMap: Record<string, number> = {
    'draft': 0,
    'analyzing': 2,
    'converting': 3,
    'validating': 5,
    'completed': 9,
    'failed': 3,
  };
  const currentStep = Math.max(statusStepMap[projectStatus] ?? 0, maxReached);
  if (step < currentStep) return 'completed';
  if (step === currentStep) return 'active';
  if (step <= currentStep + 1) return 'active';
  return 'locked';
};

export default function SidebarNew({ activeSection, projectId, onNavigate, maxReachedStep = 0, projects: propProjects, currentProject: propCurrentProject, companyRefreshKey = 0 }: SidebarProps) {
  const { user: sessionUser } = useSession();
  const isAdmin = sessionUser?.role === 'admin';
  const projectsData = propProjects ?? [];
  const resolvedCurrentProject = propCurrentProject || (projectId ? projectsData.find((p: Project) => p.id === projectId) : null);
  const [light, setLight] = useState(true);
  const [showProjectList, setShowProjectList] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [maxProjects, setMaxProjects] = useState<number | null>(null);
  const [companyProjectCount, setCompanyProjectCount] = useState<number | null>(null);

  useEffect(() => {
    const root = document.documentElement;
    if (light) {
      root.classList.add('light');
    } else {
      root.classList.remove('light');
    }
  }, [light]);

  useEffect(() => {
    if (!sessionUser?.companyId) return;
    fetch(`/api/companies/${sessionUser.companyId}`, { credentials: 'include' })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        const cap = data?.company?.maxConversions;
        const used = data?.company?.conversionCount;
        if (typeof cap === 'number') setMaxProjects(cap);
        if (typeof used === 'number') setCompanyProjectCount(used);
      })
      .catch(() => {});
  }, [sessionUser?.companyId, projectsData.length, companyRefreshKey]);

  const effectiveProjectCount = typeof companyProjectCount === 'number' ? companyProjectCount : projectsData.length;
  const isAtProjectLimit = typeof maxProjects === 'number' && effectiveProjectCount >= maxProjects;

  const filteredProjects = projectsData.filter((p: Project) =>
    p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    p.description.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <aside className="w-[260px] h-screen fixed left-0 top-0 glass flex flex-col z-50">
      <div className="p-4 border-b border-border">
        <div className="flex items-center gap-2.5">
          <div className="w-9 h-9 rounded-lg overflow-hidden flex-shrink-0">
            <Image
              src={light ? '/logo-light-theme.png' : '/logo-dark-theme.png'}
              alt="Scriba AI logo"
              width={36}
              height={36}
              className="w-full h-full object-cover"
            />
          </div>
          <div>
            <h1 className="text-base font-bold text-foreground tracking-tight">Scriba AI</h1>
            <p className="text-[10px] text-muted tracking-wider uppercase">by Algoretico</p>
          </div>
        </div>
      </div>

      <nav className="flex-1 overflow-y-auto p-3 space-y-4">
        <div className="space-y-0.5">
          <p className="text-[10px] text-muted uppercase tracking-wider px-3 py-1.5 font-semibold">Navigation</p>
          {globalSections.map((item) => {
            const Icon = item.icon;
            const isActive = activeSection === item.id && !projectId;
            const isNewConversionItem = item.id === 'new-conversion';
            const isDisabled = isNewConversionItem && isAtProjectLimit;
            return (
              <button
                key={item.id}
                onClick={() => !isDisabled && onNavigate(item.id)}
                disabled={isDisabled}
                title={isDisabled ? 'Conversion limit reached for your plan — purchase an extra slot to continue' : undefined}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-all duration-200 ${
                  isDisabled
                    ? 'text-muted/40 border border-transparent cursor-not-allowed'
                    : 'cursor-pointer'
                } ${
                  isActive
                    ? 'bg-accent/15 text-accent-light border border-accent/20 glow-accent'
                    : 'text-muted hover:text-foreground hover:bg-surface-light border border-transparent'
                }`}
              >
                <Icon className="w-4 h-4 flex-shrink-0" />
                <span className="font-medium">{item.label}</span>
                {isDisabled && <Lock className="w-3 h-3 ml-auto opacity-60" />}
              </button>
            );
          })}
          {isAdmin && (
            <>
              <div className="pt-3 pb-0.5">
                <p className="text-[10px] text-muted uppercase tracking-wider px-3 font-semibold">Admin</p>
              </div>
              {[
                { id: 'crm',     label: 'CRM',     icon: Users       },
                { id: 'finance', label: 'Finance', icon: DollarSign  },
                { id: 'admin-activity', label: 'Activity Logs', icon: Clock },
              ].map(item => {
                const Icon = item.icon;
                const isActive = activeSection === item.id && !projectId;
                return (
                  <button key={item.id} onClick={() => onNavigate(item.id)}
                    className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-all duration-200 cursor-pointer ${
                      isActive
                        ? 'bg-accent/15 text-accent-light border border-accent/20 glow-accent'
                        : 'text-muted hover:text-foreground hover:bg-surface-light border border-transparent'
                    }`}>
                    <Icon className="w-4 h-4 flex-shrink-0" />
                    <span className="font-medium">{item.label}</span>
                  </button>
                );
              })}
            </>
          )}
          {/* Company section - visible to owners */}
          {sessionUser?.isOwner && sessionUser?.companyId && (
            <>
              <div className="pt-3 pb-0.5">
                <p className="text-[10px] text-muted uppercase tracking-wider px-3 font-semibold">Company</p>
              </div>
              {[
                { id: 'company', label: 'Company', icon: Building2 },
                { id: 'credits', label: 'Credits', icon: Coins },
                { id: 'invoices', label: 'Invoices', icon: Receipt },
              ].map(item => {
                const Icon = item.icon;
                const isActive = activeSection === item.id && !projectId;
                return (
                  <button key={item.id} onClick={() => onNavigate(item.id)}
                    className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-all duration-200 cursor-pointer ${
                      isActive
                        ? 'bg-accent/15 text-accent-light border border-accent/20 glow-accent'
                        : 'text-muted hover:text-foreground hover:bg-surface-light border border-transparent'
                    }`}>
                    <Icon className="w-4 h-4 flex-shrink-0" />
                    <span className="font-medium">{item.label}</span>
                  </button>
                );
              })}
            </>
          )}
        </div>

        <div className="space-y-0.5">
          <div className="flex items-center justify-between px-3 py-1.5">
            <p className="text-[10px] text-muted uppercase tracking-wider font-semibold">Conversion</p>
            <button
              onClick={() => setShowProjectList(!showProjectList)}
              className="p-0.5 rounded hover:bg-surface-light cursor-pointer"
            >
              {showProjectList ? <ChevronUp className="w-3 h-3 text-muted" /> : <ChevronDown className="w-3 h-3 text-muted" />}
            </button>
          </div>

          {resolvedCurrentProject ? (
            <button
              onClick={() => onNavigate('conversion-dashboard', resolvedCurrentProject.id)}
              className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-all duration-200 cursor-pointer mb-2 ${
                activeSection.startsWith('conversion') && projectId === resolvedCurrentProject.id
                  ? 'bg-accent/15 text-accent-light border border-accent/20 glow-accent'
                  : 'text-muted hover:text-foreground hover:bg-surface-light border border-transparent'
              }`}
            >
              <div className="w-8 h-8 rounded-lg bg-surface-light flex items-center justify-center text-[10px] font-bold text-muted flex-shrink-0">
                {resolvedCurrentProject.name.slice(0, 2).toUpperCase()}
              </div>
              <div className="min-w-0">
                <p className="text-xs font-medium text-foreground truncate">{resolvedCurrentProject.name}</p>
                <p className="text-[10px] text-muted truncate">{resolvedCurrentProject.status}</p>
              </div>
            </button>
          ) : (
            <button
              onClick={() => setShowProjectList(!showProjectList)}
              className="w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-muted hover:text-foreground hover:bg-surface-light border border-transparent cursor-pointer mb-2"
            >
              <FolderKanban className="w-4 h-4 flex-shrink-0" />
              <span className="font-medium">Select a conversion</span>
            </button>
          )}

          {showProjectList && (
            <div className="space-y-1 pl-2 border-l-2 border-border ml-3">
              <div className="flex items-center gap-2 px-2 py-1.5 mb-1">
                <Search className="w-3 h-3 text-muted" />
                <input
                  type="text"
                  placeholder="Search conversions..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="bg-transparent text-xs text-foreground outline-none placeholder-muted flex-1"
                  autoFocus
                />
                {searchQuery && (
                  <button onClick={() => setSearchQuery('')} className="cursor-pointer">
                    <X className="w-3 h-3 text-muted" />
                  </button>
                )}
              </div>
              {filteredProjects.map((p: Project) => (
                <button
                  key={p.id}
                  onClick={() => { onNavigate('conversion-dashboard', p.id); setShowProjectList(false); }}
                  className={`w-full flex items-center gap-2 px-2 py-1.5 rounded text-xs transition-all cursor-pointer text-left ${
                    projectId === p.id ? 'bg-accent/10 text-accent-light' : 'text-muted hover:text-foreground hover:bg-surface-light'
                  }`}
                >
                  <div className="w-6 h-6 rounded bg-surface-light flex items-center justify-center text-[9px] font-bold flex-shrink-0">
                    {p.name.slice(0, 2).toUpperCase()}
                  </div>
                  <span className="truncate">{p.name}</span>
                </button>
              ))}
            </div>
          )}

          {resolvedCurrentProject && (
            <div className="space-y-0.5 ml-3 mt-2 relative">
              <div className="absolute left-[11px] top-4 bottom-4 w-px bg-border" />
              {projectSections.map((item) => {
                const Icon = item.icon;
                const isActive = activeSection === item.id && projectId === resolvedCurrentProject.id;
                const stepStatus = getStepStatus(item.step, resolvedCurrentProject.status, maxReachedStep);
                const isLocked = stepStatus === 'locked';
                const isCompleted = stepStatus === 'completed';
                const isCurrentPhase = stepStatus === 'active';
                return (
                  <button
                    key={item.id}
                    onClick={() => !isLocked && onNavigate(item.id, resolvedCurrentProject.id)}
                    className={`w-full flex items-center gap-2.5 px-2 py-1.5 rounded text-xs transition-all duration-200 ${
                      isLocked
                        ? 'text-muted/40 cursor-not-allowed'
                        : isActive
                          ? 'bg-accent/15 text-accent-light border border-accent/20 cursor-pointer'
                          : 'text-muted hover:text-foreground hover:bg-surface-light border border-transparent cursor-pointer'
                    }`}
                  >
                    <div className="relative z-10 flex-shrink-0">
                      {isCompleted ? (
                        <div className="w-[22px] h-[22px] rounded-full bg-success/20 flex items-center justify-center">
                          <CheckCircle2 className="w-3 h-3 text-success" />
                        </div>
                      ) : isCurrentPhase ? (
                        <div className="w-[22px] h-[22px] rounded-full bg-accent/20 flex items-center justify-center ring-2 ring-accent/30">
                          <Circle className="w-2.5 h-2.5 text-accent-light fill-accent-light" />
                        </div>
                      ) : isLocked ? (
                        <div className="w-[22px] h-[22px] rounded-full bg-surface-light flex items-center justify-center">
                          <Lock className="w-2.5 h-2.5 text-muted/40" />
                        </div>
                      ) : (
                        <div className="w-[22px] h-[22px] rounded-full bg-surface-light flex items-center justify-center">
                          <Circle className="w-2.5 h-2.5 text-muted" />
                        </div>
                      )}
                    </div>
                    <Icon className={`w-3.5 h-3.5 flex-shrink-0 ${isLocked ? 'opacity-30' : ''}`} />
                    <span className={`font-medium flex-1 text-left ${isLocked ? 'opacity-30' : ''}`}>{item.label}</span>
                    {item.step > 0 && (
                      <span className={`text-[9px] font-mono ${isLocked ? 'opacity-20' : 'opacity-50'}`}>{item.step}</span>
                    )}
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </nav>

      <div className="p-4 border-t border-border space-y-3">
        <button
          onClick={() => setLight(!light)}
          className="w-full flex items-center gap-2.5 px-3 py-2 rounded-lg glass-light text-sm text-muted hover:text-foreground transition-all cursor-pointer"
        >
          {light ? <Moon className="w-4 h-4" /> : <Sun className="w-4 h-4" />}
          <span className="font-medium">{light ? 'Dark Mode' : 'Light Mode'}</span>
        </button>
        <div className="flex items-center gap-3 px-2">
          <div className="w-8 h-8 rounded-full gradient-accent flex items-center justify-center text-white text-xs font-bold">
            {sessionUser?.name ? sessionUser.name.split(' ').map((w: string) => w[0]).join('').toUpperCase().slice(0, 2) : '?'}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-xs font-medium text-foreground truncate">{sessionUser?.name || 'User'}</p>
            <p className="text-[10px] text-muted truncate">{sessionUser?.email || ''}</p>
          </div>
          <button
            onClick={async () => {
              await fetch('/api/auth/signout', { method: 'POST', credentials: 'include' });
              window.location.href = '/';
            }}
            title="Sign out"
            className="p-1.5 rounded hover:bg-surface-light cursor-pointer"
          >
            <LogOut className="w-4 h-4 text-muted" />
          </button>
        </div>
      </div>
    </aside>
  );
}
