"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
import { Building2, Linkedin, Search, BarChart3, Settings, Zap, ChevronLeft, ChevronRight, MapPin, Database } from "lucide-react";
import { useAppStore } from "@/lib/store";
import { useEffect, useState } from "react";

const navItems = [
  { href: "/airscale", icon: Building2, label: "AirScale → Email", color: "text-blue-400" },
  { href: "/linkedin", icon: Linkedin, label: "LinkedIn → Email", color: "text-blue-500" },
  { href: "/serp", icon: Search, label: "SERP → Email", color: "text-purple-400" },
  { href: "/maps", icon: MapPin, label: "Maps → Email", color: "text-green-400" },
  { href: "/leadvault", icon: Database, label: "Leadspeicher", color: "text-violet-400", badge: true },
  { href: "/results", icon: BarChart3, label: "Ergebnisse & Verlauf", color: "text-yellow-400" },
  { href: "/settings", icon: Settings, label: "Einstellungen", color: "text-gray-400" },
];

interface CredentialStatus {
  anymailfinder: boolean;
  apify: boolean;
  vayne: boolean;
  googlemaps: boolean;
}

export function Sidebar() {
  const pathname = usePathname();
  const { sidebarCollapsed, setSidebarCollapsed } = useAppStore();
  const [creds, setCreds] = useState<CredentialStatus>({ anymailfinder: false, apify: false, vayne: false, googlemaps: false });
  const [newLeadsCount, setNewLeadsCount] = useState(0);

  useEffect(() => {
    fetch("/api/credentials")
      .then(r => r.json())
      .then(d => setCreds(d))
      .catch(() => {});
  }, []);

  useEffect(() => {
    function fetchNewLeads() {
      fetch("/api/leads/stats")
        .then(r => r.json())
        .then((d: { new?: number }) => setNewLeadsCount(d.new ?? 0))
        .catch(() => {});
    }
    fetchNewLeads();
    const t = setInterval(fetchNewLeads, 30000);
    return () => clearInterval(t);
  }, []);

  return (
    <aside
      className={cn(
        "relative flex flex-col border-r border-[#1e1e2e] bg-[#111118] transition-all duration-300",
        sidebarCollapsed ? "w-16" : "w-60"
      )}
    >
      {/* Logo */}
      <div className="flex items-center gap-2 px-4 py-5 border-b border-[#1e1e2e]">
        <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
          <Zap className="w-4 h-4 text-white" />
        </div>
        {!sidebarCollapsed && (
          <span className="font-bold text-lg tracking-tight text-white">LeadFlow</span>
        )}
      </div>

      {/* Nav */}
      <nav className="flex-1 px-2 py-4 space-y-1">
        {navItems.map(({ href, icon: Icon, label, color, badge }) => {
          const active = pathname === href || pathname.startsWith(href + "/");
          const showBadge = badge && newLeadsCount > 0;
          return (
            <Link
              key={href}
              href={href}
              className={cn(
                "flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all",
                active
                  ? "bg-[#1e1e2e] text-white"
                  : "text-gray-400 hover:text-white hover:bg-[#1a1a28]"
              )}
            >
              <Icon className={cn("w-5 h-5 flex-shrink-0", active ? color : "")} />
              {!sidebarCollapsed && (
                <>
                  <span className="flex-1">{label}</span>
                  {showBadge && (
                    <span className="ml-auto bg-blue-500 text-white text-[10px] font-bold rounded-full min-w-[18px] h-[18px] flex items-center justify-center px-1">
                      {newLeadsCount > 99 ? "99+" : newLeadsCount}
                    </span>
                  )}
                </>
              )}
              {sidebarCollapsed && showBadge && (
                <span className="absolute right-1 top-1 w-2 h-2 bg-blue-500 rounded-full" />
              )}
            </Link>
          );
        })}
      </nav>

      {/* Credential status */}
      {!sidebarCollapsed && (
        <div className="px-4 py-4 border-t border-[#1e1e2e] space-y-2">
          <p className="text-xs text-gray-500 uppercase tracking-wider mb-3">API-Status</p>
          {[
            { key: "anymailfinder", label: "Anymailfinder" },
            { key: "apify", label: "Apify" },
            { key: "vayne", label: "Vayne" },
            { key: "googlemaps", label: "Google Maps" },
          ].map(({ key, label }) => (
            <div key={key} className="flex items-center gap-2">
              <span className={cn("w-2 h-2 rounded-full flex-shrink-0", creds[key as keyof CredentialStatus] ? "bg-green-500" : "bg-red-500")} />
              <span className="text-xs text-gray-400">{label}</span>
            </div>
          ))}
        </div>
      )}

      {/* Collapse toggle */}
      <button
        onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
        className="absolute -right-3 top-6 w-6 h-6 rounded-full bg-[#1e1e2e] border border-[#2e2e3e] flex items-center justify-center hover:bg-[#2e2e3e] transition-colors z-10"
      >
        {sidebarCollapsed ? <ChevronRight className="w-3 h-3 text-gray-400" /> : <ChevronLeft className="w-3 h-3 text-gray-400" />}
      </button>
    </aside>
  );
}
