"use client";

import { useRef, useState } from "react";

const SIZE = 256;

/** Ảnh đại diện — có ảnh thì hiện ảnh, không thì hiện chữ cái đầu của tên. */
export function Avatar({
  name,
  src,
  size = 40,
}: {
  name: string;
  src?: string | null;
  size?: number;
}) {
  const initial = name.trim().split(/\s+/).pop()?.[0]?.toUpperCase() ?? "?";
  if (src) {
    // eslint-disable-next-line @next/next/no-img-element
    return <img src={src} alt={name} width={size} height={size} className="shrink-0 rounded-full object-cover" style={{ width: size, height: size }} />;
  }
  return (
    <span
      aria-hidden
      className="inline-flex shrink-0 items-center justify-center rounded-full bg-ink-100 font-semibold text-brand-600"
      style={{ width: size, height: size, fontSize: size * 0.4 }}
    >
      {initial}
    </span>
  );
}

/**
 * Chọn ảnh đại diện: cắt vuông giữa ảnh, thu về 256px, nén JPEG rồi đưa vào ô ẩn `avatar`
 * dưới dạng data URL (~15–25 KB). Lưu thẳng trong cơ sở dữ liệu như logo công ty — ảnh nhỏ
 * nên không cần dịch vụ lưu trữ riêng. Ô ẩn `removeAvatar` = "1" khi người dùng bấm gỡ ảnh.
 */
export function AvatarPicker({ name, current }: { name: string; current?: string | null }) {
  const [preview, setPreview] = useState<string | null>(current ?? null);
  const [removed, setRemoved] = useState(false);
  const [value, setValue] = useState("");
  const [error, setError] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  async function onPick(file: File | undefined) {
    setError("");
    if (!file) return;
    if (!file.type.startsWith("image/")) {
      setError("Vui lòng chọn một tệp ảnh.");
      return;
    }
    try {
      const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
      const side = Math.min(bitmap.width, bitmap.height);
      const canvas = document.createElement("canvas");
      canvas.width = SIZE;
      canvas.height = SIZE;
      const ctx = canvas.getContext("2d");
      if (!ctx) throw new Error("canvas");
      ctx.drawImage(bitmap, (bitmap.width - side) / 2, (bitmap.height - side) / 2, side, side, 0, 0, SIZE, SIZE);
      const dataUrl = canvas.toDataURL("image/jpeg", 0.8);
      setValue(dataUrl);
      setPreview(dataUrl);
      setRemoved(false);
    } catch {
      setError("Không đọc được ảnh này, hãy thử ảnh khác.");
    }
  }

  return (
    <div className="flex items-center gap-3">
      <Avatar name={name} src={removed ? null : preview} size={64} />
      <div className="flex flex-col gap-1.5">
        <div className="flex flex-wrap gap-2">
          <button type="button" className="btn-ghost px-3 py-1 text-xs" onClick={() => inputRef.current?.click()}>
            {preview && !removed ? "Đổi ảnh" : "Chọn ảnh"}
          </button>
          {preview && !removed && (
            <button
              type="button"
              className="btn-ghost px-3 py-1 text-xs"
              onClick={() => {
                setRemoved(true);
                setValue("");
              }}
            >
              Gỡ ảnh
            </button>
          )}
        </div>
        {error && <span className="text-xs text-red-600">{error}</span>}
      </div>
      <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => void onPick(e.target.files?.[0])} />
      <input type="hidden" name="avatar" value={value} />
      <input type="hidden" name="removeAvatar" value={removed ? "1" : ""} />
    </div>
  );
}
