'use client';

import { useState } from 'react';
import { useAdminPostAdjustment } from '@/lib/queries/use-admin-financials';
import { useEscapeToClose } from '@/lib/hooks/use-escape-to-close';
import type { AdjustmentType } from '@alqove/api-client';

interface Props {
  open: boolean;
  storeId: string;
  onClose: () => void;
  onPosted?: () => void;
}

/**
 * Manual ledger adjustment modal — admin posts a credit or debit against a
 * store's ledger. Reason is required (≥ 10 chars) for audit; amount is
 * collected in dollars and converted to cents before submission.
 */
export function AdminLedgerAdjustmentDialog({
  open,
  storeId,
  onClose,
  onPosted,
}: Props) {
  const [type, setType] = useState<AdjustmentType>('credit');
  const [amount, setAmount] = useState('');
  const [reason, setReason] = useState('');
  const [error, setError] = useState<string | null>(null);

  const post = useAdminPostAdjustment(storeId);

  useEscapeToClose(open, onClose);

  if (!open) return null;

  const reasonOk = reason.trim().length >= 10;
  const dollars = Number(amount);
  const amountOk = Number.isFinite(dollars) && dollars > 0;
  const disabled = !reasonOk || !amountOk || post.isPending;

  const submit = async () => {
    setError(null);
    if (!reasonOk || !amountOk) return;
    try {
      await post.mutateAsync({
        type,
        amount_cents: Math.round(dollars * 100),
        reason: reason.trim(),
      });
      onPosted?.();
      setAmount('');
      setReason('');
      setType('credit');
      onClose();
    } catch (e) {
      setError((e as Error).message ?? 'Failed to post adjustment.');
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Post manual ledger adjustment"
      className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
    >
      <div className="w-full max-w-md rounded-lg bg-white p-6 shadow-xl">
        <h2 className="text-lg font-semibold text-slate-900">
          Manual adjustment
        </h2>
        <p className="mt-1 text-xs text-slate-500">
          Posts a one-off credit or debit against this store&apos;s ledger.
        </p>

        <fieldset className="mt-4">
          <legend className="text-sm font-medium text-slate-700">Type</legend>
          <div className="mt-2 flex gap-4">
            <label className="flex items-center gap-2 text-sm text-slate-800">
              <input
                type="radio"
                name="adjustment-type"
                value="credit"
                checked={type === 'credit'}
                onChange={() => setType('credit')}
                data-testid="adjustment-type-credit"
              />
              <span>Credit (adds to balance)</span>
            </label>
            <label className="flex items-center gap-2 text-sm text-slate-800">
              <input
                type="radio"
                name="adjustment-type"
                value="debit"
                checked={type === 'debit'}
                onChange={() => setType('debit')}
                data-testid="adjustment-type-debit"
              />
              <span>Debit (deducts from balance)</span>
            </label>
          </div>
        </fieldset>

        <label className="mt-4 block">
          <span className="text-sm font-medium text-slate-700">
            Amount (USD)
          </span>
          <input
            type="number"
            min="0.01"
            step="0.01"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            data-testid="adjustment-amount"
            placeholder="0.00"
            className="mt-1 block w-full rounded-md border border-slate-300 p-2 text-sm"
          />
        </label>

        <label className="mt-4 block">
          <span className="text-sm font-medium text-slate-700">
            Reason (≥ 10 chars)
          </span>
          <textarea
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            rows={3}
            maxLength={2000}
            data-testid="adjustment-reason"
            className="mt-1 block w-full rounded-md border border-slate-300 p-2 text-sm"
          />
        </label>

        {error && (
          <p
            className="mt-2 text-sm text-red-600"
            data-testid="adjustment-error"
          >
            {error}
          </p>
        )}

        <div className="mt-4 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="rounded-md border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={submit}
            disabled={disabled}
            data-testid="adjustment-submit"
            className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-60"
          >
            {post.isPending ? 'Posting…' : 'Post adjustment'}
          </button>
        </div>
      </div>
    </div>
  );
}
