"use client";
import { formatFileSize } from "@/utils/shared";
import useDocumentItemPresenter from "./useDocumentItemPresenter";

interface IProps {
  fileId: string;
  /** When provided, a remove button is shown and invoked with the file id. */
  onRemove?: (fileId: string) => void;
  disabled?: boolean;
  isRemoving?: boolean;
}

const DocumentItem = ({ fileId, onRemove, disabled, isRemoving }: IProps) => {
  const { info, isLoading, isDownloading, download } =
    useDocumentItemPresenter(fileId);

  return (
    <div
      className={`flex items-center gap-3 rounded-xl border border-stroke/70 bg-white/70 p-3 shadow-theme-xs dark:border-dark-3 dark:bg-dark/30 ${
        isRemoving ? "opacity-70" : ""
      }`}
    >
      <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/[0.12] text-primary">
        <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"
          />
        </svg>
      </div>

      <div className="min-w-0 flex-1">
        <p className="truncate text-sm font-semibold text-dark dark:text-white">
          {isRemoving ? "Removing…" : isLoading ? "Loading…" : info?.filename || "Document"}
        </p>
        {info?.size ? (
          <p className="mt-0.5 text-xs text-dark-5">{formatFileSize(info.size)}</p>
        ) : null}
      </div>

      <div className="flex shrink-0 items-center gap-2">
        <button
          type="button"
          onClick={download}
          disabled={disabled || isRemoving || isDownloading}
          className="rounded-lg border border-stroke/80 bg-white px-3 py-1.5 text-xs font-semibold text-dark shadow-theme-xs transition-all hover:-translate-y-0.5 hover:border-primary hover:text-primary disabled:cursor-not-allowed disabled:opacity-60 dark:border-dark-3 dark:bg-dark-2 dark:text-white"
        >
          {isDownloading ? "Downloading…" : "Download"}
        </button>
        {onRemove ? (
          <button
            type="button"
            onClick={() => onRemove(fileId)}
            disabled={disabled || isRemoving}
            className="rounded-lg border border-error/35 bg-error/5 px-3 py-1.5 text-xs font-semibold text-error transition-all hover:-translate-y-0.5 hover:bg-error/10 disabled:cursor-not-allowed disabled:opacity-60"
          >
            {isRemoving ? "Removing…" : "Remove"}
          </button>
        ) : null}
      </div>
    </div>
  );
};

export default DocumentItem;
