'use client';

import Image from 'next/image';
import React, { useRef, useState } from 'react';
import Button from './button';

interface BannerUploaderProps {
  label?: string;
  onChange?: (file: File | null) => void;
  defaultBanner?: string;
}

export default function ImageUploader({
  label = 'Subir imagen',
  onChange,
  defaultBanner,
}: BannerUploaderProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [preview, setPreview] = useState<string | null>(defaultBanner || null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0] || null;
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    } else {
      setPreview(null);
    }
    onChange?.(file);
  };

  const handleRemoveImage = () => {
    setPreview(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
    onChange?.(null);
  };

  return (
    <div className="mb-4">
      {label && <label className="block mb-2 font-semibold">{label}</label>}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileChange}
        className="form-control mb-2"
      />
      {preview && (
        <div className="d-flex flex-column align-items-center">
          <Image
            src={preview}
            alt="Previsualización"
            className="img-fluid rounded"
            width={600}
            height={300}
          />
          <Button
            variant="danger"
            onClick={handleRemoveImage}
            className="mt-3"
          >
            Eliminar imagen
          </Button>
        </div>
      )}
    </div>
  );
}
