"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { createBrowserClient } from "@supabase/ssr";
import { type User } from "@supabase/supabase-js";
import { Rocket, Menu, X, User as UserIcon, LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { signOut } from "@/lib/actions/auth";
import { resolveSupabaseUrl } from "@/lib/utils";

interface NavbarClientProps {
  user: User | null;
  role?: string;
}

export function NavbarClient({ user, role = "partner" }: NavbarClientProps) {
  const router = useRouter();
  const [currentUser, setCurrentUser] = useState<User | null>(user);
  const [userRole, setUserRole] = useState<string>(role);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [open, setOpen] = useState(false);
  const [pathname, setPathname] = useState("/");

  useEffect(() => {
    setPathname(window.location.pathname);
  }, []);

  // Supabase URL & Anon Key auslesen (für Browser-Client)
  const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL;
  const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

  // Browser Client inline erstellen
  const supabase = createBrowserClient(
    resolveSupabaseUrl(supabaseUrl)!,
    supabaseAnonKey!,
    {
      cookieOptions: {
        name: "webshop-auth-token",
      },
    }
  );

  // Auf Auth-Statusänderungen reagieren
  useEffect(() => {
    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange(async (event, session) => {
      setCurrentUser(session?.user ?? null);
      if (session?.user) {
        try {
          const { data } = await supabase
            .from("users")
            .select("role")
            .eq("id", session.user.id)
            .single();
          if (data) {
            setUserRole(data.role);
          }
        } catch {
          setUserRole("partner");
        }
      } else {
        setUserRole("partner");
      }
    });

    return () => {
      subscription.unsubscribe();
    };
  }, [supabase]);

  useEffect(() => {
    const checkBanner = () => {
      const disabled = localStorage.getItem('demo_banner_disabled') === 'true';
      const banner = document.getElementById('demo-banner');
      if (banner) banner.style.display = disabled ? 'none' : 'block';
    };

    checkBanner();
    window.addEventListener('storage_demo_changed', checkBanner);
    return () => window.removeEventListener('storage_demo_changed', checkBanner);
  }, []);

  const handleSignOut = async () => {
    try {
      await signOut();
    } catch (e) {
      console.error("Fehler beim Server-Signout:", e);
    }
    await supabase.auth.signOut();
    setCurrentUser(null);
    setIsMobileMenuOpen(false);
    router.push("/");
    router.refresh();
  };

  return (
    <>
      <header className="px-4 lg:px-6 h-16 flex items-center justify-between border-b border-white/5 backdrop-blur-md sticky top-0 z-50 bg-[#020617]/85">
        <Link className="flex items-center justify-center gap-2 group" href="/">
          <span className="font-bold text-xl tracking-tighter text-white">CASPOS Store</span>
          <span className="text-[10px] bg-amber-500/20 text-amber-400 px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider border border-amber-500/30">
            Demo
          </span>
        </Link>

        {/* Desktop Navigation */}
        <nav className="hidden md:flex gap-6 items-center">
          <Link
            className="text-sm font-medium text-slate-300 hover:text-primary transition-colors"
            href="https://wiki.caspos.de"
            target="_blank"
            rel="noopener noreferrer"
          >
            Zulip
          </Link>
          <Link
            className="text-sm font-medium text-slate-300 hover:text-primary transition-colors"
            href="https://wiki.caspos.de"
            target="_blank"
            rel="noopener noreferrer"
          >
            Wiki
          </Link>
          <Link
            className="text-sm font-medium text-slate-300 hover:text-primary transition-colors"
            href="https://support.caspos.de"
            target="_blank"
            rel="noopener noreferrer"
          >
            Support
          </Link>

          <div className="h-4 w-px bg-white/10 mx-2" />

          {currentUser ? (
            <div className="relative">
              <Button
                variant="outline"
                onClick={() => setOpen(!open)}
                className="border-white/10 hover:bg-white/5 gap-2 text-white"
              >
                <UserIcon className="w-4 h-4 text-primary" />
                <span className="max-w-[120px] truncate">{currentUser.email}</span>
              </Button>
              {open && (
                <div className="absolute right-0 mt-2 w-48 rounded-xl border p-2 shadow-xl z-50 bg-white text-slate-900 border-slate-200 dark:bg-slate-950 dark:text-white dark:border-white/10">
                  <div className="px-3 py-1.5 text-[11px] truncate border-b text-slate-400 border-slate-100 dark:border-white/5 mb-1">
                    {currentUser.email}
                  </div>
                  {userRole === "admin" ? (
                    <>
                      <Link
                        href="/admin/einstellungen"
                        onClick={() => setOpen(false)}
                        className="block px-3 py-2 text-sm rounded-lg font-medium hover:bg-slate-100 dark:hover:bg-white/5"
                      >
                        Admin
                      </Link>
                    </>
                  ) : (
                    <>
                      <Link
                        href="/account-kunden"
                        onClick={() => setOpen(false)}
                        className="block px-3 py-2 text-sm rounded-lg font-medium hover:bg-slate-100 dark:hover:bg-white/5"
                      >
                        Account Einstellungen
                      </Link>
                      <Link
                        href="/my-customers"
                        onClick={() => setOpen(false)}
                        className="block px-3 py-2 text-sm rounded-lg font-medium hover:bg-slate-100 dark:hover:bg-white/5"
                      >
                        Kundenliste
                      </Link>
                    </>
                  )}
                  <hr className="my-1 border-slate-100 dark:border-white/5" />
                  <button
                    onClick={handleSignOut}
                    className="w-full text-left px-3 py-2 text-sm font-bold text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-500/10 rounded-lg"
                  >
                    Abmelden
                  </button>
                </div>
              )}

            </div>
          ) : (
            <Button asChild className="bg-primary hover:bg-primary/95 text-white dark:text-blue-500">
              <Link href={`/auth/login?next=${pathname}`}>Anmelden</Link>
            </Button>
          )}
        </nav>

        {/* Mobile Hamburger Trigger */}
        <button
          className="md:hidden p-2 text-slate-300 hover:text-white focus:outline-none"
          onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
        >
          {isMobileMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
        </button>
      </header>

      {/* Mobile Menu Panel */}
      {isMobileMenuOpen && (
        <div className="md:hidden fixed inset-x-0 top-16 bg-[#020617] border-b border-white/5 z-40 py-4 px-6 flex flex-col gap-4 animate-in slide-in-from-top duration-200">
          <Link
            className="text-lg font-medium text-slate-300 hover:text-white transition-colors py-2"
            href="/order"
            onClick={() => setIsMobileMenuOpen(false)}
          >
            Bestellen
          </Link>
          <Link
            className="text-lg font-medium text-slate-300 hover:text-white transition-colors py-2"
            href="https://caspos.de"
            target="_blank"
            rel="noopener noreferrer"
            onClick={() => setIsMobileMenuOpen(false)}
          >
            Wiki
          </Link>
          <Link
            className="text-lg font-medium text-slate-300 hover:text-white transition-colors py-2"
            href="https://caspos.de"
            target="_blank"
            rel="noopener noreferrer"
            onClick={() => setIsMobileMenuOpen(false)}
          >
            Support
          </Link>

          {currentUser && (
            <>
              <div className="h-px bg-white/5 my-1" />
              <div className="text-xs text-slate-500 px-1">Mein Account ({currentUser.email})</div>
              {userRole === "admin" ? (
                <>
                  <Link
                    className="text-lg font-medium text-slate-300 hover:text-white transition-colors py-2"
                    href="/admin/einstellungen"
                    onClick={() => setIsMobileMenuOpen(false)}
                  >
                    Admin
                  </Link>
                </>
              ) : (
                <>
                  <Link
                    className="text-lg font-medium text-slate-300 hover:text-white transition-colors py-2"
                    href="/my-customers"
                    onClick={() => setIsMobileMenuOpen(false)}
                  >
                    Kundenliste
                  </Link>
                </>
              )}
            </>
          )}

          <div className="h-px bg-white/5 my-1" />

          {currentUser ? (
            <Button
              variant="destructive"
              className="w-full flex items-center justify-center gap-2"
              onClick={handleSignOut}
            >
              <LogOut className="w-4 h-4" /> Abmelden
            </Button>
          ) : (
            <Button asChild className="w-full bg-primary hover:bg-primary/95 text-white dark:text-blue-500" onClick={() => setIsMobileMenuOpen(false)}>
              <Link href={`/auth/login?next=${pathname}`}>Anmelden</Link>
            </Button>
          )}
        </div>
      )}
    </>
  );
}
