'use client';

import { Button } from '@/components/ui/Button';
import { Label, Text } from '@/components/ui/Typography';
import { useTranslation } from '@/lib/hooks/useTranslation';
import { AlertCircle, CheckCircle } from 'lucide-react';
import { FormEvent, useState, useTransition } from 'react';
import { validateDiscountCode } from './actions';

export function CartDiscountForm() {
  const { t } = useTranslation();
  const [isPending, startTransition] = useTransition();
  const [couponCode, setCouponCode] = useState('');
  const [couponMessage, setCouponMessage] = useState<{ text: string; isValid: boolean } | null>(null);

  // Handle coupon validation
  const handleCouponSubmit = (e: FormEvent) => {
    e.preventDefault();
    
    if (!couponCode.trim()) {
      setCouponMessage({ 
        text: 'Please enter a discount code', 
        isValid: false 
      });
      return;
    }
    
    setCouponMessage(null);
    
    startTransition(async () => {
      try {
        const result = await validateDiscountCode({}, couponCode);
        setCouponMessage({ 
          text: result.message, 
          isValid: result.isValid 
        });
      } catch (error) {
        setCouponMessage({ 
          text: 'Error validating coupon code', 
          isValid: false 
        });
      }
    });
  };

  return (
    <div className="mt-6">
      <Label className="mb-2">{t('cart.discountCode')}</Label>
      <form onSubmit={handleCouponSubmit} className="space-y-2">
        <div className="flex">
          <input
            type="text"
            className="flex-1 border rounded-l-md p-3"
            placeholder={t('cart.discountCodePlaceholder')}
            value={couponCode}
            onChange={(e) => setCouponCode(e.target.value)}
            disabled={isPending}
          />
          <Button 
            type="submit" 
            variant="primary"
            className="rounded-l-none"
            disabled={isPending}
          >
            {isPending ? 'Loading...' : t('cart.apply')}
          </Button>
        </div>
        
        {/* Coupon feedback message */}
        {couponMessage && (
          <div className={`flex items-center ${couponMessage.isValid ? 'text-green-600' : 'text-red-600'} mt-2`}>
            {couponMessage.isValid ? 
              <CheckCircle size={16} className="mr-1" /> : 
              <AlertCircle size={16} className="mr-1" />
            }
            <Text size="sm" as="span" className={couponMessage.isValid ? 'text-green-600' : 'text-red-600'}>
              {couponMessage.text}
            </Text>
          </div>
        )}
      </form>
    </div>
  );
} 