"use client";

import { useState } from "react";
import { ImagePlus } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function ImageUploadField({
  id,
  name,
  label,
  required = false
}: {
  id?: string;
  name: string;
  label: string;
  required?: boolean;
}) {
  const [preview, setPreview] = useState<string | null>(null);
  const inputId = id ?? name;

  return (
    <div className="min-w-0">
      <Label htmlFor={inputId}>{label}</Label>
      <div className="grid min-w-0 gap-3 rounded-md border border-[var(--border)] bg-[var(--surface-muted)] p-3">
        <div className="grid aspect-[16/9] place-items-center overflow-hidden rounded-md border border-dashed bg-white">
          {preview ? (
            // The browser-only data URL is a temporary preview and is never submitted to the database.
            // eslint-disable-next-line @next/next/no-img-element
            <img src={preview} alt={`معاينة ${label}`} className="h-full w-full object-contain" />
          ) : (
            <div className="grid justify-items-center gap-2 text-xs font-semibold text-[var(--ink-faint)]">
              <ImagePlus size={24} aria-hidden />
              معاينة الصورة
            </div>
          )}
        </div>
        <Input
          id={inputId}
          name={name}
          type="file"
          accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
          required={required}
          className="min-w-0 bg-white"
          onChange={(event) => {
            const file = event.currentTarget.files?.[0];
            if (!file) {
              setPreview(null);
              return;
            }
            const reader = new FileReader();
            reader.onload = () => setPreview(typeof reader.result === "string" ? reader.result : null);
            reader.readAsDataURL(file);
          }}
        />
      </div>
    </div>
  );
}
