"use client";

import { use, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCart } from "@/context/CartContext";
import { useTelegram } from "@/components/TelegramProvider";
import { formatPrice, productSizeLabel, seasonLabels, type Product } from "@/types/product";

export default function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const { addItem } = useCart();
  const { webApp, haptic } = useTelegram();

  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const [quantity, setQuantity] = useState(1);
  const [added, setAdded] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/products/${id}`)
      .then((r) => r.json())
      .then((data) => setProduct(data.item ?? null))
      .finally(() => setLoading(false));
  }, [id]);

  useEffect(() => {
    if (!webApp || !product) return;
    webApp.MainButton.setText(`В корзину · ${formatPrice(product.price * quantity)}`);
    webApp.MainButton.show();

    const handler = () => {
      haptic("medium");
      addItem(
        {
          productId: product.id,
          name: `${product.brand} ${product.model}`,
          brand: product.brand,
          category: product.category,
          size: productSizeLabel(product),
          price: product.price,
          imageUrl: product.imageUrl,
          stock: product.stock || 50,
        },
        quantity,
      );
      setAdded(true);
      router.push("/cart");
    };

    webApp.MainButton.onClick(handler);
    return () => {
      webApp.MainButton.offClick(handler);
      webApp.MainButton.hide();
    };
  }, [webApp, product, quantity, addItem, haptic, router]);

  if (loading) {
    return <p className="p-6 text-center text-sm text-[var(--tg-hint)]">Загрузка товара...</p>;
  }

  if (!product) {
    return (
      <div className="p-6 text-center">
        <p className="text-sm text-[var(--tg-hint)]">Товар не найден</p>
        <Link href="/" className="mt-3 inline-block text-sm text-[var(--tg-accent)]">
          ← Вернуться в каталог
        </Link>
      </div>
    );
  }

  const isTire = product.category === "tire";

  return (
    <div className="pb-28">
      <div className="flex items-center gap-2 px-4 py-3">
        <button
          onClick={() => router.back()}
          className="flex h-8 w-8 items-center justify-center rounded-full bg-white/5 text-lg"
        >
          ←
        </button>
        <p className="text-sm text-[var(--tg-hint)]">Назад к каталогу</p>
      </div>

      <div className="flex aspect-[4/3] items-center justify-center bg-gradient-to-br from-[#1b2745] to-[#101a30] text-8xl">
        {isTire ? "🛞" : "⚙️"}
      </div>

      <div className="px-4 py-4">
        <p className="text-xs font-semibold uppercase tracking-wide text-[var(--tg-accent)]">
          {product.brand}
        </p>
        <h1 className="mt-1 text-xl font-bold leading-tight">{product.model}</h1>
        <p className="mt-1 text-sm text-[var(--tg-hint)]">{productSizeLabel(product)}</p>

        <div className="mt-4 flex items-end justify-between">
          <div>
            <p className="text-2xl font-extrabold">{formatPrice(product.price)}</p>
            <p className={`text-xs ${product.stock > 0 ? "text-[var(--tg-accent-2)]" : "text-rose-400"}`}>
              {product.stock > 0 ? `В наличии: ${product.stock} шт.` : "Под заказ, уточняйте сроки"}
            </p>
          </div>
          <div className="flex items-center gap-3 rounded-xl border border-white/15 px-2 py-1">
            <button
              onClick={() => setQuantity((q) => Math.max(1, q - 1))}
              className="h-8 w-8 text-lg text-[var(--tg-hint)]"
            >
              −
            </button>
            <span className="w-6 text-center font-semibold">{quantity}</span>
            <button
              onClick={() => setQuantity((q) => Math.min(product.stock || 50, q + 1))}
              className="h-8 w-8 text-lg text-[var(--tg-hint)]"
            >
              +
            </button>
          </div>
        </div>

        <div className="mt-6 overflow-hidden rounded-2xl border border-white/10">
          <h2 className="border-b border-white/10 bg-white/5 px-4 py-2 text-sm font-semibold">
            Характеристики
          </h2>
          <dl className="divide-y divide-white/5 text-sm">
            {isTire ? (
              <>
                <Row label="Типоразмер" value={`${product.width}/${product.height} R${product.diameter}`} />
                <Row label="Сезонность" value={product.season ? seasonLabels[product.season] : "—"} />
                <Row label="Шипы" value={product.spikes ? "Да" : "Нет"} />
                <Row label="RunFlat" value={product.runflat ? "Да" : "Нет"} />
                <Row label="Индекс нагрузки" value={product.loadIndex || "—"} />
                <Row label="Индекс скорости" value={product.speedIndex || "—"} />
              </>
            ) : (
              <>
                <Row label="Диаметр" value={`R${product.diameter}`} />
                <Row label="Ширина диска" value={product.widthInches ? `${product.widthInches}J` : "—"} />
                <Row label="Сверловка (PCD)" value={product.pcd || "—"} />
                <Row label="Вылет (ET)" value={product.et ? String(product.et) : "—"} />
                <Row label="Диаметр ступицы (DIA)" value={product.diskDia ? `${product.diskDia} мм` : "—"} />
                <Row label="Тип" value={product.diskType || "—"} />
                <Row label="Цвет" value={product.color || "—"} />
              </>
            )}
            <Row label="Артикул" value={product.externalId} />
          </dl>
        </div>

        <p className="mt-4 text-xs leading-relaxed text-[var(--tg-hint)]">
          Товар поставляется от оптового партнёра b2b.4tochki.ru. Розничная цена уже включает
          наценку магазина.
        </p>

        <button
          onClick={() => {
            haptic("medium");
            addItem(
              {
                productId: product.id,
                name: `${product.brand} ${product.model}`,
                brand: product.brand,
                category: product.category,
                size: productSizeLabel(product),
                price: product.price,
                imageUrl: product.imageUrl,
                stock: product.stock || 50,
              },
              quantity,
            );
            setAdded(true);
          }}
          className="mt-6 w-full rounded-xl bg-[var(--tg-accent)] py-3.5 text-sm font-bold text-white active:scale-[0.99]"
        >
          {added ? "Добавлено ✓ Добавить ещё" : `Добавить в корзину · ${formatPrice(product.price * quantity)}`}
        </button>
      </div>
    </div>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between px-4 py-2.5">
      <dt className="text-[var(--tg-hint)]">{label}</dt>
      <dd className="font-medium">{value}</dd>
    </div>
  );
}
