"use client";

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

import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { alpha } from "@mui/material/styles";

import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import CloudUploadOutlinedIcon from "@mui/icons-material/CloudUploadOutlined";

import { DocumentFileName } from "@/components/ui/document-file-name";
import { DocumentLink } from "@/components/ui/document-link";
import { PdfIcon } from "@/components/ui/icon";
import { UploadDropZone } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/upload-drop-zone";
import type { UploadStatus } from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog-types";
import { getDisplayFileName } from "@/lib/document-file";

function formatFileSize(size: number) {
  if (size < 1024 * 1024) {
    return `${Math.round(size / 1024)} KB`;
  }

  return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}

type IssueReferenceFileCardProps = {
  name: string;
  sizeLabel: string;
  uploadStatus: UploadStatus;
};

export function IssueReferenceFileCard({
  name,
  sizeLabel,
  uploadStatus,
}: IssueReferenceFileCardProps) {
  const isCompleted = uploadStatus === "completed";

  return (
    <Box
      sx={{
        width: 287,
        height: 62,
        borderRadius: "6px",
        bgcolor: "#fafafa",
        display: "flex",
        alignItems: "center",
        px: "13px",
        gap: "12px",
        flexShrink: 0,
      }}
    >
      <PdfIcon sx={{ fontSize: 40, width: 40, height: 40 }} />

      <Box
        sx={{
          minWidth: 0,
          width: 115,
          flexShrink: 0,
          display: "flex",
          flexDirection: "column",
          gap: "12px",
        }}
      >
        <DocumentFileName
          name={name}
          fontSize={12}
          fontWeight={500}
          color="#252b37"
          sx={{ width: "100%" }}
        />
        <Typography
          sx={{
            fontSize: 12,
            fontWeight: 400,
            lineHeight: 1.24,
            color: "#414651",
          }}
        >
          {sizeLabel}
        </Typography>
      </Box>

      <Box
        sx={{
          ml: "auto",
          width: 80,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: "8px",
          flexShrink: 0,
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
          {isCompleted ? (
            <CheckCircleIcon sx={{ fontSize: 11, color: "#22c55e" }} />
          ) : null}
          <Typography
            sx={{
              fontSize: 11,
              fontWeight: 500,
              lineHeight: "16px",
              color: "#868686",
              whiteSpace: "nowrap",
            }}
          >
            {isCompleted ? "Completed" : "Uploading"}
          </Typography>
        </Box>

        <Box
          sx={{
            width: 80,
            height: 4,
            borderRadius: "16px",
            bgcolor: "#ffffff",
            overflow: "hidden",
          }}
        >
          <Box
            sx={{
              width: isCompleted ? "100%" : "45%",
              height: "100%",
              borderRadius: "16px",
              bgcolor: "#22c55e",
              transition: "width 0.3s ease",
            }}
          />
        </Box>
      </Box>
    </Box>
  );
}

const PDF_ACCEPT = ".pdf,application/pdf";

type IssueReferenceUploadButtonProps = {
  inputId: string;
  onDragOver: (event: DragEvent<HTMLDivElement>) => void;
  onDrop: (event: DragEvent<HTMLDivElement>) => void;
};

function IssueReferenceUploadButton({
  inputId,
  onDragOver,
  onDrop,
}: IssueReferenceUploadButtonProps) {
  return (
    <Box
      {...(inputId
        ? { component: "label" as const, htmlFor: inputId }
        : {})}
      onDrop={onDrop}
      onDragOver={onDragOver}
      sx={{
        width: 77,
        height: 62,
        borderRadius: "12px",
        bgcolor: "#fafafa",
        border: "1px dashed #e9eaeb",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        cursor: "pointer",
        flexShrink: 0,
        transition: "0.2s",
        "&:hover": {
          bgcolor: alpha("#2584ce", 0.06),
          borderColor: "#2584ce",
        },
      }}
    >
      <CloudUploadOutlinedIcon sx={{ fontSize: 38, color: "#2584ce" }} />
    </Box>
  );
}

type ExistingIssueReference = {
  name: string;
  size?: string;
  path?: string;
};

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

export function IssuesReferenceUploadField({
  attachment,
  existingReference = null,
  fileInputRef,
  uploadStatus,
  onDragOver,
  onDrop,
  onFileChange,
  onUploadClick,
}: IssuesReferenceUploadFieldProps) {
  const inputId = useId();
  const savedReference =
    !attachment && existingReference?.name?.trim() ? existingReference : null;

  return (
    <>
      <input
        id={inputId}
        ref={fileInputRef}
        type="file"
        accept={PDF_ACCEPT}
        onChange={onFileChange}
        style={{ display: "none" }}
      />

      {attachment ? (
        <Box sx={{ display: "flex", alignItems: "center", gap: "22px" }}>
          <IssueReferenceFileCard
            name={getDisplayFileName(
              attachment.name,
              "Issues Reference Document",
            )}
            sizeLabel={formatFileSize(attachment.size)}
            uploadStatus={uploadStatus}
          />
          <IssueReferenceUploadButton
            inputId={inputId}
            onDrop={onDrop}
            onDragOver={onDragOver}
          />
        </Box>
      ) : savedReference ? (
        <Box sx={{ display: "flex", alignItems: "center", gap: "22px" }}>
          <DocumentLink
            file={
              savedReference.path
                ? { path: savedReference.path }
                : null
            }
          >
            <IssueReferenceFileCard
              name={savedReference.name}
              sizeLabel={savedReference.size?.trim() || "—"}
              uploadStatus="completed"
            />
          </DocumentLink>
          <IssueReferenceUploadButton
            inputId={inputId}
            onDrop={onDrop}
            onDragOver={onDragOver}
          />
        </Box>
      ) : (
        <UploadDropZone
          inputId={inputId}
          onDrop={onDrop}
          onDragOver={onDragOver}
          onUploadClick={onUploadClick}
        />
      )}
    </>
  );
}
