'use client';

import { useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { categoryApi, channelApi, notificationApi } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import { useChatStore } from '@/store/chatStore';
import { cn } from '@/lib/utils';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Hash, ChevronDown, ChevronRight, Plus, Settings, Users,
  FolderKanban, Image, Video, Search, Bell, FileText,
  Archive, LogOut, Circle, MessageSquare
} from 'lucide-react';

export function Sidebar() {
  const router = useRouter();
  const pathname = usePathname();
  const { user, logout } = useAuthStore();
  const { setActiveChannel } = useChatStore();
  const [categories, setCategories] = useState<any[]>([]);
  const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
  const [showCreateCat, setShowCreateCat] = useState(false);
  const [newCatName, setNewCatName] = useState('');
  const [showCreateCh, setShowCreateCh] = useState<string | null>(null);
  const [newChName, setNewChName] = useState('');
  const [unreadNotifs, setUnreadNotifs] = useState(0);

  const canManage = user?.role === 'OWNER' || user?.role === 'ADMIN';

  useEffect(() => {
    loadCategories();
    loadNotifications();
  }, []);

  const loadCategories = async () => {
    try {
      const { data } = await categoryApi.getAll();
      setCategories(data);
    } catch {}
  };

  const loadNotifications = async () => {
    try {
      const { data } = await notificationApi.getUnreadCount();
      setUnreadNotifs(data.count);
    } catch {}
  };

  const createCategory = async () => {
    if (!newCatName.trim()) return;
    try {
      await categoryApi.create(newCatName);
      setNewCatName('');
      setShowCreateCat(false);
      loadCategories();
    } catch {}
  };

  const createChannel = async (categoryId: string) => {
    if (!newChName.trim()) return;
    try {
      await channelApi.create({ name: newChName, categoryId });
      setNewChName('');
      setShowCreateCh(null);
      loadCategories();
    } catch {}
  };

  const navigateToChannel = (channel: any) => {
    setActiveChannel(channel);
    router.push(`/workspace/channels/${channel.id}`);
  };

  const toggleCollapse = (catId: string) => {
    setCollapsed(prev => ({ ...prev, [catId]: !prev[catId] }));
  };

  const navItems = [
    { icon: MessageSquare, label: 'Chat', href: '/workspace', active: pathname?.includes('/workspace/channels') || pathname === '/workspace' },
    { icon: FolderKanban, label: 'Files', href: '/workspace/files' },
    { icon: Image, label: 'Images', href: '/workspace/images' },
    { icon: Video, label: 'Videos', href: '/workspace/videos' },
    { icon: Search, label: 'Search', href: '/workspace/search' },
    { icon: Bell, label: 'Notifications', href: '/workspace/notifications', badge: unreadNotifs },
    { icon: Users, label: 'Team', href: '/workspace/team' },
  ];

  if (canManage) {
    navItems.push({ icon: Settings, label: 'Admin', href: '/workspace/admin' });
  }

  const isActive = (href: string) => {
    if (href === '/workspace') return pathname === '/workspace' || pathname?.startsWith('/workspace/channels');
    return pathname?.startsWith(href);
  };

  return (
    <div className="w-60 flex-shrink-0 bg-vault-darker border-r border-vault-border/50 flex flex-col h-full">
      {/* Header */}
      <div className="h-14 flex items-center gap-3 px-4 border-b border-vault-border/30">
        <div className="w-8 h-8 bg-gradient-to-br from-primary-500 to-purple-600 rounded-lg flex items-center justify-center text-white font-bold text-xs">
          DV
        </div>
        <div className="flex-1 min-w-0">
          <h1 className="text-sm font-semibold truncate">DrevStudio</h1>
          <p className="text-[10px] text-vault-muted">Vault Workspace</p>
        </div>
      </div>

      {/* Navigation */}
      <div className="px-2 py-2 space-y-0.5">
        {navItems.map((item) => (
          <button
            key={item.href}
            onClick={() => router.push(item.href)}
            className={cn(
              'sidebar-item w-full text-xs',
              isActive(item.href) && 'active'
            )}
          >
            <item.icon className="w-4 h-4 flex-shrink-0" />
            <span className="flex-1 text-left">{item.label}</span>
            {item.badge ? (
              <span className="bg-primary-500 text-white text-[10px] font-medium px-1.5 py-0.5 rounded-full min-w-[18px] text-center">
                {item.badge}
              </span>
            ) : null}
          </button>
        ))}
      </div>

      {/* Separator */}
      <div className="px-4 py-1.5">
        <div className="h-px bg-vault-border/30" />
      </div>

      {/* Categories & Channels */}
      <div className="flex-1 overflow-y-auto scrollbar-thin px-2">
        <div className="flex items-center justify-between mb-2">
          <span className="text-[10px] font-semibold text-vault-muted uppercase tracking-wider">Channels</span>
          {canManage && (
            <button
              onClick={() => setShowCreateCat(!showCreateCat)}
              className="text-vault-muted hover:text-vault-text transition-colors"
            >
              <Plus className="w-3.5 h-3.5" />
            </button>
          )}
        </div>

        <AnimatePresence>
          {showCreateCat && (
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{ height: 'auto', opacity: 1 }}
              exit={{ height: 0, opacity: 0 }}
              className="overflow-hidden mb-2"
            >
              <div className="flex gap-1">
                <input
                  value={newCatName}
                  onChange={(e) => setNewCatName(e.target.value)}
                  placeholder="Category name"
                  className="flex-1 bg-vault-surface border border-vault-border rounded px-2 py-1 text-xs text-vault-text placeholder-vault-muted/50 focus:outline-none focus:border-primary-500/50"
                  onKeyDown={(e) => e.key === 'Enter' && createCategory()}
                />
                <button onClick={createCategory} className="btn-primary text-xs px-2 py-1">Add</button>
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {categories.map((cat) => (
          <div key={cat.id} className="mb-1">
            <button
              onClick={() => toggleCollapse(cat.id)}
              className="flex items-center gap-1.5 w-full px-1 py-1 rounded text-[11px] text-vault-muted hover:text-vault-text transition-colors"
            >
              {collapsed[cat.id] ? <ChevronRight className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
              <span className="font-medium truncate">{cat.name}</span>
              {canManage && (
                <button
                  onClick={(e) => { e.stopPropagation(); setShowCreateCh(cat.id); setNewChName(''); }}
                  className="ml-auto text-vault-muted hover:text-vault-text"
                >
                  <Plus className="w-3 h-3" />
                </button>
              )}
            </button>

            <AnimatePresence>
              {!collapsed[cat.id] && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                >
                  {showCreateCh === cat.id && (
                    <div className="flex gap-1 ml-4 mb-1">
                      <input
                        value={newChName}
                        onChange={(e) => setNewChName(e.target.value)}
                        placeholder="channel-name"
                        className="flex-1 bg-vault-surface border border-vault-border rounded px-2 py-1 text-xs text-vault-text placeholder-vault-muted/50 focus:outline-none focus:border-primary-500/50"
                        onKeyDown={(e) => e.key === 'Enter' && createChannel(cat.id)}
                      />
                      <button onClick={() => createChannel(cat.id)} className="btn-primary text-xs px-2 py-1">+</button>
                    </div>
                  )}
                  {cat.channels?.map((ch: any) => (
                    <button
                      key={ch.id}
                      onClick={() => navigateToChannel(ch)}
                      className={cn(
                        'sidebar-item w-full text-xs py-1 ml-2',
                        pathname === `/workspace/channels/${ch.id}` && 'active'
                      )}
                    >
                      <Hash className="w-3.5 h-3.5 flex-shrink-0" />
                      <span className="truncate">{ch.name}</span>
                    </button>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        ))}
      </div>

      {/* User footer */}
      <div className="h-14 border-t border-vault-border/30 px-3 flex items-center gap-2.5">
        <div className="relative">
          <div className="w-8 h-8 rounded-full bg-gradient-to-br from-primary-500 to-purple-600 flex items-center justify-center text-white text-xs font-medium">
            {user?.displayName?.[0] || user?.username?.[0] || 'U'}
          </div>
          <span className={cn(
            'status-dot absolute -bottom-0.5 -right-0.5',
            user?.onlineStatus === 'ONLINE' ? 'bg-green-500' :
            user?.onlineStatus === 'IDLE' ? 'bg-yellow-500' :
            user?.onlineStatus === 'BUSY' ? 'bg-red-500' : 'bg-gray-500'
          )} />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-xs font-medium truncate">{user?.displayName || user?.username}</p>
          <p className="text-[10px] text-vault-muted capitalize">{user?.role?.toLowerCase()}</p>
        </div>
        <button onClick={logout} className="text-vault-muted hover:text-red-400 transition-colors">
          <LogOut className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}
