'use client';

import { useRouter } from 'next/navigation';
import { useState } from 'react';

type Props = {
  labels: Record<string, string>;
};

const TOPUP_PRESETS = [50000, 100000, 250000, 500000, 1000000];

function formatPreset(value: number) {
  if (value >= 1000000) return 'Rp 1jt';
  return `Rp ${value / 1000}rb`;
}

export function WalletTopupForm({ labels }: Props) {
  const router = useRouter();
  const [amount, setAmount] = useState('50000');
  const [description, setDescription] = useState('Development manual top up');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isMidtransSubmitting, setIsMidtransSubmitting] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  async function submitTopup(provider: 'manual' | 'midtrans') {
    const setLoading = provider === 'midtrans' ? setIsMidtransSubmitting : setIsSubmitting;
    setLoading(true);
    setMessage(null);

    try {
      const response = await fetch('/api/wallet/topups', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          provider,
          amountMinor: Number(amount || '0'),
          description,
        }),
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(typeof payload?.message === 'string' ? payload.message : labels.failedTopup);
      }
      if (provider === 'midtrans' && typeof payload?.redirectUrl === 'string' && payload.redirectUrl) {
        window.location.href = payload.redirectUrl;
        return;
      }
      setMessage(provider === 'midtrans' ? labels.midtransCreated : labels.topupSuccess);
      router.refresh();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : labels.failedTopup);
    } finally {
      setLoading(false);
    }
  }

  return (
    <form
      className="wallet-topup-form"
      onSubmit={async (event) => {
        event.preventDefault();
        await submitTopup('midtrans');
      }}
    >
      <label>
        <span>{labels.amount}</span>
        <input type="number" min="50000" step="1000" value={amount} onChange={(event) => setAmount(event.target.value)} />
      </label>
      <div className="wallet-topup-presets" aria-label={labels.presetAmounts}>
        {TOPUP_PRESETS.map((preset) => (
          <button key={preset} type="button" className={Number(amount) === preset ? 'is-active' : ''} onClick={() => setAmount(String(preset))}>
            {formatPreset(preset)}
          </button>
        ))}
      </div>
      <label>
        <span>{labels.descriptionField}</span>
        <input value={description} onChange={(event) => setDescription(event.target.value)} />
      </label>
      <button type="submit" disabled={isMidtransSubmitting || isSubmitting}>
        <span className="material-symbols-outlined">payments</span>
        {isMidtransSubmitting ? labels.processing : labels.payWithMidtrans}
      </button>
      <button type="button" className="wallet-secondary-button" disabled={isSubmitting || isMidtransSubmitting} onClick={() => submitTopup('manual')}>
        <span className="material-symbols-outlined">add_card</span>
        {isSubmitting ? labels.processing : labels.manualTopup}
      </button>
      {message ? <p>{message}</p> : null}
    </form>
  );
}
