﻿import React, { useState, ChangeEvent, useRef, useEffect } from "react";

type InputImageSingleProps = {
  initialImage?: string;
  onFileChange?: (file: File | null) => void;
  /** Se llama solo cuando el usuario quita la imagen inicial del servidor (no al revertir un archivo recién elegido). */
  onClearInitial?: () => void;
  label?: string;
  /** ID único opcional para el input (útil cuando hay varios en la misma vista) */
  inputId?: string;
  /** Texto de ayuda debajo del área drag & drop (p. ej. medidas en px) */
  helperText?: string;
};

export const InputImageSingle: React.FC<InputImageSingleProps> = ({
  initialImage,
  onFileChange,
  onClearInitial,
  label = "Imagen del modelo (1 imagen)",
  inputId = "model-image-upload",
  helperText,
}) => {
  const [preview, setPreview] = useState<string | null>(initialImage || null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const inputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (initialImage) {
      setPreview(initialImage);
    } else if (!selectedFile) {
      setPreview(null);
    }
  }, [initialImage]);

  const handleFileChange = (e: ChangeEvent<HTMLInputElement> | FileList) => {
    const files = "target" in e ? e.target.files : e;
    if (!files || files.length === 0) return;

    const file = Array.from(files)[0];
    if (!file.type.startsWith("image/")) {
      alert("Por favor selecciona un archivo de imagen válido");
      return;
    }

    if (preview && preview.startsWith("blob:")) {
      URL.revokeObjectURL(preview);
    }

    const newPreview = URL.createObjectURL(file);
    setPreview(newPreview);
    setSelectedFile(file);
    onFileChange?.(file);

    if (inputRef.current) inputRef.current.value = "";
  };

  const removeImage = () => {
    if (preview && preview.startsWith("blob:")) {
      URL.revokeObjectURL(preview);
    }
    if (selectedFile) {
      // Quitar solo la selección nueva: volver a la imagen inicial si existía
      setSelectedFile(null);
      setPreview(initialImage || null);
      onFileChange?.(null);
    } else {
      // Quitar la imagen que venía del servidor
      setPreview(null);
      setSelectedFile(null);
      onFileChange?.(null);
      onClearInitial?.();
    }
    if (inputRef.current) inputRef.current.value = "";
  };

  const hasImage = !!preview;

  return (
    <div className="form-group">
      <label
        style={{ display: "block", marginBottom: "8px", fontWeight: "bold" }}
      >
        {label}
      </label>

      <label
        htmlFor={inputId}
        onDragOver={(e) => {
          e.preventDefault();
          e.currentTarget.style.borderColor = "#007bff";
        }}
        onDragLeave={(e) => {
          e.preventDefault();
          e.currentTarget.style.borderColor = "#ccc";
        }}
        onDrop={(e) => {
          e.preventDefault();
          e.currentTarget.style.borderColor = "#ccc";
          const files = e.dataTransfer.files;
          if (files.length > 0) handleFileChange(files);
        }}
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          width: "100%",
          height: "180px",
          border: "2px dashed #ccc",
          borderRadius: "10px",
          cursor: "pointer",
          backgroundColor: "#f8f9fa",
          transition: "all 0.3s ease",
        }}
      >
        <div
          style={{
            textAlign: "center",
            color: "#6c757d",
            pointerEvents: "none",
          }}
        >
          <i
            className="fas fa-image"
            style={{ fontSize: "40px", marginBottom: "10px" }}
          />
          <p style={{ margin: 0 }}>
            <strong>Arrastra</strong> o selecciona una imagen
          </p>
        </div>

        <input
          id={inputId}
          type="file"
          accept="image/*"
          style={{ display: "none" }}
          ref={inputRef}
          onChange={handleFileChange}
        />
      </label>

      {helperText ? (
        <p className="small text-muted mb-0 mt-2" style={{ lineHeight: 1.45 }}>
          {helperText}
        </p>
      ) : null}

      {hasImage && (
        <div
          style={{
            display: "flex",
            gap: "10px",
            marginTop: "15px",
            alignItems: "flex-start",
          }}
        >
          <div
            style={{ width: "120px", height: "120px", position: "relative" }}
          >
            <button
              type="button"
              onClick={removeImage}
              style={{
                position: "absolute",
                top: "-5px",
                right: "-5px",
                backgroundColor: "#dc3545",
                color: "white",
                border: "none",
                borderRadius: "50%",
                width: "24px",
                height: "24px",
                fontSize: "14px",
                cursor: "pointer",
                zIndex: 10,
              }}
            >
              &times;
            </button>
            <img
              src={preview!}
              alt="Vista previa"
              style={{
                width: "100%",
                height: "100%",
                objectFit: "cover",
                borderRadius: "8px",
                border: "1px solid #ddd",
              }}
            />
          </div>
        </div>
      )}
    </div>
  );
};
