import type { ChangeEvent, DragEvent, RefObject } from "react";

import Box from "@mui/material/Box";

import { AppFormLabel } from "@/components/ui/form";
import type { UploadStatus } from "@/features/pswg/working-group-issues/components/create-issuses/add-working-group-issue-dialog-types";
import {
  AttachmentFileCard,
  formatFileSize,
} from "@/features/pswg/working-group-issues/components/create-issuses/attachment-file-card";
import { UploadDropZone } from "@/features/pswg/working-group-issues/components/create-issuses/upload-drop-zone";
import { UploadIconButton } from "@/features/pswg/working-group-issues/components/create-issuses/upload-icon-button";

type IssueAttachmentFieldProps = {
  attachment: File | null;
  existingAttachmentUrl?: string | null;
  fileInputRef: RefObject<HTMLInputElement | null>;
  onDragOver: (event: DragEvent<HTMLDivElement>) => void;
  onDrop: (event: DragEvent<HTMLDivElement>) => void;
  onFileChange: (event: ChangeEvent<HTMLInputElement>) => void;
  onUploadClick: () => void;
  uploadStatus: UploadStatus;
};

function getAttachmentFileName(fileUrl: string) {
  const filePath = fileUrl.split("?")[0] ?? fileUrl;
  const fileName = filePath.split("/").pop();

  return fileName ? decodeURIComponent(fileName) : "Issue attachment";
}

export function IssueAttachmentField({
  attachment,
  existingAttachmentUrl,
  fileInputRef,
  onDragOver,
  onDrop,
  onFileChange,
  onUploadClick,
  uploadStatus,
}: IssueAttachmentFieldProps) {
  const showAttachmentCard =
    attachment !== null || Boolean(existingAttachmentUrl);
  const fileName = attachment
    ? attachment.name
    : existingAttachmentUrl
      ? getAttachmentFileName(existingAttachmentUrl)
      : "";
  const fileSizeLabel = attachment
    ? formatFileSize(attachment.size)
    : "Existing file";

  return (
    <>
      <AppFormLabel>Issue Attachment</AppFormLabel>

      <input
        ref={fileInputRef}
        type="file"
        hidden
        accept=".pdf,image/*"
        onChange={onFileChange}
      />

      {showAttachmentCard ? (
        <Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2 }}>
          <AttachmentFileCard
            fileName={fileName}
            fileSizeLabel={fileSizeLabel}
            fileUrl={attachment ? null : existingAttachmentUrl}
            uploadStatus={attachment ? uploadStatus : "completed"}
          />
          <UploadIconButton
            onUploadClick={onUploadClick}
            onDrop={onDrop}
            onDragOver={onDragOver}
          />
        </Box>
      ) : (
        <UploadDropZone
          onUploadClick={onUploadClick}
          onDrop={onDrop}
          onDragOver={onDragOver}
        />
      )}
    </>
  );
}
