"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Upload, X } from "lucide-react";
import { uploadCompanyAsset, removeCompanyAsset } from "./actions";

interface Props {
  companyId: string;
  type: "logo" | "stamp";
  label: string;
  hint: string;
  currentUrl: string | null;
}

export function CompanyBrandingUploader({ companyId, type, label, hint, currentUrl }: Props) {
  const router = useRouter();
  const inputRef = useRef<HTMLInputElement>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [pending, setPending] = useState(false);
  const [removing, setRemoving] = useState(false);
  const [error, setError] = useState("");

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setError("");
    setPreview(URL.createObjectURL(file));
  }

  async function handleUpload() {
    const file = inputRef.current?.files?.[0];
    if (!file) { setError("Please select a file first"); return; }

    const fd = new FormData();
    fd.append("companyId", companyId);
    fd.append("type", type);
    fd.append("file", file);

    setPending(true);
    setError("");
    const result = await uploadCompanyAsset(fd);
    setPending(false);

    if ("error" in result) {
      setError(result.error);
    } else {
      setPreview(null);
      if (inputRef.current) inputRef.current.value = "";
      router.refresh();
    }
  }

  async function handleRemove() {
    setRemoving(true);
    setError("");
    const result = await removeCompanyAsset(companyId, type);
    setRemoving(false);
    if ("error" in result) setError(result.error);
    else { setPreview(null); router.refresh(); }
  }

  const displayUrl = preview ?? currentUrl;

  return (
    <div className="rounded-lg border border-neutral-200 p-3 space-y-2">
      <div className="flex items-center justify-between">
        <p className="text-xs font-medium text-neutral-700">{label}</p>
        {currentUrl && !preview && (
          <button
            type="button"
            onClick={handleRemove}
            disabled={removing}
            className="inline-flex items-center gap-1 text-xs font-medium text-danger-700 hover:text-danger-800 disabled:opacity-50"
          >
            <X className="h-3 w-3" />
            {removing ? "Removing…" : "Remove"}
          </button>
        )}
      </div>

      {displayUrl && (
        <div className="rounded border border-neutral-200 bg-white p-2 inline-block">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={displayUrl} alt={label} className="max-h-16 max-w-full object-contain" />
          {preview && <p className="text-[10px] text-neutral-400 mt-1">Preview — not yet saved</p>}
        </div>
      )}

      <div
        className="relative rounded-lg border-2 border-dashed border-neutral-300 bg-neutral-50 px-4 py-3 text-center cursor-pointer hover:border-primary-400 hover:bg-primary-50 transition-colors"
        onClick={() => inputRef.current?.click()}
      >
        <Upload className="mx-auto h-5 w-5 text-neutral-400 mb-1" />
        <p className="text-xs text-neutral-600">Click to select image</p>
        <p className="text-[10px] text-neutral-400 mt-0.5">{hint}</p>
        <input
          ref={inputRef}
          type="file"
          accept="image/png,image/jpeg,image/jpg,image/webp"
          onChange={handleFileChange}
          className="sr-only"
        />
      </div>

      {error && <p className="text-xs text-danger-700 bg-danger-50 rounded px-2 py-1">{error}</p>}

      {preview && (
        <button
          type="button"
          onClick={handleUpload}
          disabled={pending}
          className="rounded-lg bg-primary-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-primary-700 disabled:opacity-60"
        >
          {pending ? "Uploading…" : "Upload"}
        </button>
      )}
    </div>
  );
}
