"use client";

import { ImageUploader, type UploadedImage } from "@/components/common/image-uploader";
import { Label } from "@/components/ui/label";

function stripExtension(filename: string): string {
  const lastDot = filename.lastIndexOf(".");
  return lastDot > 0 ? filename.slice(0, lastDot) : filename;
}

function toImageId(baseName: string): string {
  const slug = baseName
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9._-]+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^-|-$/g, "");
  return slug || `image-${Date.now()}`;
}

function formatFileDate(timestamp: number): string {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function buildAutoFillPatch(
  image: UploadedImage,
  file: File,
): Record<string, string> {
  const baseName = stripExtension(image.filename).trim();
  const imageId = toImageId(baseName);
  return {
    id: imageId,
    image_name: baseName || imageId,
    image_file_name: image.filename,
    image_url: image.url,
    mime_type: image.contentType,
    image_time_stamp: formatFileDate(file.lastModified),
  };
}

type ImageFormUploadProps = {
  formData: Record<string, unknown>;
  updateForm: (key: string, value: string) => void;
  updateFormBatch: (patch: Record<string, unknown>) => void;
};

export function ImageFormUpload({ formData, updateFormBatch }: ImageFormUploadProps) {
  const imageUrl = String(formData.image_url ?? "").trim();

  const handleUploaded = (image: UploadedImage, file: File) => {
    updateFormBatch(buildAutoFillPatch(image, file));
  };

  const handleRemoved = () => {
    updateFormBatch({
      id: "",
      image_name: "",
      image_file_name: "",
      image_url: "",
      mime_type: "",
      image_time_stamp: "",
    });
  };

  return (
    <div className="md:col-span-2">
      <Label className="mb-1.5 block text-sm text-slate-700 dark:text-slate-200">
        上传图片
      </Label>
      <p className="mb-2 text-xs text-muted-foreground">
        上传后自动填充 Image ID、Image Name、File Name、Image URL、MIME Type 与 Image Date
      </p>
      <ImageUploader
        maxFiles={1}
        showPreview
        onUploaded={handleUploaded}
        onRemoved={handleRemoved}
        value={imageUrl ? [imageUrl] : undefined}
      />
    </div>
  );
}
