"use client";

import { Upload } from "lucide-react";
import { useRef, useState } from "react";

export default function AdminAssetField({ label, name, defaultValue, accept = "image/*", required, hint, canUpload = true, uploadModule }: {
  label: string;
  name: string;
  defaultValue?: string | null;
  accept?: string;
  required?: boolean;
  hint?: string;
  canUpload?: boolean;
  uploadModule: "series" | "gallery";
}) {
  const [value, setValue] = useState(defaultValue || "");
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState("");
  const fileRef = useRef<HTMLInputElement>(null);

  async function uploadFile(file: File) {
    setUploading(true);
    setError("");
    const body = new FormData();
    body.append("files", file);
    body.append("module", uploadModule);
    try {
      const response = await fetch("/api/admin/upload", { method: "POST", body });
      const result = await response.json() as { urls?: string[]; error?: string };
      if (!response.ok || !result.urls?.[0]) throw new Error(result.error || "Dosya yüklenemedi.");
      setValue(result.urls[0]);
    } catch (uploadError) {
      setError(uploadError instanceof Error ? uploadError.message : "Dosya yüklenemedi.");
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  }

  return (
    <label className="flex min-w-0 flex-col gap-2 text-[10px] font-semibold uppercase tracking-[0.14em] text-fg-muted">
      {label}
      <div className="flex gap-2">
        <input name={name} value={value} onChange={(event) => setValue(event.target.value)} required={required} placeholder="/media/... veya https://cdn..." className="min-w-0 flex-1 rounded-xl border border-border bg-surface-0/70 px-3.5 py-3 text-sm normal-case tracking-normal text-fg-primary outline-none focus:border-ember/60" />
        {canUpload ? <>
          <input ref={fileRef} type="file" accept={accept} className="hidden" onChange={(event) => { const file = event.target.files?.[0]; if (file) void uploadFile(file); }} />
          <button type="button" disabled={uploading} onClick={() => fileRef.current?.click()} className="inline-flex shrink-0 items-center gap-2 rounded-xl border border-border px-4 text-[10px] uppercase tracking-[0.12em] text-ember disabled:opacity-50">
            <Upload size={14} /> {uploading ? "Yükleniyor" : "Seç"}
          </button>
        </> : null}
      </div>
      {hint ? <small className="normal-case tracking-normal text-fg-muted">{hint}</small> : null}
      {error ? <small className="normal-case tracking-normal text-red-300">{error}</small> : null}
    </label>
  );
}
