import { api } from '@/lib/api';
import Image from 'next/image';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { Box, CheckCircle2, CircleUserRound, Clock, Headphones, Package, ShieldCheck, Star, Truck } from 'lucide-react';
import Navbar from '@/components/Navbar';
import CategorySidebar from '@/components/CategorySidebar';
import ProductPurchasePanel from '@/components/product/ProductPurchasePanel';
import ProductDescriptionPanel from '@/components/product/ProductDescriptionPanel';

export default async function ProductDetailPage({ params }: { params: Promise<{ locale: string; slug: string }> }) {
  const { locale, slug } = await params;
  let product: any = null;
  try { product = (await api.get(`/products/${slug}`)).data; } catch { notFound(); }
  if (!product) notFound();
  return <div className="min-h-screen bg-background text-foreground"><Navbar /><div className="container mx-auto flex gap-6 px-4 py-6"><CategorySidebar /><main className="min-w-0 flex-1"><div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]"><div className="min-w-0"><div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(360px,.82fr)]"><ProductImage product={product} /><ProductSummary product={product} /></div><div className="mt-5 grid gap-4 lg:grid-cols-[minmax(0,1fr)_310px]"><ProductDescriptionPanel product={product} /><SellerInfoPanel product={product} locale={locale} /></div></div><ProductPurchasePanel product={product} locale={locale} /></div></main></div></div>;
}

function ProductImage({ product }: { product: any }) { return <div className="relative aspect-square overflow-hidden rounded-lg border border-white/10 bg-gradient-to-br from-violet-950/70 to-cyan-950/60 shadow-2xl">{product.image ? <img src={product.image} alt={product.name} className="h-full w-full object-cover" /> : <div className="flex h-full items-center justify-center"><Package className="h-24 w-24 text-violet-400/40" /></div>}<div className="absolute inset-x-0 bottom-0 grid grid-cols-3 gap-2 bg-gradient-to-t from-black/85 to-transparent px-3 pb-3 pt-12"><ImageBenefit title="BẢO VỆ GIAO DỊCH" subtitle="Escrow giữ tiền an toàn" icon={<ShieldCheck />} /><ImageBenefit title="THỜI GIAN GIAO" subtitle={product.deliveryTime || 'Theo thỏa thuận'} icon={<Clock />} /><ImageBenefit title="BẢO HÀNH" subtitle={product.warranty || 'Theo mô tả'} icon={<Truck />} /></div></div>; }
function ImageBenefit({ title, subtitle, icon }: { title: string; subtitle: string; icon: React.ReactNode }) { return <div className="flex min-w-0 items-center gap-2 rounded-lg bg-[#06273a]/85 px-2 py-2 text-[10px] backdrop-blur"><span className="shrink-0 text-cyan-200 [&>svg]:h-4 [&>svg]:w-4">{icon}</span><span className="min-w-0"><b className="block truncate text-[9px] text-white">{title}</b><span className="block truncate text-cyan-100/80">{subtitle}</span></span></div>; }

function ProductSummary({ product }: { product: any }) {
  const automatic = ['AUTO', 'AUTO_ZIP', 'AUTO_TXT'].includes(product.deliveryMethod || '');
  const tags = (product.tags || []).map((item: any) => item.tag?.name).filter(Boolean).slice(0, 3);
  const soldCount = Number(product.soldCount || 0);
  const rating = product.sellerRating;
  const ratingText = rating?.count ? `${Number(rating.average).toFixed(1)}/5 · ${rating.percentage}%` : 'Chưa có đánh giá';
  return <section className="rounded-lg border border-white/10 bg-[#111214] p-4 shadow-xl"><div className="flex flex-wrap gap-2">{product.category?.name && <span className="rounded-full bg-emerald-100 px-3 py-1 text-[11px] font-black text-emerald-600">{product.category.name}</span>}{tags.map((tag: string) => <span key={tag} className="rounded-full border border-white/15 bg-black/30 px-3 py-1 text-[11px] font-bold text-gray-200">{tag}</span>)}</div><h1 className="mt-4 text-[25px] font-black leading-[1.2] tracking-tight text-white">{product.name}</h1><div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs"><span className="flex items-center gap-1 font-bold text-amber-400"><Star className={`h-4 w-4 ${rating?.count ? 'fill-current' : ''}`} />{ratingText}</span>{rating?.count ? <span className="text-gray-400">{rating.count} đánh giá</span> : null}<span className="text-gray-500">•</span><span className="font-semibold text-gray-300">Đã bán {soldCount}</span></div><p className="mt-4 line-clamp-2 text-sm font-medium leading-6 text-gray-200">{product.description || 'Người bán chưa bổ sung mô tả chi tiết cho sản phẩm này.'}</p><div className="mt-4 space-y-2.5 border-b border-white/10 pb-4 text-sm font-semibold text-gray-200"><Promise icon={<Truck />} text={automatic ? 'Giao tự động sau khi thanh toán' : 'Thực hiện theo thời gian giao đã công bố'} /><Promise icon={<ShieldCheck />} text="Bảo vệ người mua, không yêu cầu đổi mật khẩu" /><Promise icon={<CheckCircle2 />} text="Hoàn thành theo đúng thông tin đăng bán" /><Promise icon={<Headphones />} text="Hỗ trợ qua đơn hàng khi cần thiết" /></div><div className="grid grid-cols-3 divide-x divide-white/10 pt-4"><Metric icon={<Clock />} label="Bàn giao" value={product.deliveryTime || 'Theo thỏa thuận'} /><Metric icon={<Box />} label="Phương thức" value={automatic ? 'Tự động' : 'Thủ công'} /><Metric icon={<CircleUserRound />} label="Bảo hành" value={product.warranty || 'Theo mô tả'} /></div></section>;
}
function Promise({ icon, text }: { icon: React.ReactNode; text: string }) { return <p className="flex items-center gap-2"><span className="text-gray-300 [&>svg]:h-4 [&>svg]:w-4">{icon}</span>{text}</p>; }
function Metric({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) { return <div className="min-w-0 px-2 first:pl-0 last:pr-0"><p className="flex items-center gap-1 text-[11px] font-bold text-gray-300 [&>svg]:h-3.5 [&>svg]:w-3.5">{icon}{label}</p><p className="mt-1 truncate text-sm font-black text-white">{value}</p></div>; }

function SellerInfoPanel({ product, locale }: { product: any; locale: string }) {
  const automatic = ['AUTO', 'AUTO_ZIP', 'AUTO_TXT'].includes(product.deliveryMethod || '');
  const seller = product.seller;
  const presence = getPresence(seller?.lastActiveAt);
  const soldCount = Number(product.soldCount || 0);
  const rating = product.sellerRating;
  const shopSlug = seller?.sellerProfile?.shopSlug;
  const sellerHeader = <><span className="flex h-12 w-12 items-center justify-center overflow-hidden rounded-full bg-cyan-500/15 text-cyan-300">{seller?.sellerProfile?.avatarUrl ? <Image src={seller.sellerProfile.avatarUrl} alt="" width={48} height={48} className="h-full w-full object-cover" /> : <CircleUserRound className="h-7 w-7" />}</span><div className="min-w-0"><p className="truncate font-black text-white">{seller?.sellerProfile?.shopName || seller?.name || 'Người bán'}</p><p className={`mt-1 text-xs font-semibold ${presence.online ? 'text-emerald-400' : 'text-gray-500'}`}>{presence.label}</p></div></>;
  return <aside className="rounded-lg border border-white/10 bg-[#111214] p-5 shadow-xl"><p className="text-sm font-black text-white">Người bán</p>{shopSlug ? <Link href={`/${locale}/sellers/${shopSlug}`} className="mt-4 flex items-center gap-3 rounded-lg p-1 transition hover:bg-white/5" title="Xem hồ sơ người bán">{sellerHeader}</Link> : <div className="mt-4 flex items-center gap-3">{sellerHeader}</div>}<div className="mt-5 space-y-3 border-y border-white/10 py-4 text-sm"><SellerStat label="Đánh giá" value={rating?.count ? `${Number(rating.average).toFixed(1)}/5 (${rating.percentage}%)` : 'Chưa có đánh giá'} /><SellerStat label="Đơn hàng hoàn tất" value={`Đã bán ${soldCount}`} /><SellerStat label="Hoạt động gần nhất" value={presence.detail} /></div><div className="mt-4 grid grid-cols-2 gap-2 text-center text-[11px]"><div className="rounded-lg bg-white/5 p-2"><p className="text-gray-500">Phương thức</p><b className="mt-1 block text-white">{automatic ? 'Tự động' : 'Thủ công'}</b></div><div className="rounded-lg bg-white/5 p-2"><p className="text-gray-500">Bảo hành</p><b className="mt-1 block text-white">{product.warranty || 'Theo mô tả'}</b></div></div>{shopSlug && <Link href={`/${locale}/sellers/${shopSlug}`} className="mt-4 block w-full rounded-lg border border-rose-400/45 bg-rose-500/10 py-2.5 text-center text-sm font-black text-rose-300">Xem hồ sơ người bán</Link>}</aside>;
}
function SellerStat({ label, value }: { label: string; value: string }) { return <p className="flex justify-between gap-2"><span className="text-gray-500">{label}</span><b className="text-right text-gray-200">{value}</b></p>; }
function getPresence(lastActiveAt?: string | Date | null) { if (!lastActiveAt) return { online: false, label: 'Chưa có dữ liệu hoạt động', detail: 'Chưa ghi nhận' }; const minutes = Math.max(0, Math.floor((Date.now() - new Date(lastActiveAt).getTime()) / 60_000)); if (minutes < 5) return { online: true, label: '● Đang trực tuyến', detail: minutes ? `Hoạt động ${minutes} phút trước` : 'Hoạt động vừa xong' }; if (minutes < 60) return { online: false, label: `● Ngoại tuyến ${minutes} phút`, detail: `${minutes} phút trước` }; const hours = Math.floor(minutes / 60); if (hours < 24) return { online: false, label: `● Ngoại tuyến ${hours} giờ`, detail: `${hours} giờ trước` }; const days = Math.floor(hours / 24); return { online: false, label: `● Ngoại tuyến ${days} ngày`, detail: `${days} ngày trước` }; }
