import {
  Activity,
  BarChart3,
  Bell,
  ChevronRight,
  Compass,
  DollarSign,
  FileText,
  Globe,
  Home,
  Image as ImageIcon,
  Key,
  LayoutDashboard,
  Link2,
  Loader2,
  LogOut,
  Mail,
  MapPin,
  Menu,
  Package,
  Plane,
  Search,
  Settings,
  Shield,
  Sparkles,
  User,
  Users,
  Wallet,
  Webhook,
} from 'lucide-react';
import { useEffect } from 'react';
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { useAuth } from '@/contexts/AuthContext';
import { cn } from '@/lib/utils';

interface NavSection {
  title: string;
  items: NavItem[];
}

interface NavItem {
  path: string;
  icon: React.ElementType;
  label: string;
  badge?: string;
}

const adminNavSections: NavSection[] = [
  {
    title: 'Genel Bakış',
    items: [
      { path: '/admin', icon: LayoutDashboard, label: 'Dashboard' },
      { path: '/admin/analytics', icon: BarChart3, label: 'Analitik' },
      { path: '/admin/persona-analytics', icon: Users, label: 'Persona Analizi' },
    ],
  },
  {
    title: 'İçerik Yönetimi',
    items: [
      { path: '/admin/places', icon: MapPin, label: 'Yerler' },
      { path: '/admin/tours', icon: Compass, label: 'Turlar' },
      { path: '/admin/images', icon: ImageIcon, label: 'Görseller' },
      { path: '/admin/seo-settings', icon: Globe, label: 'SEO Ayarları' },
      { path: '/admin/page-seo', icon: Search, label: 'Sayfa SEO' },
      { path: '/admin/url-redirects', icon: Link2, label: 'URL Yönlendirme' },
    ],
  },
  {
    title: 'Kullanıcı Yönetimi',
    items: [
      { path: '/admin/users', icon: Users, label: 'Kullanıcılar' },
      { path: '/admin/providers-management', icon: Wallet, label: 'Sağlayıcılar' },
    ],
  },
  {
    title: 'İş Operasyonları',
    items: [
      { path: '/admin/leads', icon: Package, label: 'Leadler' },
      { path: '/admin/trips', icon: Plane, label: 'Seyahatler' },
    ],
  },
  {
    title: 'Sistem Ayarları',
    items: [
      { path: '/admin/settings', icon: Settings, label: 'Genel Ayarlar' },
      { path: '/admin/pricing', icon: DollarSign, label: 'Fiyatlandırma' },
      { path: '/admin/rate-limits', icon: Shield, label: 'Hız Limitleri' },
      { path: '/admin/notifications', icon: Bell, label: 'Bildirimler' },
      { path: '/admin/email-templates', icon: Mail, label: 'E-posta Şablonları' },
      { path: '/admin/api-keys', icon: Key, label: 'API Anahtarları' },
      { path: '/admin/webhooks', icon: Webhook, label: 'Webhooks' },
      { path: '/admin/ai-search', icon: Sparkles, label: 'AI Arama' },
      { path: '/admin/logs', icon: FileText, label: 'Sistem Logları' },
      { path: '/admin/system-health', icon: Activity, label: 'Sistem Sağlığı' },
    ],
  },
];

export default function AdminLayout() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, profile, signOut } = useAuth();

  useEffect(() => {
    // Profile yüklendi ve admin değilse ana sayfaya yönlendir
    if (profile && profile.role !== 'admin') {
      const timer = setTimeout(() => {
        navigate('/');
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [profile, navigate]);

  const handleSignOut = async () => {
    await signOut();
    navigate('/');
  };

  // Get current page title from path
  const getCurrentPageTitle = () => {
    for (const section of adminNavSections) {
      const item = section.items.find(i => i.path === location.pathname);
      if (item) return item.label;
    }
    return 'Dashboard';
  };

  // Get breadcrumbs
  const getBreadcrumbs = () => {
    const paths = location.pathname.split('/').filter(Boolean);
    return paths.map((path, index) => {
      const fullPath = `/${paths.slice(0, index + 1).join('/')}`;
      let label = path.charAt(0).toUpperCase() + path.slice(1);
      
      // Find label from nav items
      for (const section of adminNavSections) {
        const item = section.items.find(i => i.path === fullPath);
        if (item) {
          label = item.label;
          break;
        }
      }
      
      return { path: fullPath, label };
    });
  };

  const NavContent = () => (
    <div className="flex flex-col h-full">
      <div className="p-6 border-b">
        <Link to="/" className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-white">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="h-5 w-5"
            >
              <path d="M22 10v6M2 10l10-7 10 7M2 10v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6M12 18v-5" />
            </svg>
          </div>
          <div>
            <span className="text-lg font-bold">LetsGoCappadocia</span>
            <span className="block text-xs text-muted-foreground">Admin Panel</span>
          </div>
        </Link>
      </div>

      <nav className="flex-1 p-4 space-y-6 overflow-y-auto">
        {adminNavSections.map((section, sectionIndex) => (
          <div key={sectionIndex}>
            <h3 className="px-4 mb-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
              {section.title}
            </h3>
            <div className="space-y-1">
              {section.items.map((item) => {
                const Icon = item.icon;
                const isActive = location.pathname === item.path;
                return (
                  <Link
                    key={item.path}
                    to={item.path}
                    className={cn(
                      'flex items-center gap-3 px-4 py-2.5 rounded-lg transition-colors relative text-sm',
                      isActive
                        ? 'bg-primary text-white'
                        : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                    )}
                  >
                    <Icon className="h-4 w-4 shrink-0" />
                    <span className="font-medium">{item.label}</span>
                    {item.badge && (
                      <span className="ml-auto text-xs bg-primary text-white px-2 py-0.5 rounded-full">
                        {item.badge}
                      </span>
                    )}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      <Separator />

      <div className="p-4">
        <Link
          to="/profile"
          className={cn(
            'flex items-center gap-3 px-4 py-2.5 rounded-lg transition-colors mb-2 text-sm',
            location.pathname === '/profile'
              ? 'bg-primary text-white'
              : 'text-muted-foreground hover:bg-muted hover:text-foreground'
          )}
        >
          <User className="h-4 w-4" />
          <span className="font-medium">Profilim</span>
        </Link>
        
        <div className="flex items-center gap-3 px-4 py-3 mb-2 bg-muted/50 rounded-lg">
          <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold">
            {profile?.username?.charAt(0).toUpperCase() || 'A'}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium truncate">{profile?.username}</p>
            <p className="text-xs text-muted-foreground">Admin</p>
          </div>
        </div>
        
        <Button
          variant="ghost"
          className="w-full justify-start text-muted-foreground hover:text-destructive"
          onClick={handleSignOut}
        >
          <LogOut className="h-4 w-4 mr-3" />
          Çıkış Yap
        </Button>
      </div>

      <div className="p-4 border-t bg-muted/30">
        <p className="text-xs text-center text-muted-foreground">
          © 2026 LetsGoCappadocia
        </p>
        <p className="text-xs text-center text-muted-foreground mt-1">
          v1.0.0
        </p>
      </div>
    </div>
  );

  // Profile henüz yüklenmediyse (null), tam ekran loading spinner göster
  if (!profile) {
    return (
      <div className="flex h-screen w-full items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
          <p className="text-sm text-muted-foreground">Profiliniz yükleniyor...</p>
        </div>
      </div>
    );
  }

  // Profile yüklendi ama admin değilse, hata mesajı göster ve yönlendir
  if (!user || profile.role !== 'admin') {
    return (
      <div className="flex h-screen w-full flex-col items-center justify-center bg-background p-4 text-center">
        <Shield className="h-12 w-12 text-destructive mb-4" />
        <h1 className="text-2xl font-bold mb-2">Erişim Engellendi</h1>
        <p className="text-muted-foreground mb-6">
          Admin paneline erişim yetkiniz bulunmamaktadır. Ana sayfaya yönlendiriliyorsunuz...
        </p>
        <Button onClick={() => navigate('/')}>Ana Sayfaya Dön</Button>
      </div>
    );
  }

  const breadcrumbs = getBreadcrumbs();

  return (
    <div className="flex h-screen overflow-hidden bg-muted/30">
      {/* Desktop Sidebar */}
      <aside className="hidden lg:flex w-72 flex-col border-r bg-background shadow-sm">
        <NavContent />
      </aside>

      {/* Main Content */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Header with Breadcrumbs */}
        <header className="border-b bg-background">
          <div className="flex items-center justify-between p-4">
            <div className="flex items-center gap-4">
              {/* Mobile Menu */}
              <Sheet>
                <SheetTrigger asChild>
                  <Button variant="ghost" size="icon" className="lg:hidden">
                    <Menu className="h-6 w-6" />
                  </Button>
                </SheetTrigger>
                <SheetContent side="left" className="w-72 p-0">
                  <NavContent />
                </SheetContent>
              </Sheet>

              {/* Breadcrumbs */}
              <div className="flex items-center gap-2 text-sm">
                <Link to="/" className="text-muted-foreground hover:text-foreground transition-colors">
                  <Home className="h-4 w-4" />
                </Link>
                {breadcrumbs.map((crumb, index) => (
                  <div key={crumb.path} className="flex items-center gap-2">
                    <ChevronRight className="h-4 w-4 text-muted-foreground" />
                    {index === breadcrumbs.length - 1 ? (
                      <span className="font-medium text-foreground">{crumb.label}</span>
                    ) : (
                      <Link
                        to={crumb.path}
                        className="text-muted-foreground hover:text-foreground transition-colors"
                      >
                        {crumb.label}
                      </Link>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* Quick Actions */}
            <div className="flex items-center gap-2">
              <Button variant="ghost" size="icon" className="relative">
                <Bell className="h-5 w-5" />
                <span className="absolute top-1 right-1 h-2 w-2 bg-destructive rounded-full" />
              </Button>
              <Button variant="outline" size="sm" asChild>
                <Link to="/">
                  <Home className="h-4 w-4 mr-2" />
                  Ana Sayfa
                </Link>
              </Button>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <main className="flex-1 overflow-auto">
          <Outlet />
        </main>
      </div>
    </div>
  );
}
