"use client";

import { useState } from "react";
import Image from "next/image";
import { ArrowLeft } from "lucide-react";
import { formatPrice, type CategoryShowcase } from "@/data/category-showcases";

export function CategoryPreview({ category, initialProductId }: { category: CategoryShowcase; initialProductId?: string }) {
  const [selectedId, setSelectedId] = useState(initialProductId);
  const selected = category.products.find((product) => product.id === selectedId);

  if (selected) {
    return (
      <div className="category-dialog-body">
        <button type="button" className="category-back-link" onClick={() => setSelectedId(undefined)}><ArrowLeft size={15} /> All {category.title}</button>
        <div className="category-product-preview">
          <div className="category-preview-photo"><Image src={selected.image} alt={selected.name} fill sizes="(max-width: 600px) 85vw, 350px" className="category-product-image" /></div>
          <div className="category-preview-details"><p className="eyebrow">{category.title}</p><h3>{selected.name}</h3><p className="preview-product-price">{formatPrice(selected.price)}</p><p>{category.description}</p>
            <div className="category-preview-thumbnails" aria-label={`Browse ${category.title}`}>
              {category.products.map((product) => <button type="button" key={product.id} onClick={() => setSelectedId(product.id)} aria-label={`Preview ${product.name}`} aria-pressed={product.id === selected.id}><Image src={product.image} alt="" width={48} height={49} /></button>)}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="category-dialog-body">
      <p className="category-dialog-description">{category.description}</p>
      <div className="category-dialog-grid">
        {category.products.map((product) => <button type="button" key={product.id} className="category-dialog-card" onClick={() => setSelectedId(product.id)}><span className="category-dialog-card-photo"><Image src={product.image} alt={product.name} fill sizes="(max-width: 600px) 40vw, 160px" className="category-product-image" /></span><strong>{product.name}</strong><span>{formatPrice(product.price)}</span></button>)}
      </div>
    </div>
  );
}
