"use client";
import { useParams } from "next/navigation";
import Link from "next/link";
import { useProductDetail } from "./components/_hooks";

export default function ProductDetailPage() {
  const params = useParams<{ orgSlug: string; productId: string }>();
  const t = useProductDetail(params.orgSlug, params.productId);

  if (t.loading) {
    return <div className="text-center py-9"><div className="spinner-border text-primary" /></div>;
  }
  if (t.notFound || !t.product) {
    return (
      <div className="text-center py-9 text-body-tertiary">
        <span className="fa-solid fa-box-open fs-1 mb-3 d-block" />
        Product not found.
        <div className="mt-3"><Link href={`/${params.orgSlug}`}>Back to store</Link></div>
      </div>
    );
  }

  const p = t.product;

  return (
    <>
      <nav className="small text-body-tertiary mb-3">
        <Link href={`/${params.orgSlug}`} className="text-decoration-none">Store</Link> / {p.category_name ?? "Products"} / {p.name}
      </nav>

      <div className="row g-4">
        <div className="col-12 col-md-5">
          <div className="ratio ratio-1x1 bg-body-tertiary rounded">
            {p.image ? (
              <img src={p.image} alt={p.name} className="object-fit-cover rounded" />
            ) : (
              <div className="d-flex align-items-center justify-content-center">
                <span className="fa-solid fa-image fs-1 text-body-tertiary" />
              </div>
            )}
          </div>
        </div>

        <div className="col-12 col-md-7">
          <h2>{p.name}</h2>
          {p.average_rating != null && (
            <div className="text-warning mb-2">
              <span className="fa-solid fa-star me-1" />{p.average_rating} ({p.reviews.length} review{p.reviews.length !== 1 ? "s" : ""})
            </div>
          )}
          <h3 className="text-primary">{p.base_price}</h3>
          {!p.in_stock && <span className="badge badge-phoenix badge-phoenix-danger mb-2">Out of Stock</span>}
          <p className="text-body-secondary mt-3">{p.description_html || "No description available."}</p>

          <div className="d-flex align-items-center gap-2 mt-4">
            <input
              type="number" min={1} step="any" className="form-control" style={{ width: 90 }}
              value={t.quantity} onChange={(e) => t.setQuantity(e.target.value)}
            />
            <button className="btn btn-primary" disabled={!p.in_stock} onClick={t.handleAddToCart}>
              <span className="fa-solid fa-cart-plus me-2" />Add to Cart
            </button>
          </div>
          {t.addMessage && <div className="text-success small mt-2">{t.addMessage}</div>}
        </div>
      </div>

      <hr className="my-5" />

      <h4>Reviews</h4>
      <div className="row g-4 mt-1">
        <div className="col-12 col-md-6">
          {p.reviews.length === 0 && <p className="text-body-tertiary">No reviews yet — be the first!</p>}
          {p.reviews.map((r: { id: number; customer_name: string; rating: number; title: string; body: string }) => (
            <div key={r.id} className="border-bottom pb-3 mb-3">
              <div className="d-flex justify-content-between">
                <strong>{r.customer_name}</strong>
                <span className="text-warning">{"★".repeat(r.rating)}{"☆".repeat(5 - r.rating)}</span>
              </div>
              {r.title && <div className="fw-semibold small">{r.title}</div>}
              <p className="mb-0 small text-body-secondary">{r.body}</p>
            </div>
          ))}
        </div>

        <div className="col-12 col-md-6">
          {t.isLoggedIn ? (
            <form onSubmit={t.handleSubmitReview} className="card card-body">
              <label className="form-label small">Your rating</label>
              <select className="form-select mb-2" value={t.reviewRating} onChange={(e) => t.setReviewRating(Number(e.target.value))}>
                {[5, 4, 3, 2, 1].map((n) => <option key={n} value={n}>{n} star{n !== 1 ? "s" : ""}</option>)}
              </select>
              <input className="form-control mb-2" placeholder="Title (optional)" value={t.reviewTitle} onChange={(e) => t.setReviewTitle(e.target.value)} />
              <textarea className="form-control mb-2" placeholder="Share your thoughts..." rows={3} value={t.reviewBody} onChange={(e) => t.setReviewBody(e.target.value)} />
              <button className="btn btn-outline-primary btn-sm">Submit Review</button>
              {t.reviewMessage && <div className="small mt-2">{t.reviewMessage}</div>}
            </form>
          ) : (
            <div className="alert alert-subtle-info">
              <Link href={`/${params.orgSlug}/account/login`}>Sign in</Link> to leave a review.
            </div>
          )}
        </div>
      </div>
    </>
  );
}
