'use client';

import { ArrowRight, Check } from 'lucide-react';
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';

import { FieldError, FormAlert } from '@/components/forms/form-field';
import { Button } from '@/components/ui/button';
import { CopyButton } from '@/components/ui/copy-button';
import { Input } from '@/components/ui/input';
import { Modal } from '@/components/ui/overlay';
import { ApiError, api } from '@/lib/api-client';
import { formatMoney, minorFromMajor } from '@/lib/money';
import { queryKeys } from '@/lib/query-keys';
import { cn } from '@/lib/utils';
import { MAX_TOP_UP_MINOR, MIN_TOP_UP_MINOR } from '@/shared/schemas/wallet';

const PRESETS = [50, 100, 250, 500];

export function TopUpModal({
  open,
  currency,
  provider,
  onClose,
}: {
  open: boolean;
  currency: string;
  provider: 'manual' | 'stripe';
  onClose: () => void;
}) {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [amount, setAmount] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [instructions, setInstructions] = useState<string | null>(null);
  const [pending, setPending] = useState(false);
  const amountMinor = minorFromMajor(amount);
  const rangeText = `between ${formatMoney(MIN_TOP_UP_MINOR, currency)} and ${formatMoney(MAX_TOP_UP_MINOR, currency)}`;
  const outOfRange = amount.length > 0 && (amountMinor === null || amountMinor < MIN_TOP_UP_MINOR || amountMinor > MAX_TOP_UP_MINOR);

  const close = () => {
    setInstructions(null);
    setError(null);
    onClose();
  };

  return (
    <Modal open={open} title={instructions === null ? 'Top up wallet' : 'Complete your bank transfer'} onClose={close}>
      {instructions !== null ? (
        <div className="grid gap-5" role="status">
          <ol className="grid gap-4">
            {[
              { title: `Transfer ${amountMinor === null ? 'the amount' : formatMoney(amountMinor, currency)}`, text: 'Use the bank details below from your business account.' },
              { title: 'Use the payment reference', text: 'Include the reference from the instructions so we can match your transfer.' },
              { title: 'We confirm and credit your wallet', text: 'Usually within one business day. You will see it under pending top-ups until then.' },
            ].map((step, index) => (
              <li key={step.title} className="flex gap-3">
                <span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-primary-soft text-small font-bold text-primary">{index + 1}</span>
                <div>
                  <p className="text-small font-semibold">{step.title}</p>
                  <p className="text-caption text-muted-foreground">{step.text}</p>
                </div>
              </li>
            ))}
          </ol>
          <div className="relative rounded-lg border border-border bg-surface-muted">
            <div className="absolute right-2 top-2">
              <CopyButton notify value={instructions} label="Copy bank details" className="bg-surface shadow-xs" />
            </div>
            <pre className="whitespace-pre-wrap p-4 pr-12 font-mono text-small leading-6 text-foreground">{instructions}</pre>
          </div>
          <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
            <Button type="button" variant="secondary" onClick={() => router.push('/wallet')}>
              Go to wallet
            </Button>
            <Button type="button" onClick={close}>
              <Check className="h-4 w-4" aria-hidden="true" />
              Done
            </Button>
          </div>
        </div>
      ) : (
        <form
          className="grid gap-5"
          noValidate
          onSubmit={(event) => {
            event.preventDefault();
            if (amountMinor === null || amountMinor < MIN_TOP_UP_MINOR || amountMinor > MAX_TOP_UP_MINOR) {
              setError(`Enter an amount ${rangeText}.`);
              return;
            }
            setPending(true);
            setError(null);
            void api<{ instructions?: string; checkoutUrl?: string }>('/wallet/topups', { json: { amountMinor, provider } })
              .then(async (result) => {
                await queryClient.invalidateQueries({ queryKey: queryKeys.me });
                await queryClient.invalidateQueries({ queryKey: queryKeys.wallet });
                if (result.checkoutUrl !== undefined) {
                  window.location.assign(result.checkoutUrl);
                  return;
                }
                setInstructions(result.instructions ?? 'The top-up was requested.');
              })
              .catch((reason: unknown) => setError(reason instanceof ApiError ? reason.message : 'The top-up could not be created.'))
              .finally(() => setPending(false));
          }}
        >
          <fieldset>
            <legend className="mb-2 text-small font-semibold">Amount</legend>
            <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
              {PRESETS.map((preset) => {
                const selected = amount === String(preset);
                return (
                  <label
                    key={preset}
                    className={cn(
                      'relative grid h-16 cursor-pointer place-items-center rounded-lg border bg-surface transition-[border-color,background-color,box-shadow] has-[:focus-visible]:shadow-glow',
                      selected ? 'border-2 border-primary bg-primary-soft' : 'border-border hover:border-border-strong',
                    )}
                  >
                    <input
                      type="radio"
                      name="topup-preset"
                      className="sr-only"
                      checked={selected}
                      onChange={() => {
                        setAmount(String(preset));
                        setError(null);
                      }}
                    />
                    <span className="font-display text-h3 font-bold tabular-nums">{formatMoney(preset * 100, currency)}</span>
                    {selected ? (
                      <span className="absolute right-1.5 top-1.5 grid h-4 w-4 place-items-center rounded-full bg-primary text-primary-foreground" aria-hidden="true">
                        <Check className="h-2.5 w-2.5" strokeWidth={3} />
                      </span>
                    ) : null}
                  </label>
                );
              })}
            </div>
          </fieldset>
          <div className="grid gap-1.5">
            <label htmlFor="topup-amount" className="text-small font-semibold">
              Or enter an amount
            </label>
            <Input
              id="topup-amount"
              inputMode="decimal"
              className="tabular-nums"
              leading={<span className="text-small font-semibold text-muted-foreground">{currency}</span>}
              value={amount}
              placeholder="0.00"
              aria-invalid={outOfRange || error !== null ? true : undefined}
              aria-describedby="topup-amount-hint"
              onChange={(event) => {
                setAmount(event.target.value);
                setError(null);
              }}
            />
            {outOfRange ? (
              <FieldError id="topup-amount-hint">Enter an amount {rangeText}.</FieldError>
            ) : (
              <p id="topup-amount-hint" className="text-caption text-muted-foreground">
                Minimum {formatMoney(MIN_TOP_UP_MINOR, currency)}, maximum {formatMoney(MAX_TOP_UP_MINOR, currency)}.
              </p>
            )}
          </div>
          <div className="flex items-center justify-between rounded-lg bg-surface-muted px-4 py-3 text-small">
            <span className="text-muted-foreground">{provider === 'manual' ? 'Pay by bank transfer' : 'Pay by card'}</span>
            <span className="font-display text-h3 font-bold tabular-nums">{amountMinor === null || outOfRange ? '—' : formatMoney(amountMinor, currency)}</span>
          </div>
          {error !== null && !outOfRange ? <FormAlert>{error}</FormAlert> : null}
          <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
            <Button type="button" variant="secondary" onClick={close}>
              Cancel
            </Button>
            <Button type="submit" loading={pending} className="group">
              Continue
              {pending ? null : <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" aria-hidden="true" />}
            </Button>
          </div>
        </form>
      )}
    </Modal>
  );
}
