'use client';

import { useState } from 'react';
import { useAdminResolveReturn } from '@/lib/queries/use-returns';
import { useEscapeToClose } from '@/lib/hooks/use-escape-to-close';
import type { OrderReturnSummary, ReturnAdminAction } from '@alqove/api-client';

interface Props {
  return: OrderReturnSummary;
  escalationReason?: string | null;
  open: boolean;
  onClose: () => void;
  onResolved?: () => void;
}

const ACTIONS: { value: ReturnAdminAction; label: string; description: string }[] = [
  {
    value: 'force_refund',
    label: 'Refund the buyer',
    description: 'Override the seller and refund. Stripe refund is issued now.',
  },
  {
    value: 'force_close_no_refund',
    label: 'Close in seller’s favour',
    description: 'No refund is issued; the return is closed.',
  },
  {
    value: 'no_action',
    label: 'Resolve without action',
    description: 'Mark the escalation handled but leave the return where it is.',
  },
];

export function AdminResolveReturnDialog({
  return: r,
  escalationReason,
  open,
  onClose,
  onResolved,
}: Props) {
  const [action, setAction] = useState<ReturnAdminAction | ''>('');
  const [resolution, setResolution] = useState('');
  const [error, setError] = useState<string | null>(null);
  const resolve = useAdminResolveReturn();

  useEscapeToClose(open, onClose);

  if (!open) return null;

  const resolutionOk = resolution.trim().length >= 10;
  const submitDisabled = !action || !resolutionOk || resolve.isPending;

  const submit = async () => {
    setError(null);
    if (!action || !resolutionOk) return;
    try {
      await resolve.mutateAsync({
        returnId: r.id,
        action,
        resolution: resolution.trim(),
      });
      onResolved?.();
      onClose();
      setAction('');
      setResolution('');
    } catch (e) {
      setError((e as Error).message ?? 'Failed to resolve return.');
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Resolve escalated return"
      className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
    >
      <div className="w-full max-w-lg rounded-lg bg-white p-6 shadow-xl">
        <h2 className="text-lg font-semibold text-slate-900">Resolve escalated return</h2>
        <p className="mt-1 text-xs text-slate-500">
          Order {r.order_id.slice(0, 8)} · current state:{' '}
          <span className="font-medium text-slate-700">{r.state}</span>
        </p>

        {escalationReason && (
          <p className="mt-3 rounded-md bg-slate-50 p-3 text-sm text-slate-700">
            <span className="block text-xs font-medium text-slate-500">
              Buyer&apos;s escalation
            </span>
            {escalationReason}
          </p>
        )}

        <fieldset className="mt-4">
          <legend className="text-sm font-medium text-slate-700">Action</legend>
          <div className="mt-2 space-y-2">
            {ACTIONS.map((a) => (
              <label key={a.value} className="flex items-start gap-2 text-sm text-slate-800">
                <input
                  type="radio"
                  name="admin-action"
                  value={a.value}
                  checked={action === a.value}
                  onChange={() => setAction(a.value)}
                  className="mt-1"
                />
                <span>
                  <span className="font-medium text-slate-900">{a.label}</span>
                  <span className="block text-xs text-slate-500">{a.description}</span>
                </span>
              </label>
            ))}
          </div>
        </fieldset>

        <label className="mt-4 block">
          <span className="text-sm font-medium text-slate-700">
            Resolution notes (≥ 10 chars)
          </span>
          <textarea
            value={resolution}
            onChange={(e) => setResolution(e.target.value)}
            rows={4}
            maxLength={2000}
            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">{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={submitDisabled}
            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"
          >
            {resolve.isPending ? 'Resolving…' : 'Resolve'}
          </button>
        </div>
      </div>
    </div>
  );
}
