"use client";

import type { RelatedProductRelation, RelatedProductSummary } from "@shared/interfaces";
import Link from "next/link";
import { useMemo, useState } from "react";

interface RelatedProductsProps {
    relations?: RelatedProductRelation[];
}

const isProduct = (
    product: RelatedProductRelation["product"],
): product is RelatedProductSummary => Boolean(product && typeof product === "object");

const plainText = (value?: string) =>
    (value || "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();

const RelatedProducts = ({ relations = [] }: RelatedProductsProps) => {
    const groups = useMemo(() => {
        const grouped = new Map<string, { label: string; items: RelatedProductRelation[] }>();

        relations.forEach((relation) => {
            if (!relation.group_key || !relation.product_code) return;
            const current = grouped.get(relation.group_key);

            if (current) {
                current.items.push(relation);
            } else {
                grouped.set(relation.group_key, {
                    label: relation.group_label || "Tamamlayıcı ürünler",
                    items: [relation],
                });
            }
        });

        return [...grouped.entries()].map(([key, group]) => ({ key, ...group }));
    }, [relations]);

    const [selectedGroup, setSelectedGroup] = useState(groups[0]?.key || "");
    const activeGroup = groups.find((group) => group.key === selectedGroup) || groups[0];

    if (!activeGroup) return null;

    return (
        <section className="my-10 border-y border-koyugri/20 bg-acikgri/40 sm:my-14" aria-labelledby="related-products-title">
            <div className="py-7 sm:py-8">
                <div className="mb-6 flex flex-col justify-between gap-2 md:flex-row md:items-end">
                    <div>
                        <span className="text-xs font-semibold uppercase tracking-[0.18em] text-primary">
                            Ürün ekosistemi
                        </span>
                        <h2 id="related-products-title" className="mt-2 text-2xl font-semibold text-black">
                            Tamamlayıcı ürünler
                        </h2>
                    </div>
                    <p className="max-w-xl text-sm leading-6 text-metin">
                        Kurulumunuzu tamamlayan, farklı ürün gruplarında yer alabilen uyumlu bileşenler.
                    </p>
                </div>

                <div
                    className="mb-5 flex gap-1 overflow-x-auto border-b border-koyugri/20"
                    role="tablist"
                    aria-label="Tamamlayıcı ürün grupları"
                >
                    {groups.map((group) => {
                        const active = group.key === activeGroup.key;
                        return (
                            <button
                                key={group.key}
                                type="button"
                                role="tab"
                                aria-selected={active}
                                onClick={() => setSelectedGroup(group.key)}
                                className={`relative shrink-0 px-5 py-4 text-left text-sm font-semibold transition-colors ${
                                    active
                                        ? "bg-primary text-white"
                                        : "bg-white text-black hover:bg-gri"
                                }`}
                            >
                                {group.label}
                                <span className={`ml-2 text-xs ${active ? "text-white/75" : "text-metin"}`}>
                                    ({group.items.length})
                                </span>
                            </button>
                        );
                    })}
                </div>

                <div className="grid gap-3" role="tabpanel">
                    {activeGroup.items.map((relation) => {
                        const product = isProduct(relation.product) ? relation.product : null;
                        const href = product?._id
                            ? `/products/${product._id}`
                            : relation.source_url || "#";
                        const description = plainText(product?.subtitle || product?.description).slice(0, 180);
                        const external = !product?._id && Boolean(relation.source_url);

                        return (
                            <Link
                                key={`${relation.group_key}-${relation.product_code}`}
                                href={href}
                                prefetch={false}
                                target={external ? "_blank" : undefined}
                                rel={external ? "noreferrer" : undefined}
                                className="group grid min-h-28 grid-cols-[72px_minmax(0,1fr)] items-center gap-3 border border-koyugri/15 bg-white p-3 transition duration-200 hover:border-primary hover:shadow-md sm:grid-cols-[104px_minmax(0,1fr)_40px] sm:gap-4 sm:p-4 lg:grid-cols-[140px_minmax(0,1fr)_40px] lg:gap-5"
                            >
                                <div className="flex h-20 items-center justify-center bg-acikgri p-2 sm:h-24 sm:p-3">
                                    {product?.image ? (
                                        <img
                                            src={product.image}
                                            alt={product.name}
                                            loading="lazy"
                                            decoding="async"
                                            className="h-full w-full object-contain transition-transform duration-300 group-hover:scale-105"
                                        />
                                    ) : (
                                        <span className="text-center text-xs font-semibold text-metin">Görsel hazırlanıyor</span>
                                    )}
                                </div>

                                <div className="min-w-0">
                                    <div className="mb-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-metin">
                                        {product?.brand?.name && <span>{product.brand.name}</span>}
                                        {product?.categories?.name && <span>{product.categories.name}</span>}
                                    </div>
                                    <h3 className="text-base font-bold text-black md:text-lg">
                                        {product?.name || relation.product_code}
                                    </h3>
                                    {description && <p className="mt-2 line-clamp-2 text-sm leading-5 text-metin">{description}</p>}
                                </div>

                                <span className="hidden h-10 w-10 items-center justify-center border border-primary text-lg text-primary transition group-hover:bg-primary group-hover:text-white sm:flex" aria-hidden="true">
                                    →
                                </span>
                            </Link>
                        );
                    })}
                </div>
            </div>
        </section>
    );
};

export default RelatedProducts;
