'use client';

import React, { useState } from 'react';
import { parse } from 'date-fns';
import Link from 'next/link';
import Image from 'next/image';
import CountDown from '@/components/Common/CountDown';
import { DealType } from '@/types';
import { formatCurrency } from '@/lib/formatPrice';

type ItemDealProps = {
  item: DealType;
};

const ItemDeal: React.FC<ItemDealProps> = ({ item }) => {
  const [now] = useState(() => Date.now());
  const deadline = parse(item.to_time, 'dd-MM-yyyy, h:mm a', new Date()).getTime();

  if (deadline <= now) {
    return null;
  }

  const remainingQuantity = Number(item.quantity) - Number(item.sale_quantity);
  const percentRemaining = (remainingQuantity / Number(item.quantity)) * 100;

  return (
    <div className="product-item">
      <div className="item-deal">
        <Link href={item.product_info.productUrl} className="product-image position-relative">
          <Image
            src={item.product_info.productImage.large}
            width={250}
            height={250}
            alt={item.product_info.productName}
          />
        </Link>

        <div className="product-info flex-1">
          <Link href={item.product_info.productUrl}>
            <h3 className="product-title line-clamp-3">{item.product_info.productName}</h3>
          </Link>

          <div className="product-martket-main flex items-center">
            {Number(item.product_info.marketPrice) > 0 && (
              <>
                <p className="product-market-price">
                  {formatCurrency(item.product_info.marketPrice)} đ
                </p>
                <div className="product-percent-price">-{item.product_info.price_off || 0}%</div>
              </>
            )}
          </div>

          <div className="product-price-main font-bold">
            {item.product_info.price > '0'
              ? `${formatCurrency(item.product_info.price)} đ`
              : 'Liên hệ'}
          </div>

          <div className="p-quantity-sale">
            <i className="sprite sprite-fire-deal"></i>
            <div className="bg-gradient"></div>
            <p className="js-line-deal-left" style={{ width: `${percentRemaining}%` }}></p>
            <span>
              Còn {remainingQuantity}/{Number(item.quantity)} sản phẩm
            </span>
          </div>

          <div className="js-item-deal-time js-item-time-25404">
            <div className="time-deal-page flex items-center justify-center gap-2">
              <div>Kết thúc sau:</div>
              <CountDown deadline={item.to_time} />
            </div>
          </div>

          <Link href={item.product_info.productUrl} className="buy-now-deal">
            Mua giá sốc
          </Link>
        </div>
      </div>
    </div>
  );
};

export default ItemDeal;
