'use client';

import { useEffect, useRef, useState } from 'react';
import type { CouponCartItem, CouponQuote } from '@/lib/coupon-server';

export type AppliedCoupon = CouponQuote & { cartKey: string };

function cleanCouponMessage(text: string): string {
  if (!text) return '';
  return text
    .replace(/&quot;/g, '"')
    .replace(/&#039;/g, "'")
    .replace(/&apos;/g, "'")
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&nbsp;/g, ' ')
    .replace(/&#(\d+);/g, (_, dec) => String.fromCharCode(Number(dec)))
    .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
    .trim();
}

interface Props {
  items: CouponCartItem[];
  subtotal: number;
  cartKey: string;
  disabled: boolean;
  applied: AppliedCoupon | null;
  onChange: (coupon: AppliedCoupon | null) => void;
  onBusy: (busy: boolean) => void;
}

export default function CouponField({ items, subtotal, cartKey, disabled, applied, onChange, onBusy }: Props) {
  const [enabled, setEnabled] = useState(false);
  const [code, setCode] = useState('');
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');
  const request = useRef<AbortController | null>(null);
  const generation = useRef(0);

  useEffect(() => {
    const controller = new AbortController();
    fetch('/api/coupon', { cache: 'no-store', signal: controller.signal })
      .then((response) => response.ok ? response.json() : { enabled: false })
      .then((settings) => setEnabled(settings.enabled === true))
      .catch(() => {});
    return () => controller.abort();
  }, []);

  useEffect(() => {
    generation.current++;
    request.current?.abort();
    onChange(null);
    setBusy(false);
    onBusy(false);
    setMessage('');
    return () => { generation.current++; request.current?.abort(); };
  }, [cartKey, onChange, onBusy]);

  const apply = async () => {
    if (busy || disabled || !code.trim()) return;
    const token = ++generation.current;
    request.current?.abort();
    const controller = new AbortController();
    request.current = controller;
    setBusy(true);
    onBusy(true);
    onChange(null);
    setMessage('');
    try {
      const response = await fetch('/api/coupon', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: code.trim(), items }), signal: controller.signal,
      });
      const data = await response.json();
      if (token !== generation.current) return;
      if (!response.ok || !data.success) throw new Error(data.message || 'Could not apply coupon.');
      if (Math.abs(Number(data.subtotal) - subtotal) > 0.01) throw new Error('Product prices have changed. Please re-add your items before applying this coupon.');
      onChange({ ...data, cartKey });
      setCode(data.code);
    } catch (error) {
      if (token === generation.current && !controller.signal.aborted) {
        setMessage(cleanCouponMessage(error instanceof Error ? error.message : 'Could not apply coupon.'));
      }
    } finally {
      if (token === generation.current) { setBusy(false); onBusy(false); }
    }
  };

  if (!enabled) return null;
  return (
    <div className="nje-coupon-wrap">
      <style dangerouslySetInnerHTML={{ __html: `
        .nje-coupon-wrap {
          margin-top: 18px;
          padding-top: 16px;
          border-top: 1px dashed var(--line, #e2e8f0);
        }
        .nje-coupon-label {
          display: block;
          font-size: 13.5px;
          font-weight: 600;
          color: var(--graphite, #191B1E);
          margin-bottom: 8px;
          letter-spacing: -0.01em;
        }
        .nje-coupon-row {
          display: flex !important;
          flex-direction: row !important;
          align-items: stretch !important;
          gap: 8px !important;
          width: 100% !important;
        }
        .nje-coupon-input {
          flex: 1 1 0% !important;
          min-width: 0 !important;
          width: 0 !important;
          height: 46px !important;
          padding: 0 14px !important;
          border: 1.5px solid var(--line, #e2e8f0) !important;
          border-radius: 10px !important;
          background: #ffffff !important;
          color: var(--graphite, #191B1E) !important;
          font-size: 14px !important;
          font-family: inherit !important;
          text-transform: uppercase !important;
          letter-spacing: 0.04em !important;
          font-weight: 600 !important;
          outline: none !important;
          transition: border-color 0.18s ease, box-shadow 0.18s ease !important;
          box-sizing: border-box !important;
        }
        .nje-coupon-input::placeholder {
          text-transform: none !important;
          letter-spacing: normal !important;
          color: #94a3b8 !important;
          font-weight: 400 !important;
        }
        .nje-coupon-input:focus {
          border-color: #191B1E !important;
          box-shadow: 0 0 0 3px rgba(25, 27, 30, 0.08) !important;
        }
        .nje-coupon-input:disabled {
          background: #f8fafc !important;
          color: #94a3b8 !important;
        }
        .nje-coupon-btn {
          flex: 0 0 auto !important;
          width: auto !important;
          min-width: 86px !important;
          height: 46px !important;
          margin: 0 !important;
          padding: 0 20px !important;
          border-radius: 10px !important;
          border: none !important;
          background: #191B1E !important;
          color: #ffffff !important;
          font-size: 14px !important;
          font-weight: 600 !important;
          font-family: inherit !important;
          cursor: pointer !important;
          display: inline-flex !important;
          align-items: center !important;
          justify-content: center !important;
          white-space: nowrap !important;
          transition: background 0.18s ease, transform 0.1s ease, opacity 0.18s ease !important;
          box-sizing: border-box !important;
        }
        .nje-coupon-btn:hover:not(:disabled) {
          background: #2D3136 !important;
        }
        .nje-coupon-btn:active:not(:disabled) {
          transform: scale(0.98) !important;
        }
        .nje-coupon-btn:disabled {
          background: #e2e8f0 !important;
          color: #94a3b8 !important;
          cursor: not-allowed !important;
          opacity: 0.7 !important;
        }
        .nje-coupon-applied-box {
          display: flex !important;
          align-items: center !important;
          justify-content: space-between !important;
          padding: 10px 14px !important;
          border-radius: 10px !important;
          background: #f0fdf4 !important;
          border: 1px solid #86efac !important;
          gap: 10px !important;
          box-sizing: border-box !important;
        }
        .nje-coupon-applied-info {
          display: flex !important;
          align-items: center !important;
          gap: 8px !important;
          color: #166534 !important;
          font-size: 13.5px !important;
          font-weight: 500 !important;
        }
        .nje-coupon-applied-tag {
          display: inline-flex !important;
          align-items: center !important;
          padding: 3px 8px !important;
          border-radius: 6px !important;
          background: #dcfce7 !important;
          border: 1px solid #bbf7d0 !important;
          font-weight: 700 !important;
          letter-spacing: 0.04em !important;
          text-transform: uppercase !important;
          font-size: 12.5px !important;
        }
        .nje-coupon-remove-btn {
          border: none !important;
          background: none !important;
          color: #dc2626 !important;
          font-size: 13px !important;
          font-weight: 600 !important;
          cursor: pointer !important;
          padding: 4px 8px !important;
          border-radius: 6px !important;
          transition: background 0.15s ease !important;
          margin: 0 !important;
          width: auto !important;
        }
        .nje-coupon-remove-btn:hover {
          background: #fee2e2 !important;
        }
        .nje-coupon-message {
          font-size: 12.5px !important;
          color: #dc2626 !important;
          margin: 8px 0 0 0 !important;
          display: flex !important;
          align-items: center !important;
          gap: 6px !important;
          font-weight: 500 !important;
        }
      `}} />

      <label htmlFor="coupon-code" className="nje-coupon-label">
        Coupon code
      </label>

      {applied ? (
        <div className="nje-coupon-applied-box">
          <div className="nje-coupon-applied-info">
            <span className="nje-coupon-applied-tag">
              🏷️ {applied.code}
            </span>
            <span>
              (-৳{Number(applied.discount).toLocaleString('en-US')}) applied
            </span>
          </div>
          <button
            type="button"
            disabled={disabled}
            onClick={() => {
              onChange(null);
              setMessage('');
            }}
            aria-label="Remove coupon"
            className="nje-coupon-remove-btn"
          >
            Remove
          </button>
        </div>
      ) : (
        <div className="nje-coupon-row">
          <input
            id="coupon-code"
            name="coupon_code"
            type="text"
            maxLength={80}
            autoComplete="off"
            placeholder="Enter code (e.g. offer100)"
            value={code}
            disabled={disabled || busy}
            onChange={(event) => {
              setCode(event.target.value);
              setMessage('');
            }}
            onKeyDown={(event) => {
              if (event.key === 'Enter') {
                event.preventDefault();
                void apply();
              }
            }}
            className="nje-coupon-input"
          />
          <button
            type="button"
            className="nje-coupon-btn"
            disabled={disabled || busy || !code.trim()}
            onClick={() => void apply()}
          >
            {busy ? 'Applying…' : 'Apply'}
          </button>
        </div>
      )}

      {message && (
        <p role="alert" className="nje-coupon-message">
          <span>⚠️</span>
          <span>{message}</span>
        </p>
      )}
    </div>
  );
}
