import React, { useEffect, useState } from "react";
import { URL_API } from "~/constants";
// @ts-ignore
import { VerticalTimeline, VerticalTimelineElement } from "react-vertical-timeline-component";
import "react-vertical-timeline-component/style.min.css";

/** Respuesta GET /api/about-us/sections */
interface AboutUsSectionApi {
    id: number;
    year: string;
    title: string;
    subtitle: string;
    imageUrl: 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 CompanyPage() {
    const [sections, setSections] = useState<AboutUsSectionApi[]>([]);
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState(false);

    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                setLoading(true);
                setLoadError(false);
                const res = await fetch(`${URL_API}about-us/sections`);
                if (!res.ok) throw new Error("bad status");
                const data: AboutUsSectionApi[] = await res.json();
                if (!Array.isArray(data)) throw new Error("invalid json");
                if (cancelled) return;
                const active = data
                    .filter((s) => s.status === 1)
                    .sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.id - b.id);
                setSections(active);
            } catch {
                if (!cancelled) {
                    setLoadError(true);
                    setSections([]);
                }
            } 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">
                            NUESTRA <span className="company-title__highlight">HISTORIA</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 historia…</div>
            ) : loadError ? (
                <div className="text-center py-5 text-muted">
                    No se pudo cargar el contenido. Intenta más tarde.
                </div>
            ) : sections.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">Aún no hay secciones publicadas en «Nosotros».</p>
                </div>
            ) : (
                <VerticalTimeline lineColor="#e9e9e9" animate={true}>
                    {sections.map((item) => (
                        <VerticalTimelineElement
                            key={item.id}
                            className="vertical-timeline-element--work"
                            contentStyle={{
                                background: "#fff",
                                color: "#333",
                                borderRadius: "15px",
                                border: "1px solid #eee",
                                boxShadow: "0 10px 30px rgba(0,0,0,0.05)",
                            }}
                            contentArrowStyle={{ borderRight: "7px solid #eee" }}
                            icon={
                                <span
                                    className="d-flex align-items-center justify-content-center h-100 fw-bold"
                                    style={{ fontSize: "12px" }}
                                >
                                    {item.year}
                                </span>
                            }
                            iconStyle={{
                                background: mainRed,
                                color: "#fff",
                                boxShadow: `0 0 0 4px #fff, inset 0 2px 0 rgba(0,0,0,.08), 0 3px 0 4px rgba(0,0,0,.05)`,
                            }}
                        >
                            <div className="mb-3 overflow-hidden rounded shadow-sm">
                                <img
                                    src={fixLocalApiImageUrl(item.imageUrl) || "/images/no-image.png"}
                                    alt={item.title}
                                    style={{ width: "100%", height: "200px", objectFit: "cover" }}
                                />
                            </div>
                            <h3 className="vertical-timeline-element-title fw-bold" style={{ color: "#222" }}>
                                {item.title}
                            </h3>
                            <p className="text-muted" style={{ fontSize: "0.95rem", lineHeight: "1.6" }}>
                                {item.subtitle}
                            </p>
                        </VerticalTimelineElement>
                    ))}
                </VerticalTimeline>
            )}

            <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: company-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 company-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;
                }

                .vertical-timeline-element-date {
                    color: #666 !important;
                    font-weight: 700 !important;
                    font-size: 1.1rem !important;
                }
                .vertical-timeline::before {
                    background: #eee !important;
                }
                @media (max-width: 1169px) {
                    .vertical-timeline-element-date {
                        display: none !important;
                    }
                }

                @media (max-width: 768px) {
                    .company-title__text {
                        font-size: 1.8rem;
                    }
                }

                @media (max-width: 576px) {
                    .company-title__text {
                        font-size: 1.5rem;
                    }
                }
            `}</style>
        </div>
    );
}
