"use client";

import { useState, useRef } from "react";
import Image from "next/image";
import Link from "next/link";
import { ClinicsLocationsProps } from "@/types/clinics-and-doctors";
import BlueArrow from "../../../../public/images/blue-arrow.svg";
import DarkBlueArrow from "../../../../public/images/dark-blue-arrow.svg";
import BookAnAppointmentModal from "@/components/CommonComponent/BookAppointmentModal";

export default function ClinicsLocations({ heading, description, locations = [] }: ClinicsLocationsProps) {
    const [activeTab, setActiveTab] = useState(0);
    const [activeCardIdx, setActiveCardIdx] = useState(0);
    const carouselRef = useRef<HTMLDivElement>(null);

    const safeTab = activeTab < (locations?.length || 0) ? activeTab : 0;
    const activeTabData = locations[safeTab];
    const cards = activeTabData?.locationdetails ?? [];
    const activeClinic = cards[activeCardIdx] || cards[0];

    const handleTabChange = (idx: number) => {
        setActiveTab(idx);
        setActiveCardIdx(0);
        if (carouselRef.current) carouselRef.current.scrollLeft = 0;
    };

    // Track active card in mobile view on scroll
    const handleScroll = () => {
        const el = carouselRef.current;
        if (!el) return;
        const cardWidth = (el.children[0] as HTMLElement)?.offsetWidth ?? 0;
        const idx = Math.round(el.scrollLeft / (cardWidth + 16));
        const finalIdx = Math.min(Math.max(0, idx), cards.length - 1);
        if (finalIdx !== activeCardIdx) {
            setActiveCardIdx(finalIdx);
        }
    };

    // Scroll to specific card on mobile dot click
    const scrollToCard = (idx: number) => {
        const el = carouselRef.current;
        if (!el) return;
        const card = el.children[idx] as HTMLElement;
        if (card) {
            el.scrollTo({ left: card.offsetLeft - 20, behavior: "smooth" });
        }
        setActiveCardIdx(idx);
    };

    if (!locations.length) return null;

    return (
        <section className="mb-16 md:mb-24 xl:mb-30 scroll-mt-30" id="viewClinics">
            <div className="container">

                {/* ══════════ DESKTOP VIEW ══════════ */}
                <div className="hidden md:grid grid-cols-12 md:gap-x-10 items-start">

                    {/* Header: Title Left, Tabs Right */}
                    <div className="col-span-12 grid grid-cols-12 gap-8 items-end md:mb-10 xl:mb-14">
                        <div className="col-span-6">
                            <h2 className="text-[32px] xl:text-[40px] text-[#00204F] font-medium leading-[1.15] mb-3">
                                {heading}
                            </h2>
                            <p className="text-[16px] xl:text-[18px] text-[#334D72] font-normal leading-[1.4] max-w-[580px]">
                                {description}
                            </p>
                        </div>
                        <div className="col-span-6 flex justify-end">
                            <div role="tablist" className="flex flex-wrap gap-2">
                                {locations.map((loc, idx) => (
                                    <button
                                        key={idx}
                                        onClick={() => handleTabChange(idx)}
                                        className={`px-6 py-3 rounded-[40px] border text-[14px] md:text-[16px] font-medium transition-all duration-150 cursor-pointer outline-none
                                            ${safeTab === idx
                                                ? "bg-[#0A0C5C] border-[#0A0C5C] text-white"
                                                : "bg-white border-[#CCD2DC] text-[#334D72]"
                                            }`}
                                    >
                                        {loc.tab}
                                    </button>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Left: Big active clinic image */}
                    <div className="col-span-6">
                        <div className="w-full rounded-[16px] overflow-hidden aspect-[4/3] shadow-[0_4px_24px_rgba(0,0,0,0.06)] border border-[#E5E9F0]">
                            <Image
                                src={activeClinic?.image}
                                alt={`${activeClinic?.location || "Selected clinic"} building`}
                                className="w-full h-full object-cover"
                                width={600}
                                height={450}
                                priority
                            />
                        </div>
                    </div>

                    {/* Right: List of location cards */}
                    <div className="col-span-6 flex flex-col gap-4">
                        {cards.map((card, idx) => {
                            const isActive = activeCardIdx === idx;

                            // Prepare address details list dynamically
                            const details = [...card.addressdetails];
                            // if (details.length === 2) {
                            //     details.push({
                            //         icon: "/images/clock.svg",
                            //         details: ""
                            //     });
                            // }

                            return (
                                <article
                                    key={idx}
                                    onClick={() => setActiveCardIdx(idx)}
                                    className={`bg-[#F2F4F6] rounded-[16px] p-6 overflow-hidden grid grid-cols-12 gap-6
                                        ${isActive
                                            ? "bg-[#F2F4F6]"
                                            : "bg-[#F2F4F6]"
                                        }`}
                                >
                                    <div className="col-span-4  relative min-h-[170px]">
                                        <Image
                                            src={card.image}
                                            alt={card.location}
                                            fill
                                            className="object-cover rounded-[16px] "
                                            sizes="20vw"
                                        />
                                    </div>
                                    <div className="col-span-8 flex flex-col justify-between">
                                        <div>
                                            <h3 className="text-[18px] xl:text-[20px] text-[#00204F] font-bold mb-3">{card.location}</h3>

                                            {/* Details Info List */}
                                            <div className="space-y-2 mb-6 md:mb-8">
                                                {details.map((addr, aIdx) => (
                                                    <div key={aIdx} className="flex items-center gap-2">
                                                        {addr.icon && (
                                                            <Image src={addr.icon} alt="" width={16} height={16} className="shrink-0" />
                                                        )}
                                                        <span className="text-[12px] xl:text-[16px] text-[#334D72] leading-[1.4]">
                                                            {addr.details}
                                                        </span>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>

                                        {/* Actions Row */}
                                        <div className="flex items-center gap-4">
                                            <Link
                                                href={card.cta_link ?? "#"}
                                                className="inline-flex items-center justify-center gap-2 px-5 py-2.5 rounded-[8px] bg-[#1718FF] text-white text-[13px] xl:text-[14px] font-bold hover:bg-[#0A0CA8] transition-all w-full"
                                            >
                                                {card.cta}
                                                <Image src={BlueArrow} alt="white-arrow" width={16} height={16} className="brightness-[0] invert" />
                                            </Link>
                                            {card.book_space && (
                                                <BookAnAppointmentModal
                                                    buttonBgClass="bg-transparent border border-[#1718FF]"
                                                    buttonText={card.book_space}
                                                    buttonTextClass="!text-[#1718FF] !text-[16px] !px-4 !py-2 w-full"
                                                    arrowIcon={BlueArrow}
                                                />
                                            )}
                                        </div>
                                    </div>
                                </article>
                            );
                        })}
                    </div>
                </div>

                {/* ══════════ MOBILE VIEW ══════════ */}
                <div className="md:hidden">
                    <h2 className="text-[28px] text-[#00204F] font-medium leading-[1.2] mb-3">{heading}</h2>
                    <p className="text-[16px] text-[#334D72] font-normal leading-[1.4] mb-5">{description}</p>

                    {/* Big Active Location Image */}
                    <div className="w-full rounded-[16px] overflow-hidden mb-8 aspect-[4/3] shadow-[0_4px_16px_rgba(0,0,0,0.06)] border border-[#E5E9F0]">
                        <Image
                            src={activeClinic?.image || "/images/our-location.png"}
                            alt={`${activeClinic?.location || "Selected clinic"} building`}
                            className="w-full h-full object-cover"
                            width={500}
                            height={375}
                            priority
                        />
                    </div>

                    {/* Tab pills row (horizontal scroll matching parent padding) */}
                    <div className="-mx-5 px-5 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden mb-8" role="tablist">
                        <div className="flex gap-2 w-max">
                            {locations.map((loc, idx) => (
                                <button
                                    key={idx}
                                    onClick={() => handleTabChange(idx)}
                                    className={`px-4 py-2 rounded-full border text-[13px] font-medium whitespace-nowrap transition-all duration-150 cursor-pointer outline-none
                                        ${safeTab === idx
                                            ? "bg-[#0A0C5C] border-[#0A0C5C] text-white"
                                            : "bg-white border-[#CCD2DC] text-[#334D72]"
                                        }`}
                                >
                                    {loc.tab}
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Cards Carousel with snap margin left alignment matching Figma */}
                    <div
                        ref={carouselRef}
                        onScroll={handleScroll}
                        className="-mx-5 px-5 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden snap-x snap-mandatory flex gap-4 pb-2"
                    >
                        {cards.map((card, idx) => {
                            // Prepare address details list dynamically
                            const details = [...card.addressdetails];
                            // if (details.length === 2) {
                            //     details.push({
                            //         icon: "/images/clock.svg",
                            //         details: ""
                            //     });
                            // }

                            return (
                                <article
                                    key={idx}
                                    className="snap-start shrink-0 w-[calc(85vw-20px)] max-w-[320px] bg-white border border-[#E5E9F0] rounded-[16px] overflow-hidden shadow-[0_2px_12px_0_rgba(0,0,0,0.07)] flex flex-col scroll-ml-5"
                                >
                                    <div className="relative w-full aspect-[16/9]">
                                        <Image
                                            src={card.image}
                                            alt={card.location}
                                            fill
                                            className="object-cover"
                                            sizes="85vw"
                                        />
                                    </div>
                                    <div className="p-4 flex flex-col flex-grow text-left">
                                        <h3 className="text-[18px] text-[#00204F] font-bold mb-3">{card.location}</h3>

                                        {/* Details Info List */}
                                        <div className="space-y-2 mb-4">
                                            {details.map((addr, aIdx) => (
                                                <div key={aIdx} className="flex items-center gap-2">
                                                    {addr.icon && (
                                                        <Image src={addr.icon} alt="" width={14} height={14} className="shrink-0" />
                                                    )}
                                                    <span className="text-[13px] text-[#334D72] leading-[1.4]">
                                                        {addr.details}
                                                    </span>
                                                </div>
                                            ))}
                                        </div>

                                        {/* Actions Stack */}
                                        <div className="flex flex-col gap-2 mt-auto w-full">
                                            <Link
                                                href={card.cta_link ?? "#"}
                                                className="inline-flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-[8px] bg-[#1718FF] text-white text-[14px] font-bold hover:bg-[#0A0CA8] transition-all"
                                            >
                                                {card.cta}
                                                <Image src={BlueArrow} alt="" width={16} height={16} className="brightness-[100] invert" />
                                            </Link>
                                            {card.book_space && (
                                                <BookAnAppointmentModal
                                                    buttonBgClass="bg-transparent border border-[#1718FF]"
                                                    buttonText={card.book_space}
                                                    buttonTextClass="!text-[#1718FF] !text-[16px] !px-4 !py-2 w-full"
                                                    arrowIcon={BlueArrow}
                                                />
                                            )}
                                        </div>
                                    </div>
                                </article>
                            );
                        })}
                        <div className="shrink-0 w-5" aria-hidden="true" />
                    </div>

                    {/* Dot indicators */}
                    {cards.length > 1 && (
                        <div className="flex justify-center gap-2 mt-4">
                            {cards.map((_, idx) => (
                                <button
                                    key={idx}
                                    onClick={() => scrollToCard(idx)}
                                    className={`rounded-full transition-all duration-200 cursor-pointer outline-none
                                        ${activeCardIdx === idx ? "w-5 h-2 bg-[#0A0C5C]" : "w-2 h-2 bg-[#CCD2DC]"}`}
                                />
                            ))}
                        </div>
                    )}
                </div>

            </div>
        </section>
    );
}