"use client";

import Image from "next/image";
import Link from "next/link";
import { useState, useEffect } from "react";
import { Menu, X, LogIn, UserPlus, LogOut, User } from "lucide-react";
import { Button } from "@/components/ui/button";
import { createClient } from "@/lib/supabase/client";
import type { User as SupabaseUser } from "@supabase/supabase-js";

const navLinks = [
  { href: "home", label: "Home" },
  { href: "about", label: "About Us" },
  { href: "certifications", label: "Certifications" },
  { href: "customers", label: "Our Customers" },
  { href: "profile", label: "Our Profile" },
];

export function Header() {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [user, setUser] = useState<SupabaseUser | null>(null);
  const [loading, setLoading] = useState(true);
  const supabase = createClient();

  useEffect(() => {
    const getUser = async () => {
      const { data: { user } } = await supabase.auth.getUser();
      setUser(user);
      setLoading(false);
    };
    getUser();

    const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
      setUser(session?.user ?? null);
    });

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

  const handleSignOut = async () => {
    await supabase.auth.signOut();
    setUser(null);
  };

  const scrollToSection = (sectionId: string) => {
    const element = document.getElementById(sectionId);
    if (element) {
      const headerOffset = 80;
      const elementPosition = element.getBoundingClientRect().top;
      const offsetPosition = elementPosition + window.scrollY - headerOffset;

      window.scrollTo({
        top: offsetPosition,
        behavior: "smooth",
      });
    }
    setMobileMenuOpen(false);
  };

  return (
    <header className="fixed top-0 left-0 right-0 z-50 bg-background/95 backdrop-blur-sm border-b border-border">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-20">
          <Link href="/" className="flex-shrink-0">
            <Image
              src="/logo.png"
              alt="BD Knit Design Ltd. Logo"
              width={160}
              height={60}
              className="h-12 w-auto mix-blend-multiply"
              priority
            />
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden lg:flex items-center gap-6">
            {navLinks.map((link) => (
              <button
                key={link.href}
                type="button"
                onClick={() => scrollToSection(link.href)}
                className="text-foreground/80 hover:text-primary transition-colors font-medium text-sm cursor-pointer"
              >
                {link.label}
              </button>
            ))}
            <Button onClick={() => scrollToSection("contact")}>
              Contact Us
            </Button>
            
            {/* Auth Buttons */}
            {!loading && (
              <>
                {user ? (
                  <div className="flex items-center gap-3">
                    <span className="text-sm text-muted-foreground flex items-center gap-1">
                      <User className="h-4 w-4" />
                      {user.email?.split('@')[0]}
                    </span>
                    <Button variant="outline" size="sm" onClick={handleSignOut}>
                      <LogOut className="h-4 w-4 mr-1" />
                      Sign Out
                    </Button>
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <Button variant="outline" size="sm" asChild>
                      <Link href="/auth/login">
                        <LogIn className="h-4 w-4 mr-1" />
                        Sign In
                      </Link>
                    </Button>
                    <Button size="sm" asChild>
                      <Link href="/auth/sign-up">
                        <UserPlus className="h-4 w-4 mr-1" />
                        Sign Up
                      </Link>
                    </Button>
                  </div>
                )}
              </>
            )}
          </nav>

          {/* Mobile Menu Button */}
          <button
            type="button"
            className="lg:hidden p-2"
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            aria-label="Toggle menu"
          >
            {mobileMenuOpen ? (
              <X className="h-6 w-6 text-foreground" />
            ) : (
              <Menu className="h-6 w-6 text-foreground" />
            )}
          </button>
        </div>

        {/* Mobile Navigation */}
        {mobileMenuOpen && (
          <nav className="lg:hidden py-4 border-t border-border">
            <div className="flex flex-col gap-4">
              {navLinks.map((link) => (
                <button
                  key={link.href}
                  type="button"
                  onClick={() => scrollToSection(link.href)}
                  className="text-foreground/80 hover:text-primary transition-colors font-medium py-2 text-left cursor-pointer"
                >
                  {link.label}
                </button>
              ))}
              <Button className="w-full mt-2" onClick={() => scrollToSection("contact")}>
                Contact Us
              </Button>
              
              {/* Mobile Auth Buttons */}
              {!loading && (
                <div className="pt-4 border-t border-border">
                  {user ? (
                    <div className="flex flex-col gap-2">
                      <span className="text-sm text-muted-foreground flex items-center gap-1">
                        <User className="h-4 w-4" />
                        {user.email}
                      </span>
                      <Button variant="outline" className="w-full bg-transparent" onClick={handleSignOut}>
                        <LogOut className="h-4 w-4 mr-1" />
                        Sign Out
                      </Button>
                    </div>
                  ) : (
                    <div className="flex flex-col gap-2">
                      <Button variant="outline" className="w-full bg-transparent" asChild>
                        <Link href="/auth/login" onClick={() => setMobileMenuOpen(false)}>
                          <LogIn className="h-4 w-4 mr-1" />
                          Sign In
                        </Link>
                      </Button>
                      <Button className="w-full" asChild>
                        <Link href="/auth/sign-up" onClick={() => setMobileMenuOpen(false)}>
                          <UserPlus className="h-4 w-4 mr-1" />
                          Sign Up
                        </Link>
                      </Button>
                    </div>
                  )}
                </div>
              )}
            </div>
          </nav>
        )}
      </div>
    </header>
  );
}
