import { useState } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  LayoutDashboard, Users, MessageSquare, Settings,
  ChevronLeft, ChevronDown, Sparkles, Key, UserCog, Server,
  Image, BarChart3, HelpCircle, Send, Wand2,
} from 'lucide-react';
import NotificationDropdown from './NotificationDropdown';

interface NavChild {
  label: string;
  path: string;
  icon: typeof LayoutDashboard;
}

interface NavItem {
  label: string;
  path: string;
  icon: typeof LayoutDashboard;
  color: string;
  match: (p: string) => boolean;
  children?: NavChild[];
}

const navItems: NavItem[] = [
  { label: 'Ana Sayfa', path: '/dashboard', icon: LayoutDashboard, color: 'text-indigo-400', match: (p) => p === '/dashboard' },
  { label: 'Karakterler', path: '/characters', icon: Users, color: 'text-violet-400', match: (p) => p.startsWith('/characters') },
  { label: 'Görseller', path: '/templates', icon: Image, color: 'text-pink-400', match: (p) => p.startsWith('/templates') },
  { label: 'Görsel Üret', path: '/image-generate', icon: Wand2, color: 'text-fuchsia-400', match: (p) => p === '/image-generate' },
  { label: 'Konuşmalar', path: '/conversations', icon: MessageSquare, color: 'text-emerald-400', match: (p) => p.startsWith('/conversations') },
  { label: 'Analitik', path: '/analytics', icon: BarChart3, color: 'text-amber-400', match: (p) => p.startsWith('/analytics') },
  {
    label: 'Telegram Yönetimi', path: '/telegram/webhooks', icon: Send, color: 'text-sky-400',
    match: (p) => p.startsWith('/telegram'),
    children: [
      { label: 'Webhook Ayarları', path: '/telegram/webhooks', icon: Server },
      { label: 'Kanallar', path: '/telegram/channels', icon: MessageSquare },
      { label: 'Mesajlar', path: '/telegram/messages', icon: MessageSquare },
      { label: 'Stars Gelir', path: '/telegram/stars', icon: Key },
    ],
  },
  {
    label: 'Ayarlar', path: '/settings', icon: Settings, color: 'text-slate-400',
    match: (p) => p.startsWith('/settings'),
    children: [
      { label: 'API Anahtarları', path: '/settings/api', icon: Key },
      { label: 'Konuşma Tarzı', path: '/settings/persona', icon: UserCog },
      { label: 'Sistem', path: '/settings', icon: Server },
    ],
  },
  { label: 'Rehber', path: '/guide', icon: HelpCircle, color: 'text-cyan-400', match: (p) => p === '/guide' },
];

const W_OPEN = 260;
const W_CLOSED = 72;

export default function Layout() {
  const [collapsed, setCollapsed] = useState(false);
  const [expandedNav, setExpandedNav] = useState<string | null>('/settings');
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const w = collapsed ? W_CLOSED : W_OPEN;

  return (
    <div className="flex min-h-screen bg-[#0a0a12]">
      <motion.aside
        animate={{ width: w }}
        transition={{ type: 'spring', stiffness: 300, damping: 30 }}
        className="fixed top-0 left-0 h-screen z-40 flex flex-col border-r border-white/[0.06] bg-[#0f0f1a]"
      >
        {/* Brand */}
        <button
          onClick={() => navigate('/')}
          className="flex items-center gap-3 px-5 h-16 shrink-0 border-b border-white/[0.06] cursor-pointer hover:bg-white/[0.02] transition-colors"
        >
          <div className="flex items-center justify-center w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-violet-600 shadow-lg shadow-indigo-500/20 shrink-0">
            <Sparkles className="w-5 h-5 text-white" />
          </div>
          <AnimatePresence>
            {!collapsed && (
              <motion.div initial={{ opacity: 0, x: -8 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -8 }} className="overflow-hidden whitespace-nowrap">
                <span className="text-[15px] font-bold text-white tracking-tight">AI Content Creator</span>
                <span className="block text-[10px] text-slate-500 tracking-widest uppercase mt-0.5">by Baever</span>
              </motion.div>
            )}
          </AnimatePresence>
        </button>

        {/* Menu label */}
        <AnimatePresence>
          {!collapsed && (
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="px-5 pt-5 pb-2">
              <span className="text-[10px] font-semibold text-slate-600 uppercase tracking-[0.15em]">Ana Menü</span>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Nav */}
        <nav className="flex-1 px-3 space-y-1 overflow-y-auto pb-4">
          {navItems.map((item) => {
            const active = item.match(pathname);
            const Icon = item.icon;
            const hasChildren = item.children && item.children.length > 0;
            const isExpanded = expandedNav === item.path;
            return (
              <div key={item.path}>
                <button
                  onClick={() => {
                    if (hasChildren && !collapsed) { setExpandedNav(isExpanded ? null : item.path); }
                    else { navigate(item.path); }
                  }}
                  title={collapsed ? item.label : undefined}
                  className={`relative flex items-center gap-3 w-full rounded-xl px-3 py-2.5 transition-all cursor-pointer group ${
                    active ? 'bg-gradient-to-r from-indigo-500/[0.12] to-violet-500/[0.08] text-white shadow-sm' : 'text-slate-400 hover:text-white hover:bg-white/[0.04]'
                  }`}
                >
                  {active && <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />}
                  <div className={`flex items-center justify-center w-8 h-8 rounded-lg shrink-0 transition-colors ${
                    active ? 'bg-indigo-500/20' : 'bg-white/[0.04] group-hover:bg-white/[0.08]'
                  }`}>
                    <Icon className={`w-[18px] h-[18px] ${active ? item.color : 'text-slate-500 group-hover:text-slate-300'}`} />
                  </div>
                  <AnimatePresence>
                    {!collapsed && (
                      <motion.span initial={{ opacity: 0, width: 0 }} animate={{ opacity: 1, width: 'auto' }} exit={{ opacity: 0, width: 0 }}
                        className="text-[13px] font-medium overflow-hidden whitespace-nowrap flex-1 text-left">
                        {item.label}
                      </motion.span>
                    )}
                  </AnimatePresence>
                  {hasChildren && !collapsed && (
                    <motion.div animate={{ rotate: isExpanded ? 180 : 0 }} transition={{ duration: 0.2 }}>
                      <ChevronDown className="w-4 h-4 text-slate-600" />
                    </motion.div>
                  )}
                </button>
                <AnimatePresence>
                  {hasChildren && isExpanded && !collapsed && (
                    <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={{ duration: 0.2 }} className="overflow-hidden">
                      <div className="ml-5 mt-1 space-y-0.5 border-l border-white/[0.06] pl-4">
                        {item.children!.map((child) => {
                          const childActive = pathname === child.path;
                          const ChildIcon = child.icon;
                          return (
                            <button key={child.path} onClick={() => navigate(child.path)}
                              className={`flex items-center gap-2.5 w-full text-left rounded-lg px-3 py-2 text-[12px] transition-all cursor-pointer ${
                                childActive ? 'text-indigo-400 bg-indigo-500/[0.08]' : 'text-slate-500 hover:text-slate-300 hover:bg-white/[0.03]'
                              }`}>
                              <ChildIcon className="w-3.5 h-3.5" />
                              {child.label}
                            </button>
                          );
                        })}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            );
          })}
        </nav>

        {/* Collapse */}
        <div className="shrink-0 border-t border-white/[0.06] p-3">
          <button onClick={() => setCollapsed(c => !c)}
            className="flex items-center justify-center w-full rounded-xl py-2.5 text-slate-600 hover:text-slate-400 hover:bg-white/[0.04] transition-all cursor-pointer">
            <motion.div animate={{ rotate: collapsed ? 180 : 0 }}><ChevronLeft className="w-4 h-4" /></motion.div>
          </button>
        </div>
      </motion.aside>

      {/* Main content */}
      <motion.div animate={{ marginLeft: w }} transition={{ type: 'spring', stiffness: 300, damping: 30 }} className="flex-1 min-h-screen flex flex-col">
        {/* Top bar */}
        <header className="sticky top-0 z-30 h-16 border-b border-white/[0.06] bg-[#0a0a12]/80 backdrop-blur-xl flex items-center justify-between px-8">
          <div />
          <div className="flex items-center gap-3">
            <NotificationDropdown />
            <div className="w-px h-6 bg-white/[0.06]" />
            <div className="flex items-center gap-2.5 pl-2">
              <div className="w-8 h-8 rounded-full bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center text-white text-xs font-bold">A</div>
              <div className="text-right">
                <div className="text-[13px] font-medium text-slate-200">Admin</div>
                <div className="text-[10px] text-slate-500">Baever</div>
              </div>
            </div>
          </div>
        </header>
        <main className="flex-1 p-8"><Outlet /></main>
      </motion.div>
    </div>
  );
}
