'use client';

import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCart } from '@/context/CartContext';
import { useSize } from '@/context/SizeContext';
import { siteConfig } from '@/config/site';
import { normalizeVariationLabel, normalizeVariationValue, cleanProductTitle } from '@/lib/format';

export default function CartDrawer() {
  const router = useRouter();
  const {
    cart,
    isCartOpen,
    closeCart,
    setQuantity,
    removeItem,
    subtotal,
    pickProduct,
    closePickSize,
    pickSize,
  } = useCart();
  const { selectSize, openSizeGuide } = useSize();

  const handlePick = (sz: string) => {
    selectSize(sz);
    const isBuy = pickProduct?.buyNow;
    pickSize(sz);
    if (isBuy) {
      router.push('/checkout');
    }
  };

  const freeDeliveryThreshold = siteConfig.shipping.freeShippingThreshold || 3000;
  const remainingForFree = Math.max(0, freeDeliveryThreshold - subtotal);
  const freeDeliveryPercent = Math.min(100, (subtotal / freeDeliveryThreshold) * 100);

  const pickProductSizes = React.useMemo(() => {
    if (!pickProduct) return [];
    const p = pickProduct.product;
    if (p.categories?.some((c) => c.toLowerCase().includes('eyewear'))) {
      return ['one'];
    }
    if (p.availableSizes && p.availableSizes.length > 0) {
      return p.availableSizes;
    }
    return [];
  }, [pickProduct]);

  return (
    <aside className={`sheet ${isCartOpen ? 'open' : ''}`} aria-hidden={!isCartOpen}>
      <div className="veil" onClick={closeCart} />
      <div className="pane" role="dialog" aria-modal="true">
        <div className="phead">
          <h2>{pickProduct ? (pickProductSizes.length > 0 ? 'Choose your size' : 'Add to bag') : 'Your bag'}</h2>
          <button type="button" aria-label="Close" onClick={closeCart}>
            <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        </div>

        <div className="pbody">
          {pickProduct ? (
            <div>
              <div className="pickbox">
                <img
                  src={pickProduct.product.image || '/images/placeholder.png'}
                  alt={pickProduct.product.name}
                  onError={(e) => {
                    (e.currentTarget as HTMLImageElement).src = '/images/placeholder.png';
                  }}
                />
                <div>
                  <h4>{pickProduct.product.name}</h4>
                  <p className="meta">
                    <b>
                      {pickProduct.product.minPrice !== undefined &&
                      pickProduct.product.maxPrice !== undefined &&
                      pickProduct.product.minPrice < pickProduct.product.maxPrice
                        ? `${siteConfig.currency.symbol}${Math.round(pickProduct.product.minPrice).toLocaleString()} – ${siteConfig.currency.symbol}${Math.round(pickProduct.product.maxPrice).toLocaleString()}`
                        : `${siteConfig.currency.symbol}${pickProduct.product.price.toLocaleString()}`}
                    </b>
                    {((pickProduct.product.maxRegularPrice || pickProduct.product.regularPrice) > (pickProduct.product.minPrice || pickProduct.product.price)) && (
                      <del>
                        {pickProduct.product.minRegularPrice !== undefined &&
                        pickProduct.product.maxRegularPrice !== undefined &&
                        pickProduct.product.minRegularPrice < pickProduct.product.maxRegularPrice
                          ? `${siteConfig.currency.symbol}${Math.round(pickProduct.product.minRegularPrice).toLocaleString()} – ${siteConfig.currency.symbol}${Math.round(pickProduct.product.maxRegularPrice).toLocaleString()}`
                          : `${siteConfig.currency.symbol}${(pickProduct.product.maxRegularPrice || pickProduct.product.regularPrice).toLocaleString()}`}
                      </del>
                    )}
                  </p>
                </div>
              </div>

              {pickProduct.product.fit && (
                <p className="pickfit">
                  Fit note — {pickProduct.product.fit}
                </p>
              )}

              {pickProductSizes.length > 0 ? (
                <>
                  <p style={{ fontSize: '14px', fontWeight: 600, margin: '16px 0 9px' }}>
                    Select your size
                  </p>

                  <div className="szgrid">
                    {pickProductSizes.map((sz) => (
                      <button
                        key={sz}
                        type="button"
                        className="szbtn"
                        onClick={() => handlePick(sz)}
                      >
                        {sz === 'one' ? 'One size' : sz}
                      </button>
                    ))}
                  </div>
                </>
              ) : (
                <div style={{ marginTop: '20px' }}>
                  <button
                    type="button"
                    className="btn"
                    style={{ width: '100%', padding: '14px', borderRadius: '100px', background: '#111', color: '#fff', fontWeight: 600 }}
                    onClick={() => handlePick('')}
                  >
                    Confirm &amp; Add
                  </button>
                </div>
              )}

              <p style={{ color: 'var(--soft)', fontSize: '13px', marginTop: '14px' }}>
                Not sure?{' '}
                <button
                  type="button"
                  onClick={() => {
                    closeCart();
                    openSizeGuide();
                  }}
                  style={{
                    background: 'none',
                    border: 0,
                    borderBottom: '1px solid var(--line)',
                    color: 'inherit',
                    padding: 0,
                    cursor: 'pointer',
                    font: 'inherit',
                  }}
                >
                  Check the size guide
                </button>{' '}
                — it takes a minute.
              </p>
            </div>
          ) : cart.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px 10px', color: 'var(--soft)' }}>
              <p style={{ fontSize: '16px', marginBottom: '16px' }}>Your bag is empty.</p>
              <Link href="/shop" className="btn" onClick={closeCart}>
                Start shopping
              </Link>
            </div>
          ) : (
            <>
              {remainingForFree > 0 ? (
                <div className="cfree">
                  Add {siteConfig.currency.symbol}{remainingForFree.toLocaleString()} more for free delivery
                  <span className="fbar">
                    <i style={{ width: `${freeDeliveryPercent}%` }} />
                  </span>
                </div>
              ) : (
                <div className="cfree">Free delivery unlocked.</div>
              )}

              {cart.map((item) => (
                <div key={item.key} className="line">
                  <img
                    src={item.image || '/images/placeholder.png'}
                    alt={item.name}
                    onError={(e) => {
                      (e.currentTarget as HTMLImageElement).src = '/images/placeholder.png';
                    }}
                  />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <h4>{cleanProductTitle(item.name)}</h4>
                    {item.attributes && Object.keys(item.attributes).length > 0 ? (
                      <div style={{ color: 'var(--soft)', fontSize: '12px', marginTop: '1px', marginBottom: '2px' }}>
                        {Object.entries(item.attributes)
                          .filter(([_, v]) => v && String(v).toLowerCase() !== 'one')
                          .map(([k, v]) => `${normalizeVariationLabel(k)}: ${normalizeVariationValue(v)}`)
                          .join(' · ')}
                      </div>
                    ) : null}
                    <small>
                      {item.size && !item.attributes ? `Size ${item.size === 'one' ? 'One size' : normalizeVariationValue(item.size)} · ` : ''}
                      {siteConfig.currency.symbol}{item.price.toLocaleString()}
                    </small>
                    <div className="qty">
                      <button
                        type="button"
                        onClick={() => setQuantity(item.id, item.quantity - 1)}
                        aria-label="Decrease"
                      >
                        –
                      </button>
                      <span>{item.quantity}</span>
                      <button
                        type="button"
                        onClick={() => setQuantity(item.id, item.quantity + 1)}
                        aria-label="Increase"
                      >
                        +
                      </button>
                    </div>
                  </div>
                  <button
                    type="button"
                    className="rm"
                    onClick={() => removeItem(item.id)}
                  >
                    Remove
                  </button>
                </div>
              ))}
            </>
          )}
        </div>

        <div className="pfoot">
          {pickProduct ? (
            <button
              type="button"
              className="btn ghost"
              style={{ width: '100%' }}
              onClick={closePickSize}
            >
              Back to bag
            </button>
          ) : cart.length > 0 ? (
            <>
              <div className="row">
                <span>Subtotal</span>
                <span>{siteConfig.currency.symbol}{subtotal.toLocaleString()}</span>
              </div>
              <div className="row">
                <span>Delivery</span>
                <span>{siteConfig.shipping.freeShippingThreshold > 0 && subtotal >= siteConfig.shipping.freeShippingThreshold
                  ? 'Free'
                  : `${siteConfig.currency.symbol}${Math.min(siteConfig.shipping.insideDhaka.fee, siteConfig.shipping.dhakaSubArea.fee, siteConfig.shipping.outsideDhaka.fee)} – ${siteConfig.currency.symbol}${Math.max(siteConfig.shipping.insideDhaka.fee, siteConfig.shipping.dhakaSubArea.fee, siteConfig.shipping.outsideDhaka.fee)}`}</span>
              </div>
              <div className="tot">
                <span>Total</span>
                <span>{siteConfig.currency.symbol}{subtotal.toLocaleString()}+</span>
              </div>
              <small>Delivery is added at checkout once you choose your district.</small>
              <div className="two">
                <Link href="/shop" className="btn ghost" onClick={closeCart}>
                  Keep shopping
                </Link>
                <Link href="/checkout" className="btn btn-pri" onClick={closeCart}>
                  Checkout
                </Link>
              </div>
            </>
          ) : null}
        </div>
      </div>
    </aside>
  );
}
