'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';
import { useToast } from './Toaster';

type PromoState = 'idle' | 'expanded' | 'loading' | 'applied' | 'error';

interface PromoCodeInputProps {
  onApply: (code: string) => Promise<void>;
  className?: string;
}

export function PromoCodeInput({ onApply, className }: PromoCodeInputProps) {
  const t = useTranslations('promo');
  const tToast = useTranslations('toast');
  const tCommon = useTranslations('common');
  const toast = useToast();
  const [promoState, setPromoState] = useState<PromoState>('idle');
  const [code, setCode] = useState('');
  const [appliedCode, setAppliedCode] = useState('');

  const handleApply = async () => {
    if (!code.trim()) return;
    setPromoState('loading');
    try {
      await onApply(code.trim());
      setAppliedCode(code.trim());
      setPromoState('applied');
      toast(tToast('promo_applied'), 'success');
    } catch (err) {
      setPromoState('error');
      const rejection =
        err instanceof Error
          ? err.message
          : typeof err === 'object' && err !== null && 'rejection_message' in err
            ? String((err as { rejection_message: string }).rejection_message)
            : null;
      toast(rejection ?? tToast('promo_rejected'), 'error');
    }
  };

  const handleRemove = () => {
    setCode('');
    setAppliedCode('');
    setPromoState('idle');
  };

  if (promoState === 'applied') {
    return (
      <div className={cn('flex items-center justify-between rounded-md bg-success/10 px-3 py-2 text-sm', className)}>
        <span className="text-success font-medium">{t('applied')}: {appliedCode}</span>
        <button type="button" onClick={handleRemove} className="text-xs text-neutral-500 hover:text-neutral-700 transition-colors ms-3">
          {t('remove')}
        </button>
      </div>
    );
  }

  if (promoState === 'idle') {
    return (
      <button
        type="button"
        onClick={() => setPromoState('expanded')}
        className={cn('text-sm text-primary-600 hover:underline text-start', className)}
      >
        {t('have_code')}
      </button>
    );
  }

  return (
    <div className={cn('space-y-1', className)}>
      <div className="flex gap-2">
        <input
          type="text"
          value={code}
          onChange={(e) => setCode(e.target.value)}
          placeholder={t('placeholder')}
          className="input flex-1"
          disabled={promoState === 'loading'}
          onKeyDown={(e) => e.key === 'Enter' && handleApply()}
        />
        <button
          type="button"
          onClick={handleApply}
          disabled={promoState === 'loading' || !code.trim()}
          className="btn-primary shrink-0 flex items-center gap-1.5"
        >
          {promoState === 'loading' ? (
            <>
              <svg className="h-4 w-4 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" aria-hidden="true">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              <span className="sr-only">{tCommon('loading')}</span>
            </>
          ) : t('apply')}
        </button>
      </div>
      {promoState === 'error' && (
        <p className="text-xs text-danger">{t('invalid')}</p>
      )}
    </div>
  );
}
