"use client";

import { useCallback, useEffect, useState } from "react";

const DEFAULT_LOGO_URL = "";

type BrandLogoProps = {
  className?: string;
  alt?: string;
  variant?: "sidebar" | "dashboard" | "settings";
};

type LogoResponse = {
  logoUrl?: string | null;
};

function DefaultBrandLogo({ variant }: { variant: "sidebar" | "dashboard" | "settings" }) {
  const isDashboard = variant === "dashboard";
  const isSettings = variant === "settings";

  return (
    <div
      className={`flex items-center ${
        isDashboard || isSettings ? "gap-4" : "gap-3"
      }`}
    >
      <div
        className={`rounded-xl bg-gradient-to-br from-gold-400 to-gold-600 flex items-center justify-center shadow-lg shrink-0 ${
          isDashboard || isSettings ? "h-14 w-14" : "h-10 w-10"
        }`}
      >
        <span
          className={`text-white font-bold ${
            isDashboard || isSettings ? "text-2xl" : "text-lg"
          }`}
        >
          C
        </span>
      </div>
      <div>
        <h1
          className={`font-bold tracking-wide ${
            isDashboard || isSettings ? "text-2xl text-gray-900" : "text-xl text-white"
          }`}
        >
          ChicAdorn
        </h1>
        <p
          className={`tracking-wide ${
            isDashboard || isSettings ? "text-sm text-gray-500" : "text-xs text-brand-300"
          }`}
        >
          Saree Business ERP
        </p>
      </div>
    </div>
  );
}

export default function BrandLogo({
  className = "h-14 w-full object-contain",
  alt = "ChicAdorn",
  variant = "sidebar",
}: BrandLogoProps) {
  const [logoUrl, setLogoUrl] = useState<string | null>(DEFAULT_LOGO_URL);

  const loadLogo = useCallback(async () => {
    try {
      const response = await fetch("/api/settings/logo", { cache: "no-store" });
      if (!response.ok) return;
      const data = (await response.json()) as LogoResponse;
      setLogoUrl(data.logoUrl || DEFAULT_LOGO_URL);
    } catch {
      setLogoUrl(DEFAULT_LOGO_URL);
    }
  }, []);

  useEffect(() => {
    loadLogo();

    const handleLogoUpdated = () => {
      loadLogo();
    };

    window.addEventListener("brand-logo-updated", handleLogoUpdated);
    return () => window.removeEventListener("brand-logo-updated", handleLogoUpdated);
  }, [loadLogo]);

  if (!logoUrl) {
    return <DefaultBrandLogo variant={variant} />;
  }

  return (
    <img
      src={logoUrl}
      alt={alt}
      className={className}
      onError={() => setLogoUrl(DEFAULT_LOGO_URL)}
    />
  );
}
