import React, { useEffect, useState } from "react";
import { URL_API } from "~/constants";

interface BankPaymentMethodApi {
    id: number;
    name: string;
    image_url: string;
    url: string;
    sort_order: number;
    status: number;
}

function fixLocalApiImageUrl(url: string): string {
    let fixed = url || "";
    if (fixed.startsWith("http://localhost/api/")) {
        fixed = fixed.replace("http://localhost/api/", "http://localhost/api-monticars/api/");
    }
    return fixed;
}

const mainRed = "#e31e24";

export default function PagosPage() {
    const [items, setItems] = useState<BankPaymentMethodApi[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);

    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                setLoading(true);
                setError(false);
                const res = await fetch(`${URL_API}bank-payment-methods`);
                if (!res.ok) throw new Error("bad");
                const data: BankPaymentMethodApi[] = await res.json();
                if (!Array.isArray(data)) throw new Error("invalid");
                if (cancelled) return;
                const visible = data.filter((r) => r.status === 1);
                const sorted = [...visible].sort(
                    (a, b) => (a.sort_order ?? a.id) - (b.sort_order ?? b.id),
                );
                setItems(sorted);
            } catch {
                if (!cancelled) {
                    setError(true);
                    setItems([]);
                }
            } finally {
                if (!cancelled) setLoading(false);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, []);

    return (
        <div className="py-5">
            <div className="company-title text-center mb-5">
                <div className="company-title__container">
                    <div className="company-title__text-wrapper">
                        <h1 className="company-title__text">
                            MÉTODOS DE <span className="company-title__highlight">PAGO</span>
                        </h1>
                        <div className="company-title__bubble company-title__bubble--1" />
                        <div className="company-title__bubble company-title__bubble--2" />
                        <div className="company-title__bubble company-title__bubble--3" />
                    </div>
                </div>
                <div className="company-title__underline" />
            </div>

            {loading ? (
                <div className="text-center py-5 text-muted">Cargando métodos de pago…</div>
            ) : error ? (
                <div className="text-center py-5 text-muted">No se pudo cargar la información.</div>
            ) : items.length === 0 ? (
                <div
                    className="text-center py-5 text-muted shadow-sm bg-white rounded-3 mx-auto"
                    style={{ maxWidth: 480 }}
                >
                    <p className="mb-0">Pronto publicaremos los métodos de pago disponibles.</p>
                </div>
            ) : (
                <div className="container">
                    <div className="row g-4 justify-content-center">
                        {items.map((p) => {
                            const img = fixLocalApiImageUrl(p.image_url);
                            const inner = (
                                <>
                                    <div className="payment-card__img-wrap d-flex align-items-center justify-content-center p-4">
                                        <img
                                            src={img || "/images/no-image.png"}
                                            alt=""
                                            className="payment-card__img"
                                        />
                                    </div>
                                    <div className="payment-card__body text-center px-3 pb-4">
                                        <h2 className="payment-card__title h5 mb-0 font-weight-bold">{p.name}</h2>
                                    </div>
                                </>
                            );
                            return (
                                <div key={p.id} className="col-12 col-md-4 d-flex">
                                    {p.url?.trim() ? (
                                        <a
                                            href={p.url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="payment-card text-decoration-none text-dark w-100 d-flex flex-column"
                                        >
                                            {inner}
                                        </a>
                                    ) : (
                                        <div className="payment-card w-100 d-flex flex-column">{inner}</div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            <style jsx>{`
                .payment-card {
                    background: #fff;
                    border-radius: 15px;
                    border: 1px solid #eee;
                    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
                    transition: box-shadow 0.2s ease, transform 0.2s ease;
                    margin-bottom: 20px;
                }
                a.payment-card:hover {
                    box-shadow: 0 14px 36px rgba(0, 0, 0, 0.1);
                    transform: translateY(-2px);
                }
                .payment-card__img-wrap {
                    min-height: 140px;
                }
                .payment-card__img {
                    max-width: 100%;
                    max-height: 100px;
                    width: auto;
                    height: auto;
                    object-fit: contain;
                }
                .payment-card__title {
                    color: #222;
                }
            `}</style>

            <style jsx global>{`
                .company-title {
                    margin-bottom: 3rem;
                }
                .company-title__container {
                    width: 100%;
                }
                .company-title__text-wrapper {
                    position: relative;
                    display: inline-block;
                }
                .company-title__bubble {
                    position: absolute;
                    width: 6px;
                    height: 6px;
                    border-radius: 50%;
                    background: ${mainRed};
                    pointer-events: none;
                    animation: payment-title-bubble-rise 4s ease-out infinite;
                }
                .company-title__bubble--1 {
                    left: 15%;
                    animation-delay: 0s;
                }
                .company-title__bubble--2 {
                    left: 50%;
                    animation-delay: 1.3s;
                }
                .company-title__bubble--3 {
                    left: 85%;
                    animation-delay: 2.6s;
                }
                @keyframes payment-title-bubble-rise {
                    0% {
                        bottom: 0;
                        opacity: 0.45;
                        transform: scale(1);
                    }
                    70% {
                        opacity: 0.15;
                    }
                    100% {
                        bottom: 100%;
                        opacity: 0;
                        transform: scale(0.8);
                    }
                }
                .company-title__text {
                    font-size: 2.5rem;
                    font-weight: 700;
                    color: #000;
                    text-transform: uppercase;
                    letter-spacing: 2px;
                    margin-bottom: 0.5rem;
                    position: relative;
                    z-index: 1;
                }
                .company-title__highlight {
                    color: ${mainRed};
                }
                .company-title__underline {
                    width: 100px;
                    height: 4px;
                    background: ${mainRed};
                    margin: 0.5rem auto 0;
                }
                @media (max-width: 768px) {
                    .company-title__text {
                        font-size: 1.8rem;
                    }
                }
                @media (max-width: 576px) {
                    .company-title__text {
                        font-size: 1.5rem;
                    }
                }
            `}</style>
        </div>
    );
}
