'use client';

import { useState } from 'react';
import { BadgeCheck, CreditCard, Minus, PackageCheck, Plus, ShieldCheck, ShoppingCart, TicketPercent, Truck, WalletCards } from 'lucide-react';
import BuyNowButton from './BuyNowButton';

type Variant = { id: string; name: string; price: number | string; stock: number };
type Props = {
  product: {
    id: string;
    name: string;
    price: number | string;
    stock: number;
    deliveryMethod?: string;
    deliveryTime?: string;
    warranty?: string;
    variants?: Variant[];
  };
  locale: string;
};

const money = (value: number) => `${value.toLocaleString('vi-VN')} đ`;

export default function ProductPurchasePanel({ product, locale }: Props) {
  const variants = product.variants?.length
    ? product.variants
    : [{ id: '', name: 'Gói mặc định', price: product.price, stock: product.stock }];
  const [variantId, setVariantId] = useState(variants[0]?.id || '');
  const [quantity, setQuantity] = useState(1);
  const [coupon, setCoupon] = useState('');
  const selectedVariant = variants.find((variant) => variant.id === variantId) || variants[0];
  const max = Math.max(0, selectedVariant?.stock ?? 0);
  const price = Number(selectedVariant?.price ?? 0);
  const automatic = ['AUTO', 'AUTO_ZIP', 'AUTO_TXT'].includes(product.deliveryMethod || '');

  const changeQuantity = (next: number) => setQuantity(Math.max(1, Math.min(max || 1, next)));
  const selectVariant = (id: string) => {
    setVariantId(id);
    setQuantity(1);
  };

  return (
    <aside className="space-y-3 rounded-2xl border border-white/10 bg-[#15171c] p-4 shadow-2xl lg:sticky lg:top-5 lg:self-start">
      <div className="border-b border-white/10 pb-4">
        <p className="text-xs font-bold uppercase tracking-wide text-gray-500">Giá chỉ từ</p>
        <p className="mt-1 text-3xl font-black tracking-tight text-rose-400">{money(price)}</p>
        <p className={`mt-1 text-xs font-bold ${max ? 'text-emerald-400' : 'text-rose-400'}`}>
          {max ? `Còn hàng · ${max} sản phẩm khả dụng` : 'Sản phẩm hiện đã hết hàng'}
        </p>
      </div>

      <section className="space-y-2 border-b border-white/10 pb-4">
        <p className="text-sm font-bold text-white">Chọn gói / SKU</p>
        <div className="space-y-2">
          {variants.map((variant) => {
            const selected = variant.id === variantId;
            const stock = Math.max(0, variant.stock || 0);
            return (
              <button
                key={variant.id || 'default'}
                type="button"
                onClick={() => selectVariant(variant.id)}
                className={`w-full rounded-xl border p-3 text-left transition ${selected ? 'border-rose-400 bg-rose-500/10 shadow-[0_0_0_1px_rgba(251,113,133,.15)]' : 'border-white/10 bg-black/20 hover:border-white/25'} ${!stock ? 'opacity-50' : ''}`}
              >
                <div className="flex items-center gap-2">
                  <span className={`flex h-8 w-8 items-center justify-center rounded-lg ${selected ? 'bg-rose-500/20 text-rose-300' : 'bg-white/5 text-gray-400'}`}><PackageCheck className="h-4 w-4" /></span>
                  <span className="min-w-0 flex-1">
                    <span className="block truncate text-sm font-bold text-white">{variant.name}</span>
                    <span className="mt-0.5 block text-xs text-gray-500">{automatic ? 'Giao tự động bằng ZIP bảo mật' : 'Xử lý theo thời gian giao đã chọn'}</span>
                  </span>
                  <span className="text-right">
                    <span className="block text-sm font-black text-rose-400">{money(Number(variant.price))}</span>
                    <span className={`text-[11px] ${stock ? 'text-emerald-400' : 'text-rose-400'}`}>{stock ? `Còn ${stock}` : 'Hết hàng'}</span>
                  </span>
                </div>
              </button>
            );
          })}
        </div>
      </section>

      <section className="border-b border-white/10 pb-4">
        <div className="mb-2 flex items-center justify-between"><p className="text-sm font-bold text-white">Số lượng</p><span className="text-xs text-gray-500">Tối đa {max}</span></div>
        <div className="flex items-center justify-between rounded-xl border border-white/10 bg-black/30 p-1">
          <button type="button" aria-label="Giảm số lượng" onClick={() => changeQuantity(quantity - 1)} disabled={quantity <= 1 || !max} className="rounded-lg p-2 text-gray-300 hover:bg-white/10 disabled:opacity-30"><Minus className="h-4 w-4" /></button>
          <input aria-label="Số lượng" type="number" min={1} max={max || 1} value={quantity} disabled={!max} onChange={(event) => changeQuantity(Number(event.target.value) || 1)} className="w-16 bg-transparent text-center text-sm font-black text-white outline-none disabled:text-gray-600" />
          <button type="button" aria-label="Tăng số lượng" onClick={() => changeQuantity(quantity + 1)} disabled={quantity >= max || !max} className="rounded-lg p-2 text-gray-300 hover:bg-white/10 disabled:opacity-30"><Plus className="h-4 w-4" /></button>
        </div>
      </section>

      <BuyNowButton productId={product.id} productName={product.name} inStock={max > 0} locale={locale} quantity={quantity} variantId={selectedVariant?.id || undefined} />
      <button type="button" disabled className="flex w-full items-center justify-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] py-3 text-sm font-bold text-gray-500"><ShoppingCart className="h-4 w-4" />Thêm vào giỏ <span className="text-[10px]">(sắp có)</span></button>

      <section className="rounded-xl border border-white/10 bg-black/20 p-3">
        <label className="mb-2 flex items-center gap-2 text-xs font-bold text-gray-300"><TicketPercent className="h-4 w-4 text-amber-300" />Có mã giảm giá?</label>
        <div className="flex gap-2"><input value={coupon} onChange={(event) => setCoupon(event.target.value)} placeholder="Nhập mã" className="min-w-0 flex-1 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm outline-none placeholder:text-gray-600 focus:border-rose-400/60" /><button type="button" disabled={!coupon.trim()} className="rounded-lg bg-white/10 px-3 text-xs font-bold text-gray-300 disabled:opacity-40">Áp dụng</button></div>
      </section>

      <section className="rounded-xl border border-white/10 bg-black/20 p-3 text-sm">
        <div className="mb-3 flex items-center justify-between font-bold text-white"><span>Tổng thanh toán</span><span className="text-lg text-rose-400">{money(price * quantity)}</span></div>
        <div className="space-y-2 border-t border-white/10 pt-3 text-xs"><Row icon={<CreditCard className="h-3.5 w-3.5" />} label="Tạm tính" value={money(price * quantity)} /><Row icon={<WalletCards className="h-3.5 w-3.5" />} label="Phí giao dịch" value="Miễn phí" /><Row icon={<Truck className="h-3.5 w-3.5" />} label="Bàn giao" value={automatic ? 'Tự động' : product.deliveryTime || '1 - 24 giờ'} /><Row icon={<BadgeCheck className="h-3.5 w-3.5" />} label="Bảo hành" value={product.warranty || 'Theo mô tả'} /></div>
      </section>

      <div className="grid grid-cols-2 gap-2 border-t border-white/10 pt-3 text-[11px] text-gray-400"><div className="flex gap-2"><ShieldCheck className="h-4 w-4 shrink-0 text-emerald-400" /><span><b className="block text-gray-200">Giữ tiền an toàn</b>Escrow bảo vệ giao dịch</span></div><div className="flex gap-2"><PackageCheck className="h-4 w-4 shrink-0 text-cyan-400" /><span><b className="block text-gray-200">Đúng SKU đã chọn</b>Kiểm tra trước khi mua</span></div></div>
    </aside>
  );
}

function Row({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return <div className="flex items-center justify-between gap-3 text-gray-500"><span className="flex items-center gap-1.5">{icon}{label}</span><span className="text-right font-semibold text-gray-300">{value}</span></div>;
}
