/**
 * CouponForm Component
 * Apply and validate discount codes for subscriptions
 */

import React, { useState } from 'react';
import {
  Tag,
  Check,
  X,
  Loader2,
  Percent,
  AlertCircle,
} from 'lucide-react';
import { validateCoupon } from '../../services/payment.service';

export interface CouponInfo {
  code: string;
  valid: boolean;
  discountType: 'percent' | 'fixed';
  discountValue: number;
  discountAmount?: number;
  expiresAt?: string;
  minPurchase?: number;
  maxUses?: number;
  usedCount?: number;
}

interface CouponFormProps {
  planId?: string;
  amount?: number;
  onApply: (couponInfo: CouponInfo) => void;
  onClear?: () => void;
  appliedCoupon?: CouponInfo | null;
  disabled?: boolean;
}

const CouponForm: React.FC<CouponFormProps> = ({
  planId,
  amount,
  onApply,
  onClear,
  appliedCoupon,
  disabled = false,
}) => {
  const [code, setCode] = useState('');
  const [isValidating, setIsValidating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleValidate = async () => {
    if (!code.trim()) {
      setError('Please enter a coupon code');
      return;
    }

    setIsValidating(true);
    setError(null);

    try {
      const result = await validateCoupon(code.trim().toUpperCase(), planId || '');

      if (result.valid) {
        // Calculate discount amount if we have the price
        let discountAmount: number | undefined;
        if (amount) {
          discountAmount = result.discountType === 'percent'
            ? (amount * result.discount) / 100
            : Math.min(result.discount, amount);
        }

        onApply({
          code: code.trim().toUpperCase(),
          valid: result.valid,
          discountType: result.discountType === 'amount' ? 'fixed' : 'percent',
          discountValue: result.discount,
          discountAmount,
        });
        setCode('');
      } else {
        setError(result.message || 'Invalid coupon code');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to validate coupon');
    } finally {
      setIsValidating(false);
    }
  };

  const handleClear = () => {
    setCode('');
    setError(null);
    onClear?.();
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isValidating && code.trim()) {
      e.preventDefault();
      handleValidate();
    }
  };

  // Show applied coupon state
  if (appliedCoupon) {
    return (
      <div className="flex items-center justify-between p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-green-500/20 rounded-lg">
            <Tag className="w-4 h-4 text-green-400" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="font-medium text-green-400">{appliedCoupon.code}</span>
              <Check className="w-4 h-4 text-green-400" />
            </div>
            <p className="text-sm text-gray-400">
              {appliedCoupon.discountType === 'percent' ? (
                <>{appliedCoupon.discountValue}% off</>
              ) : (
                <>${appliedCoupon.discountValue} off</>
              )}
              {appliedCoupon.discountAmount && (
                <span className="text-green-400 ml-1">
                  (-${appliedCoupon.discountAmount.toFixed(2)})
                </span>
              )}
            </p>
          </div>
        </div>
        <button
          onClick={handleClear}
          disabled={disabled}
          className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors disabled:opacity-50"
          title="Remove coupon"
        >
          <X className="w-4 h-4" />
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Tag className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input
            type="text"
            value={code}
            onChange={(e) => {
              setCode(e.target.value.toUpperCase());
              setError(null);
            }}
            onKeyDown={handleKeyDown}
            placeholder="Enter coupon code"
            disabled={disabled || isValidating}
            className="w-full pl-10 pr-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-blue-500 disabled:opacity-50 uppercase"
          />
        </div>
        <button
          onClick={handleValidate}
          disabled={disabled || isValidating || !code.trim()}
          className="flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isValidating ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" />
              Checking...
            </>
          ) : (
            <>
              <Percent className="w-4 h-4" />
              Apply
            </>
          )}
        </button>
      </div>

      {error && (
        <div className="flex items-center gap-2 text-sm text-red-400">
          <AlertCircle className="w-4 h-4" />
          <span>{error}</span>
        </div>
      )}
    </div>
  );
};

export default CouponForm;
