"use client";

import { useRef, useState, useEffect } from "react";
import { LaserPricingTableProps } from "@/types/laser-vision";

/* ── helpers ─────────────────────────────────────────────── */

/** Render "Yes" / "None" with icon badges, or plain text for everything else */
function CellContent({ value }: { value: string }) {
    const lower = value.trim().toLowerCase();

    if (lower === "yes") {
        return (
            <div className="flex items-center justify-center gap-2">
                <span className="w-5 h-5 rounded-full bg-[#10B981] flex items-center justify-center shrink-0">
                    <svg className="w-3.5 h-3.5 stroke-white fill-none stroke-[3]" viewBox="0 0 24 24">
                        <polyline points="20 6 9 17 4 12" />
                    </svg>
                </span>
                <span>Yes</span>
            </div>
        );
    }

    if (lower === "none") {
        return (
            <div className="flex items-center justify-center gap-2">
                <span className="w-5 h-5 rounded-full bg-[#94A3B8] flex items-center justify-center shrink-0">
                    <svg className="w-3.5 h-3.5 stroke-white fill-none stroke-[2.5]" viewBox="0 0 24 24">
                        <line x1="5" y1="12" x2="19" y2="12" />
                    </svg>
                </span>
                <span>None</span>
            </div>
        );
    }

    /* Default: plain text */
    return <span>{value}</span>;
}

/* ── component ───────────────────────────────────────────── */

export default function LaserPricingTable({
    heading,
    description,
    range_cost,
    className,
}: LaserPricingTableProps) {
    const tableContainerRef = useRef<HTMLDivElement>(null);
    const [scrollProgress, setScrollProgress] = useState(0);
    const [canScroll, setCanScroll] = useState(false);

    const handleScroll = () => {
        if (!tableContainerRef.current) return;
        const { scrollLeft, scrollWidth, clientWidth } = tableContainerRef.current;
        const maxScroll = scrollWidth - clientWidth;
        setCanScroll(maxScroll > 0);
        if (maxScroll <= 0) {
            setScrollProgress(0);
        } else {
            setScrollProgress((scrollLeft / maxScroll) * 100);
        }
    };

    useEffect(() => {
        const container = tableContainerRef.current;
        if (container) {
            container.addEventListener("scroll", handleScroll);
            handleScroll();
        }
        return () => {
            if (container) {
                container.removeEventListener("scroll", handleScroll);
            }
        };
    }, []);

    /* First entry holds column headers (price is empty) */
    const headerRow = range_cost?.[0];
    const dataRows = range_cost?.slice(1) ?? [];

    return (
        <section className={`${className ?? ""}`}>
            <div className="container">
                {/* ── Header ──────────────────────────────── */}
                <div className="text-center max-w-[800px] mx-auto mb-10 md:mb-16">
                    <h2 className="text-[32px] md:text-[48px] text-[#00204F] font-medium leading-[1.1] mb-4 max-w-[520px] mx-auto">
                        {heading}
                    </h2>
                    <p className="text-[16px] md:text-[20px] text-[#334D72] font-normal leading-[1.3] max-w-[680px] mx-auto">
                        {description}
                    </p>
                </div>

                {/* ── Table ───────────────────────────────── */}
                <div className="relative">
                    <div
                        ref={tableContainerRef}
                        className="overflow-x-auto scrollbar-none"
                    >
                        {/*
                          min-w-[600px] ensures the table triggers horizontal scroll on
                          narrow viewports instead of squashing columns.
                        */}
                        <table className="min-w-[600px] w-full max-w-[1064px] mx-auto border-collapse text-left text-[14px] md:text-[16px]">
                            {/* Column header row */}
                            <thead>
                                <tr>
                                    {/* Empty corner */}
                                    <th className="min-w-[160px] w-[30%] bg-white p-4 sticky left-0 z-10"></th>
                                    {/* TransPRK header */}
                                    <th className="min-w-[180px] w-[35%] p-0">
                                        <div className="bg-[#1718FF] text-white text-center p-4 font-bold text-[16px] md:text-[20px] rounded-tl-[16px] border-r border-white/20">
                                            {headerRow?.cost_duration || "TransPRK"}
                                        </div>
                                    </th>
                                    {/* FemtoLASIK header */}
                                    <th className="min-w-[180px] w-[35%] p-0">
                                        <div className="bg-[#0B1380] text-white text-center p-4 font-bold text-[16px] md:text-[20px] rounded-tr-[16px]">
                                            FemtoLASIK
                                        </div>
                                    </th>
                                </tr>
                            </thead>

                            {/* Data rows */}
                            <tbody>
                                {dataRows.map((row, idx) => {
                                    const isEven = idx % 2 === 1;
                                    const stripeBg = isEven ? "bg-[#F5F9FF]" : "";

                                    return (
                                        <tr
                                            key={idx}
                                            className="border-b border-[#E2E8F0]"
                                        >
                                            {/* Row label — sticky on mobile */}
                                            <td
                                                className={`min-w-[160px] p-4 font-semibold text-[#334D72] bg-white sticky left-0 z-10
                                                    shadow-[5px_0_10px_-5px_rgba(0,0,0,0.05)] md:shadow-none`}
                                            >
                                                {row.price}
                                            </td>

                                            {/* TransPRK value */}
                                            <td
                                                className={`min-w-[180px] p-4 text-center text-[#00204F] font-medium ${stripeBg}`}
                                            >
                                                <CellContent value={row.cost_duration} />
                                            </td>

                                            {/* FemtoLASIK value */}
                                            <td
                                                className={`min-w-[180px] p-4 text-center text-[#00204F] font-medium ${stripeBg}`}
                                            >
                                                <CellContent value={row.femto_cost} />
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>

                    {/* Mobile Scroll Indicator — only visible when scrollable */}
                    {canScroll && (
                        <div className="md:hidden w-full h-[3px] bg-[#E2E8F0] rounded-full overflow-hidden mt-2">
                            <div
                                className="h-full bg-[#1718FF] transition-all duration-150"
                                style={{ width: `${Math.max(scrollProgress, 10)}%` }}
                            ></div>
                        </div>
                    )}
                </div>
            </div>
        </section>
    );
}