import React, { useState } from 'react';

import Button from '../widgets/Button';
import { useAppStateContext } from '../../context/user.data.context';
import { redeemDiscountCode } from '../../service/discount/discount.service';

/**
 * Voucher code input for the pricing page. Redeems an EXTEND_TRIAL_DAYS code,
 * shows how many trial days were granted and refreshes the user so the trial
 * countdown updates.
 */
const VoucherRedeem = (): React.ReactElement => {
  const { fetchUser } = useAppStateContext();

  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleRedeem = async (): Promise<void> => {
    if (!code.trim()) return;
    setLoading(true);
    setError(null);
    setSuccess(null);

    try {
      const res: any = await redeemDiscountCode(code.trim());

      if (res?.success && res?.trial_days_granted !== undefined) {
        const granted: number = res.trial_days_granted ?? 0;
        const remaining: number = res.remaining_trial_days ?? 0;
        setSuccess(
          `You've got +${granted} trial ${
            granted === 1 ? 'day' : 'days'
          }! You now have ${remaining} ${
            remaining === 1 ? 'day' : 'days'
          } of trial left.`
        );
        setCode('');
        await fetchUser();
      } else {
        setError(
          res?.error || res?.errors || 'This code could not be redeemed.'
        );
      }
    } catch {
      setError('This code could not be redeemed.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="mb-6 rounded-lg border border-gray-200 bg-white p-5">
      <h3 className="text-sm font-semibold text-gray-900">Voucher</h3>
      <p className="mt-0.5 text-xs text-gray-500">
        Have a voucher? Enter it below.
      </p>

      <div className="mt-3 flex max-w-md flex-col gap-3 sm:flex-row sm:items-center">
        <input
          type="text"
          value={code}
          onChange={e => setCode(e.target.value.toUpperCase())}
          onKeyDown={e => {
            if (e.key === 'Enter') handleRedeem();
          }}
          placeholder="ENTER VOUCHER"
          className="flex-1 rounded-md border border-gray-300 bg-white px-3 py-2 font-mono text-sm uppercase text-gray-900 placeholder:text-gray-400 focus:border-gray-400 focus:outline-none focus:ring-1 focus:ring-gray-200"
        />
        <Button
          onClick={handleRedeem}
          isLoading={loading}
          disabled={loading || !code.trim()}
          className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white"
        >
          Apply
        </Button>
      </div>

      {success && (
        <div className="mt-3 max-w-md rounded-md bg-emerald-50 p-3 text-sm text-emerald-800 ring-1 ring-inset ring-emerald-600/20">
          {success}
        </div>
      )}
      {error && (
        <div className="mt-3 max-w-md rounded-md bg-red-50 p-3 text-sm text-red-800 ring-1 ring-inset ring-red-600/20">
          {error}
        </div>
      )}
    </div>
  );
};

export default VoucherRedeem;
