'use client';

import { useState } from 'react';
import { useEscalateReturn } from '@/lib/queries/use-returns';
import type { OrderReturn, ReturnAdminAction } from '@alqove/api-client';

interface Props {
  return: OrderReturn;
}

const ESCALATABLE_STATES = new Set([
  'approved',
  'awaiting_shipment',
  'in_transit',
  'received',
]);

const ACTION_LABELS: Record<ReturnAdminAction, string> = {
  force_refund: 'Refunded the buyer',
  force_close_no_refund: 'Closed in the seller’s favour',
  no_action: 'Resolved without further action',
};

export function EscalateReturnButton({ return: r }: Props) {
  const [open, setOpen] = useState(false);
  const [reason, setReason] = useState('');
  const [error, setError] = useState<string | null>(null);
  const escalate = useEscalateReturn();

  const escalation = r.escalation;

  if (escalation && escalation.state === 'open') {
    return (
      <div
        role="status"
        className="rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900"
      >
        Escalation submitted — admin will follow up shortly.
      </div>
    );
  }

  if (escalation && escalation.state === 'resolved') {
    const actionLabel = escalation.action ? ACTION_LABELS[escalation.action] : null;
    return (
      <div
        role="status"
        className="rounded-md border border-slate-200 bg-slate-50 p-3 text-sm text-slate-700"
      >
        <p className="font-medium">Resolved by admin</p>
        {actionLabel && <p className="mt-1 text-xs text-slate-500">{actionLabel}</p>}
        {escalation.resolution && (
          <p className="mt-1 text-xs text-slate-600">{escalation.resolution}</p>
        )}
      </div>
    );
  }

  if (!ESCALATABLE_STATES.has(r.state)) {
    return null;
  }

  const reasonOk = reason.trim().length >= 10;
  const submitDisabled = !reasonOk || escalate.isPending;

  const submit = async () => {
    setError(null);
    if (!reasonOk) return;
    try {
      await escalate.mutateAsync({ returnId: r.id, reason: reason.trim() });
      setOpen(false);
      setReason('');
    } catch (e) {
      setError((e as Error).message ?? 'Failed to submit escalation.');
    }
  };

  if (!open) {
    return (
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="text-sm text-slate-600 underline hover:text-slate-900"
      >
        Need help with this return?
      </button>
    );
  }

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Escalate return"
      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">Tell us what&apos;s wrong</h2>
        <p className="mt-1 text-sm text-slate-500">
          Escalating sends this return to Alqove support for review. They&apos;ll read
          your message and the seller&apos;s response and make a binding decision.
        </p>

        <label className="mt-4 block">
          <span className="text-sm font-medium text-slate-700">
            What&apos;s the problem? (≥ 10 chars)
          </span>
          <textarea
            value={reason}
            onChange={(e) => setReason(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={() => setOpen(false)}
            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"
          >
            {escalate.isPending ? 'Submitting…' : 'Submit'}
          </button>
        </div>
      </div>
    </div>
  );
}
