"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Pagination } from "swiper/modules";
import { AestheticServicesProps } from "@/types/about-aesthetic";

// Import Swiper styles
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";

import LeftArrow from "../../../../public/images/doctors-left-arrow.svg";
import RightArrow from "../../../../public/images/doctors-right-arrow.svg";
import BlueArrowUpRight from "../../../../public/images/blue-arrow-up-right.svg";
import WhiteArrow from "../../../../public/images/white-arrow.svg";
import BlueArrow from "../../../../public/images/blue-arrow.svg";
import BookAnAppointmentModal from "@/components/CommonComponent/BookAppointmentModal";
import { getImageSrc } from "@/utils/image";

export default function AestheticServices({ heading, description, tabs }: AestheticServicesProps) {
    const [activeTabIdx, setActiveTabIdx] = useState(0);

    const safeIdx = activeTabIdx < (tabs?.length || 0) ? activeTabIdx : 0;
    const activeTabObject = tabs?.[safeIdx] || tabs?.[0];
    const activeCards = activeTabObject?.specialist_card || [];

    // Helper to format tab title into readable sentence case (e.g., COSMETIC MEDICINE -> Cosmetic Medicine)
    const formatTabTitle = (title: string = "") => {
        if (!title) return "";
        return title
            .trim()
            .toLowerCase()
            .split(" ")
            .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
            .join(" ");
    };

    // Helper to clean trailing dashes or spacers from service card names
    const formatCardName = (name: string = "") => {
        if (!name) return "";
        return name.trim().replace(/\s*—\s*$/, "");
    };

    // Helper to automatically de-duplicate text strings (like "See cosmetic surgery See cosmetic surgery")
    const cleanCtaText = (text: string) => {
        if (!text) return "";
        const trimmed = text.trim();
        const words = trimmed.split(/\s+/);
        const halfLength = Math.floor(words.length / 2);
        if (words.length % 2 === 0) {
            const firstHalf = words.slice(0, halfLength).join(" ");
            const secondHalf = words.slice(halfLength).join(" ");
            if (firstHalf.toLowerCase() === secondHalf.toLowerCase()) {
                return firstHalf;
            }
        }
        return trimmed;
    };

    return (
        <section className="bg-[#F8FAFC] py-16 md:py-24 xl:py-30 mb-16 md:mb-24 xl:mb-30">
            <div className="container">
                {/* 12-Column CSS Grid Header Section */}
                <div className="grid grid-cols-12 gap-y-6 md:gap-y-8 items-end mb-10 md:mb-16">
                    {/* Header text left (Spans 12 on mobile, 6 on desktop) */}
                    <div className="col-span-12 md:col-span-6">
                        <span className="text-[12px] md:text-[14px] text-[#334D72] font-semibold tracking-[0.5px] uppercase block mb-3">
                            OUR SERVICES
                        </span>
                        <h2 className="text-[32px] md:text-[48px] text-[#00204F] font-medium leading-[1.2] tracking-[-0.5px]">
                            {heading}
                        </h2>
                    </div>

                    {/* Description right (Spans 12 on mobile, 6 on desktop) */}
                    <div className="col-span-12 md:col-span-6 md:pl-6">
                        <p className="text-[16px] md:text-[18px] text-[#334D72] leading-relaxed max-w-[550px]">
                            {description}
                        </p>
                    </div>

                    {/* Filter tabs and navigation row (Spans full 12 columns) */}
                    <div className="col-span-12 flex items-center justify-between gap-4 mt-6">
                        {/* Horizontal scrollable tab buttons */}
                        <div className="flex items-center gap-3 overflow-x-auto pb-2 md:pb-0 scrollbar-none shrink-0 max-w-full">
                            {tabs?.map((t, index) => {
                                const tabName = t?.tab || "";
                                const isActive = index === safeIdx;

                                return (
                                    <button
                                        key={index}
                                        onClick={() => setActiveTabIdx(index)}
                                        className={`px-6 py-2.5 rounded-full text-[14px] font-bold border transition-all duration-300 cursor-pointer shrink-0 ${isActive
                                            ? "bg-[#00204F] border-[#00204F] text-white"
                                            : "bg-white border-[#E5E9ED] text-[#334D72] hover:bg-[#F8FAFC]"
                                            }`}
                                    >
                                        {formatTabTitle(tabName)}
                                    </button>
                                );
                            })}
                        </div>

                        {/* Navigation Arrows (Desktop only) */}
                        <div className="hidden md:flex items-center gap-3 shrink-0">
                            <button
                                className="flagship-prev cursor-pointer transition-all duration-300"
                                aria-label="Previous slide"
                            >
                                <Image src={LeftArrow} width={48} height={48} alt="Previous Arrow" />
                            </button>
                            <button
                                className="flagship-next cursor-pointer transition-all duration-300"
                                aria-label="Next slide"
                            >
                                <Image src={RightArrow} width={48} height={48} alt="Next Arrow" />
                            </button>
                        </div>
                    </div>
                </div>

                {/* Swiper Slider Wrapper */}
                <div className="relative w-full">
                    {/* Key Swiper by safeIdx & tab title to trigger full re-mount when category/language is switched */}
                    <Swiper
                        key={`${safeIdx}-${activeTabObject?.tab}`}
                        modules={[Navigation, Pagination]}
                        navigation={{
                            prevEl: ".flagship-prev",
                            nextEl: ".flagship-next",
                        }}
                        pagination={{
                            clickable: true,
                            el: ".flagship-pagination",
                        }}
                        spaceBetween={24}
                        slidesPerView={4}
                        breakpoints={{
                            320: {
                                slidesPerView: 1.15,
                                spaceBetween: 16,
                            },
                            640: {
                                slidesPerView: 2.2,
                                spaceBetween: 20,
                            },
                            768: {
                                slidesPerView: 3,
                                spaceBetween: 24,
                            },
                            1024: {
                                slidesPerView: 4,
                                spaceBetween: 24,
                            },
                        }}
                        className="myAestheticServicesSwiper w-full !pb-3"
                    >
                        {activeCards.map((card, index) => {
                            const cardImageSrc = getImageSrc(card.image);

                            return (
                                <SwiperSlide key={index} className="h-auto flex flex-col">
                                    <article className="bg-white rounded-[24px] border border-[#E5E9ED] overflow-hidden flex flex-col flex-1 w-full transition-shadow duration-300 hover:shadow-lg">
                                        {/* Image Container with fixed aspect ratio */}
                                        {cardImageSrc && (
                                            card.cta_link ? (
                                                <Link href={card.cta_link} className="block relative aspect-[1.15/1] w-full overflow-hidden bg-[#F8FAFC]">
                                                    <Image
                                                        src={cardImageSrc}
                                                        alt={card.name || "service image"}
                                                        fill
                                                        className="object-cover transition-transform duration-500 hover:scale-105"
                                                        sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 25vw"
                                                    />
                                                </Link>
                                            ) : (
                                                <figure className="relative aspect-[1.15/1] w-full overflow-hidden bg-[#F8FAFC]">
                                                    <Image
                                                        src={cardImageSrc}
                                                        alt={card.name || "service image"}
                                                        fill
                                                        className="object-cover"
                                                        sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 25vw"
                                                    />
                                                </figure>
                                            )
                                        )}

                                    {/* Text content details */}
                                    <div className="p-6 flex flex-col justify-between flex-grow">
                                        <div>
                                            {/* Header with Title and action up-right arrow button */}
                                            <div className="flex justify-between items-start gap-4 mb-4">
                                                <h3 className="text-[18px] md:text-[20px] font-bold text-[#00204F] leading-snug">
                                                    {card.cta_link ? (
                                                        <Link href={card.cta_link} className="hover:text-[#1718F5] transition-colors duration-300">
                                                            {formatCardName(card.name)}
                                                        </Link>
                                                    ) : (
                                                        formatCardName(card.name)
                                                    )}
                                                </h3>
                                                {card.cta_link && (
                                                    <Link href={card.cta_link} className="w-8 h-8 rounded-full bg-[#E8F1FF] flex items-center justify-center shrink-0 hover:bg-[#D4E6FF] transition-colors duration-300">
                                                        <Image
                                                            src={BlueArrowUpRight}
                                                            width={16}
                                                            height={16}
                                                            alt="diagonal arrow icon"
                                                        />
                                                    </Link>
                                                )}
                                            </div>

                                            {/* List details compiled from dynamic HTML string */}
                                            <div
                                                className="text-[16px] text-[#334D72] font-medium"
                                                dangerouslySetInnerHTML={{ __html: card.description }}
                                            />
                                        </div>
                                    </div>
                                </article>
                            </SwiperSlide>
                        );
                    })}
                    </Swiper>

                    {/* Pagination Container (Mobile only) */}
                    <div className="flagship-pagination flex md:hidden justify-center items-center gap-2 mt-6"></div>
                </div>

                {/* Bottom Call to Actions (CTA) Buttons */}
                {activeTabObject && (
                    <div className="flex flex-col sm:flex-row justify-center items-center gap-4 mt-10 md:mt-12 w-full">
                        {activeTabObject.cta_text && activeTabObject.cta_link && (
                            <Link
                                href={activeTabObject.cta_link}
                                className="w-full sm:w-auto text-center justify-center items-center inline-flex bg-[#1718F5] hover:bg-[#0004ff] text-white font-bold text-[16px] px-6 py-3.5 rounded-[8px] gap-2 transition-all shadow-md hover:shadow-lg cursor-pointer"
                            >
                                {cleanCtaText(activeTabObject.cta_text)}
                                <Image
                                    src={WhiteArrow}
                                    width={16}
                                    height={16}
                                    alt="arrow icon"
                                />
                            </Link>
                        )}
                        {/* book appointment modal */}
                        {activeTabObject.cosmetic_text && activeTabObject.cosmetic_link && (
                            <BookAnAppointmentModal
                                arrowIcon={BlueArrow}
                                buttonText={cleanCtaText(activeTabObject.cosmetic_text)}
                                buttonBgClass="!bg-transparent border border-[#1718FF]"
                                buttonTextClass="text-[#1718FF] hover:bg-[#1718FF]/5"
                            />
                        )}
                    </div>
                )}
            </div>
        </section>
    );
}
