"use client";

import Image from "next/image";
import { deleteAuth, getAuth } from "../../api/auth";
import { Button } from "@mui/material";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

interface AuthPayload {
  token?: string;
  email?: string;
  name?: string;
  [k: string]: unknown;
}

export default function Header() {
  const router = useRouter();
  const [mounted, setMounted] = useState(false);
  const [auth, setAuth] = useState<AuthPayload | string | null>(null);

  useEffect(() => {
    setMounted(true);
    const a = getAuth() as AuthPayload | string | null;
    setAuth(a);
  }, []);

  const onLogout = () => {
    deleteAuth();
    router.push("/login");
  };

  if (!mounted) return null;

  return (
    <header className="fixed top-0 left-0 right-0 z-50 bg-white shadow-sm">
      <div className="max-w-screen-xl mx-auto flex items-center justify-between p-3">
        <div className="flex items-center gap-2">
          <Image src="/favicon.ico" width={32} height={32} alt="logo" />
          <span className="font-semibold">indoteknik</span>
        </div>
        <div className="flex items-center gap-3">
          <span className="text-sm text-gray-600">
            {typeof auth === "object" && auth?.email ? auth.email : ""}
          </span>
          <Button size="small" variant="text" color="error" onClick={onLogout}>
            Logout
          </Button>
        </div>
      </div>
    </header>
  );
}
