"use client";

import React, { useState } from "react";
import { Button, Image } from "react-bootstrap";
import { FaUpload } from "react-icons/fa";
import axiosInstance from "@/utils/api-config";

//Para poder subir las imagenes
interface UploadedImage {
    originalName: string;
    filename: string;
    path: string;
}

export default function BannerUpload() {
    const [files, setFiles] = useState<File[]>([]);
    const [loading, setLoading] = useState(false);
    const [uploaded, setUploaded] = useState<UploadedImage[]>([]);
    const [progress, setProgress] = useState(0);

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files) {
        setFiles(Array.from(e.target.files));
        }
    };

    const handleUpload = async () => {
        if (files.length === 0) {
        alert("Selecciona al menos un archivo");
        return;
        }

        const formData = new FormData();
        files.forEach((file) => {
        formData.append("banners", file);
        });

        try {
            setLoading(true);
            setProgress(0);

            const res = await axiosInstance.post("/cuestionario/banners/bulk", formData, {
                headers: { "Content-Type": "multipart/form-data" },
                onUploadProgress: (progressEvent) => {
                if (progressEvent.total) {
                    setProgress(
                    Math.round((progressEvent.loaded * 100) / progressEvent.total)
                    );
                }
                },
            });

            //Falta hacer validacion

            setUploaded(res.data);
            alert("Banners subidos correctamente ✅");
            setFiles([]);
        } catch (error) {
            console.error(error);
            alert(error || "Error al subir archivos");
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="container-fluid my-4">
        <div className="row mb-4">
            <div className="col-12">
            <div className="p-4 border rounded bg-light">
                <h2 className="mb-2">Subir Banners</h2>
                <p className="mb-0 text-muted">
                Arrastra o selecciona imágenes para subir tus banners (jpg, png, webp).
                </p>
            </div>
            </div>
        </div>

        {/* Área Drag & Drop */}
        <div
            className="border p-4 text-center rounded"
            style={{ cursor: "pointer" }}
            onClick={() => document.getElementById("bannerInput")?.click()}
        >
            <FaUpload size={40} className="mb-2 text-muted" />
            <p className="mb-1">
            Arrastra aquí tus imágenes o haz clic para buscar
            </p>
            <p className="is-size-6">Tamaño máximo 20MB</p>
        </div>

        <input
            id="bannerInput"
            type="file"
            accept=".jpg,.jpeg,.png,.webp"
            multiple
            style={{ display: "none" }}
            onChange={handleFileChange}
        />

        {/* Previsualización */}
        {files.length > 0 && (
            <div className="d-flex flex-wrap gap-3 mt-4">
            {files.map((file, i) => (
                <div
                key={i}
                className="border rounded overflow-hidden shadow-sm"
                style={{ width: "350px", height: "350px" }}
                >
                <Image
                    src={URL.createObjectURL(file)}
                    alt={file.name}
                    className="img-fluid h-75 w-100 object-fit-cover"
                />
                <p className="small text-center bg-light p-2 m-0">{file.name}</p>
                </div>
            ))}
            </div>
        )}

        {/* Botón */}
        <div className="d-flex gap-2 mt-3">
            <Button
            variant="outline-primary"
            disabled={loading}
            onClick={handleUpload}
            >
            {loading ? "Subiendo..." : "Subir Banners"}
            </Button>
        </div>

        {/* Barra de progreso */}
        {loading && (
            <div className="progress mt-3" style={{ height: "8px" }}>
            <div
                className="progress-bar progress-bar-striped bg-primary"
                role="progressbar"
                style={{ width: `${progress}%` }}
            ></div>
            </div>
        )}

        {/* Archivos subidos */}
        {uploaded.length > 0 && (
            <div className="mt-4">
            <h5 className="mb-2 text-muted">Archivos subidos:</h5>
            <ul className="list-group">
                {uploaded.map((file, i) => (
                <li key={i} className="list-group-item d-flex justify-content-between align-items-center">
                    <span>{file.originalName}</span>
                    <a href={`/${file.path}`} target="_blank" className="text-primary">
                    Ver
                    </a>
                </li>
                ))}
            </ul>
            </div>
        )}
        </div>
    );
}
