import { useEffect, useState, useCallback } from "react";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import Particles from "react-particles";
import { loadSlim } from "tsparticles-slim";
import type { Engine } from "tsparticles-engine";
import { URL_API } from "~/constants";

interface IBranch {
    sucursalID: number;
    name: string;
    banner: string;
    url: string;
    region?: string;
    address?: string;
    email?: string;
    website?: string;
    phone?: string;
    phone2?: string;
    instagram?: string;
    latitude?: number;
    longitude?: number;
}

const mainRed = "#e31e24";

export default function BranchesPage() {
    const router = useRouter();
    const [branches, setBranches] = useState<IBranch[]>([]);
    const [expandedBranches, setExpandedBranches] = useState<Set<number>>(new Set());
    const [loading, setLoading] = useState(true);

    const particlesInit = useCallback(async (engine: Engine) => {
        await loadSlim(engine);
    }, []);

    const particlesConfig: any = {
        particles: {
            number: {
                value: 25,
                density: {
                    enable: true,
                    value_area: 800,
                },
            },
            color: {
                value: mainRed,
            },
            shape: {
                type: "circle",
            },
            opacity: {
                value: 0.6,
                random: true,
                anim: {
                    enable: true,
                    speed: 1,
                    opacity_min: 0.1,
                    sync: false,
                },
            },
            size: {
                value: 12,
                random: true,
                anim: {
                    enable: true,
                    speed: 2,
                    size_min: 5,
                    sync: false,
                },
            },
            line_linked: {
                enable: false,
            },
            move: {
                enable: true,
                speed: 1.5,
                direction: "top",
                random: true,
                straight: false,
                out_mode: "out",
                bounce: false,
                attract: {
                    enable: false,
                },
            },
        },
        interactivity: {
            detect_on: "canvas",
            events: {
                onhover: {
                    enable: false,
                },
                onclick: {
                    enable: false,
                },
                resize: true,
            },
        },
        retina_detect: true,
    };

    useEffect(() => {
        const fetchBranches = async () => {
            try {
                setLoading(true);
                const response = await fetch(`${URL_API}/sucursal`);
                const data = await response.json();
                setBranches(data);
            } catch (error) {
                console.error("Error al obtener las sucursales:", error);
                toast.error("Error al obtener las sucursales");
            } finally {
                setLoading(false);
            }
        };
        fetchBranches();
    }, []);

    const toggleBranch = (branchId: number) => {
        const newExpanded = new Set(expandedBranches);
        if (newExpanded.has(branchId)) {
            newExpanded.delete(branchId);
        } else {
            newExpanded.add(branchId);
        }
        setExpandedBranches(newExpanded);
    };

    const handleViewOnMap = (branch: IBranch) => {
        if (branch.latitude && branch.longitude) {
            const mapUrl = `https://www.google.com/maps?q=${branch.latitude},${branch.longitude}`;
            window.open(mapUrl, "_blank");
        } else {
            toast.info("Coordenadas no disponibles para esta sucursal");
        }
    };

    if (loading) {
        return (
            <div className="container py-5">
                <div className="text-center">
                    <div className="spinner-border text-primary" role="status">
                        <span className="sr-only">Cargando...</span>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="branches-page">
            <div className="container py-4">
                {/* Título con partículas */}
                <div className="branches-title text-center mb-5 mt-5">
                    <div className="branches-title__container">
                        <Particles
                            id="branches-particles"
                            init={particlesInit}
                            options={particlesConfig}
                            className="bubbles-canvas"
                        />
                        <h1 className="branches-title__text">
                            CONOCE TODAS NUESTRAS <span className="branches-title__highlight">SUCURSALES</span>
                        </h1>
                    </div>
                    <div className="branches-title__underline"></div>
                </div>

                {/* ACORDEÓN POR SUCURSAL */}
                <div className="branches-accordion">
                    {branches.map((branch) => {
                        const isExpanded = expandedBranches.has(branch.sucursalID);
                        return (
                            <div key={branch.sucursalID} className="branches-accordion__item">
                                <button
                                    className="branches-accordion__header"
                                    onClick={() => toggleBranch(branch.sucursalID)}
                                >
                                                                        <span className="branches-accordion__caret">
                                        <svg
                                            width="10"
                                            height="10"
                                            viewBox="0 0 10 10"
                                            fill="none"
                                            xmlns="http://www.w3.org/2000/svg"
                                            className={isExpanded ? "expanded" : ""}
                                        >
                                            <path
                                                d="M3 4L5 6L7 4"
                                                stroke="#b0b0b0"
                                                strokeWidth="1"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                fill="none"
                                            />
                                        </svg>
                                    </span>
                                    <span className="branches-accordion__region-name">{branch.name}</span>
                                </button>

                                {isExpanded && (
                                    <div className="branches-accordion__content">
                                        <div className="branch-card">
                                            <h3 className="branch-card__name">{branch.name}</h3>
                                            
                                            <p className="branch-card__address">
                                                CARRETERA NACIONAL LA ENCRUCIJADA-SAN MATEO. EDIFICIO L TOCARS. PISO 1. LOCAL S/N., LA ENCRUCIJADA ARAGUA
                                            </p>

                                            <div className="branch-card__contact">
                                                <div className="branch-card__contact-item">
                                                    <strong>Email:</strong>{" "}
                                                    <a href="mailto:ltocars.ventas@grupolongk.com">ltocars.ventas@grupolongk.com</a>
                                                </div>

                                                <div className="branch-card__contact-item">
                                                    <strong>Sitio web:</strong>{" "}
                                                    <a
                                                        href="https://ltocarsoficial.com/"
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                    >
                                                        https://ltocarsoficial.com/
                                                    </a>
                                                    <span className="external-link-icon">↗</span>
                                                </div>

                                                <div className="branch-card__contact-item">
                                                    <strong>Teléfono:</strong> (244) 419.89.91
                                                </div>

                                                <div className="branch-card__contact-item">
                                                    <strong>Teléfono:</strong> (412) 043.07.11
                                                    <a
                                                        href="https://wa.me/584120430711"
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        className="whatsapp-icon"
                                                    >
                                                        <svg
                                                            width="16"
                                                            height="16"
                                                            viewBox="0 0 24 24"
                                                            fill="currentColor"
                                                        >
                                                            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.239-.375a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
                                                        </svg>
                                                    </a>
                                                </div>

                                                <div className="branch-card__contact-item">
                                                    <a
                                                        href="https://instagram.com"
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        className="instagram-icon"
                                                    >
                                                        <svg
                                                            width="20"
                                                            height="20"
                                                            viewBox="0 0 24 24"
                                                            fill="currentColor"
                                                        >
                                                            <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z" />
                                                        </svg>
                                                    </a>
                                                </div>
                                            </div>

                                            <button
                                                className="branch-card__map-btn"
                                                onClick={() => handleViewOnMap(branch)}
                                            >
                                                Ver en el mapa
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            </div>

            <style jsx global>{`
                .branches-page {
                    min-height: 100vh;
                    background-color: #fff;
                }

                .branches-title {
                    margin-bottom: 3rem;
                }

                .branches-title__container {
                    position: relative;
                    display: inline-block;
                    width: 100%;
                }

                .bubbles-canvas {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    z-index: 0;
                }

                .branches-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;
                }

                .branches-title__highlight {
                    color: ${mainRed};
                }

                .branches-title__underline {
                    width: 100px;
                    height: 4px;
                    background: ${mainRed};
                    margin: 0rem auto 0;
                }

                .branches-accordion {
                    margin-top: 2rem;
                }

                .branches-accordion__item {
                    border-bottom: 1px solid #e0e0e0;
                }

                .branches-accordion__header {
                    width: 100%;
                    display: flex;
                    align-items: center;
                    padding: 16px 0;
                    background: none;
                    border: none;
                    cursor: pointer;
                    text-align: left;
                    font-size: 1.1rem;
                    font-weight: bold;
                    color: #333;
                }

                .branches-accordion__header:hover {
                    background-color: #f8f9fa;
                }

                .branches-accordion__caret {
                    margin-right: 12px;
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                }

                .branches-accordion__caret svg {
                    transition: transform 0.3s ease;
                }

                .branches-accordion__caret svg.expanded {
                    transform: rotate(180deg);
                }

                .branches-accordion__region-name {
                    font-weight: bold;
                    font-size: 1.1rem;
                }

                .branches-accordion__content {
                    padding: 20px 0;
                }

                .branch-card {
                    background-color: #f5f5f5;
                    padding: 24px;
                    margin-bottom: 16px;
                    border-radius: 4px;
                }

                .branch-card__name {
                    font-size: 1.5rem;
                    font-weight: bold;
                    color: #333;
                    margin-bottom: 12px;
                }

                .branch-card__address {
                    color: #666;
                    margin-bottom: 16px;
                    line-height: 1.6;
                }

                .branch-card__contact {
                    margin-bottom: 20px;
                }

                .branch-card__contact-item {
                    margin-bottom: 12px;
                    color: #333;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                }

                .branch-card__contact-item strong {
                    font-weight: 600;
                }

                .branch-card__contact-item a {
                    color: #333;
                    text-decoration: none;
                }

                .branch-card__contact-item a:hover {
                    text-decoration: underline;
                }

                .external-link-icon {
                    color: #333;
                    font-size: 0.9rem;
                    margin-left: 4px;
                }

                .whatsapp-icon,
                .instagram-icon {
                    margin-left: 8px;
                    color: #333;
                    display: inline-flex;
                    align-items: center;
                    transition: opacity 0.3s ease;
                }

                .whatsapp-icon:hover,
                .instagram-icon:hover {
                    opacity: 0.7;
                }

                .branch-card__map-btn {
                    border: 1px solid #333;
                    background: #fff;
                    color: #333;
                    padding: 8px 16px;
                    border-radius: 4px;
                    font-weight: 500;
                    cursor: pointer;
                    transition: all 0.3s ease;
                }

                .branch-card__map-btn:hover {
                    background: #f8f9fa;
                }

                /* RESPONSIVE */
                @media (max-width: 768px) {
                    .branches-title__text {
                        font-size: 1.8rem;
                    }

                    .branch-card {
                        padding: 16px;
                    }

                    .branch-card__name {
                        font-size: 1.2rem;
                    }
                }

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