import { ServerCog, ShieldHalf } from "lucide-react";
import { useMemo, useState } from "react";
import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from "../../../components/ui/avatar";
import type { ClientSummary, ClientType } from "../../../lib/devApi";
import { t } from "../../../lib/i18n";

type ClientLogoProps = {
  client: Pick<ClientSummary, "name" | "type" | "metadata">;
};

function readLogoUrl(metadata?: Record<string, unknown>): string | undefined {
  const logoUrl = metadata?.logo_url;
  if (typeof logoUrl !== "string") {
    return undefined;
  }

  const trimmedLogoUrl = logoUrl.trim();
  return trimmedLogoUrl.length > 0 ? trimmedLogoUrl : undefined;
}

function TypeFallbackIcon({ type }: { type: ClientType }) {
  if (type === "private") {
    return <ServerCog className="h-4 w-4" aria-hidden="true" />;
  }

  return <ShieldHalf className="h-4 w-4" aria-hidden="true" />;
}

export function ClientLogo({ client }: ClientLogoProps) {
  const [didImageFail, setDidImageFail] = useState(false);
  const logoUrl = useMemo(
    () => readLogoUrl(client.metadata),
    [client.metadata],
  );
  const showImage = Boolean(logoUrl) && !didImageFail;
  const clientName = client.name || t("ui.dev.clients.untitled", "Untitled");

  return (
    <Avatar className="h-9 w-9 rounded-lg border border-border/60 bg-primary/10 text-primary">
      {showImage ? (
        <AvatarImage
          src={logoUrl}
          alt={t("ui.dev.clients.logo_alt", "{{name}} 로고", {
            name: clientName,
          })}
          className="object-contain p-1"
          onError={() => setDidImageFail(true)}
        />
      ) : null}
      <AvatarFallback className="rounded-lg bg-primary/10 text-primary">
        <TypeFallbackIcon type={client.type} />
      </AvatarFallback>
    </Avatar>
  );
}
