"use client";

import { useMemo, useState } from "react";
import { cn } from "@/lib/cn";
import type { StorefrontProductDetail } from "@/types/storefront";

const TAB_LABELS = {
  description: "Opis",
  technical: "Tehnički podatci",
  downloads: "Preuzimanja",
  sizeChart: "Tablica veličina",
} as const;

type TabId = keyof typeof TAB_LABELS;

export function ProductDetailTabs({
  product,
}: {
  product: StorefrontProductDetail;
}) {
  const tabs = useMemo(
    () =>
      [
        { id: "description" as const, label: TAB_LABELS.description, html: product.tabs.descriptionHtml },
        { id: "technical" as const, label: TAB_LABELS.technical, html: product.tabs.technicalDetailsHtml },
        { id: "downloads" as const, label: TAB_LABELS.downloads, html: product.tabs.downloadsHtml },
        { id: "sizeChart" as const, label: TAB_LABELS.sizeChart, html: product.tabs.sizeChartHtml },
      ].filter((tab) => tab.html.trim().length > 0),
    [product.tabs],
  );
  const [activeTab, setActiveTab] = useState<TabId>(tabs[0]?.id ?? "description");

  const activeTabContent = tabs.find((tab) => tab.id === activeTab) ?? tabs[0];

  if (!activeTabContent) {
    return null;
  }

  return (
    <section className="space-y-6">
      <div className="flex items-center overflow-x-auto border-b border-black/10">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => setActiveTab(tab.id)}
            className={cn(
              "inline-flex items-center justify-center border-b-2 px-6 py-3 text-[16px] font-bold leading-[1.4] tracking-[-0.02em] transition-colors",
              activeTab === tab.id
                ? "border-accent text-accent"
                : "border-transparent text-primary/60",
            )}
          >
            {tab.label}
          </button>
        ))}
      </div>

      <div
        className="space-y-6 text-[16px] font-medium leading-[1.5] tracking-[-0.02em] text-primary/70 [&_p]:m-0 [&_p+*]:mt-6 [&_table]:w-full [&_table]:border-collapse [&_td]:border [&_td]:border-black/10 [&_td]:p-3 [&_th]:border [&_th]:border-black/10 [&_th]:p-3 [&_ul]:pl-5"
        dangerouslySetInnerHTML={{ __html: activeTabContent.html }}
      />
    </section>
  );
}
