"use client";

import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/Button";
import { ApiError, deleteUserAvatar, uploadUserAvatar } from "@/lib/api";
import { mediaUrl } from "@/lib/media";

export function UserAvatarUpload({
  name,
  avatarPath,
  userId,
  onAvatarChange,
  onPendingFile,
  disabled = false,
}: {
  name: string;
  avatarPath?: string | null;
  userId?: number;
  onAvatarChange?: (path: string | null) => void;
  onPendingFile?: (file: File | null) => void;
  disabled?: boolean;
}) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [localPreview, setLocalPreview] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const initials = name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0])
    .join("");

  const displaySrc = localPreview ?? mediaUrl(avatarPath);

  useEffect(() => {
    return () => {
      if (localPreview) URL.revokeObjectURL(localPreview);
    };
  }, [localPreview]);

  const handleFile = async (file: File | null) => {
    if (!file) return;
    setError(null);

    if (localPreview) URL.revokeObjectURL(localPreview);
    setLocalPreview(URL.createObjectURL(file));

    if (!userId) {
      onPendingFile?.(file);
      return;
    }

    setBusy(true);
    try {
      const updated = await uploadUserAvatar(userId, file);
      onAvatarChange?.(updated.avatar_path ?? null);
      if (localPreview) URL.revokeObjectURL(localPreview);
      setLocalPreview(null);
      onPendingFile?.(null);
    } catch (err) {
      if (localPreview) URL.revokeObjectURL(localPreview);
      setLocalPreview(null);
      setError(err instanceof ApiError ? err.message : "خطا در آپلود نمایه");
    } finally {
      setBusy(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  };

  const handleDelete = async () => {
    setError(null);

    if (!userId) {
      if (localPreview) URL.revokeObjectURL(localPreview);
      setLocalPreview(null);
      onPendingFile?.(null);
      onAvatarChange?.(null);
      if (inputRef.current) inputRef.current.value = "";
      return;
    }

    setBusy(true);
    try {
      const updated = await deleteUserAvatar(userId);
      onAvatarChange?.(updated.avatar_path ?? null);
      if (localPreview) URL.revokeObjectURL(localPreview);
      setLocalPreview(null);
      onPendingFile?.(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در حذف نمایه");
    } finally {
      setBusy(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  };

  return (
    <div className="rounded-xl border border-[var(--border)] p-4" style={{ backgroundColor: "rgb(248, 250, 252)" }}>
      <p className="mb-3 text-sm font-semibold text-slate-800">نمایه کاربری</p>
      <div className="flex flex-wrap items-center gap-4">
        {displaySrc ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={displaySrc} alt={name} className="h-24 w-24 rounded-full border border-slate-100 object-cover shadow-sm" />
        ) : (
          <div
            className="user-avatar-fallback flex h-24 w-24 items-center justify-center rounded-full text-2xl font-bold"
          >
            {initials || "؟"}
          </div>
        )}

        <div>
          <div className="flex flex-wrap gap-2">
            <input
              ref={inputRef}
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="hidden"
              disabled={disabled || busy}
              onChange={(e) => void handleFile(e.target.files?.[0] ?? null)}
            />
            <Button
              type="button"
              variant="secondary"
              loading={busy}
              disabled={disabled}
              onClick={() => inputRef.current?.click()}
            >
              {displaySrc ? "تغییر تصویر" : "آپلود تصویر"}
            </Button>
            {displaySrc ? (
              <Button type="button" variant="danger" loading={busy} disabled={disabled} onClick={() => void handleDelete()}>
                حذف
              </Button>
            ) : null}
          </div>
          <p className="mt-2 text-xs text-[var(--muted)]">فرمت‌های مجاز: JPEG، PNG، WebP — حداکثر ۲ مگابایت</p>
          {error ? <p className="mt-2 text-xs text-red-600">{error}</p> : null}
        </div>
      </div>
    </div>
  );
}
