'use client';

import { useState } from 'react';
import {
  useAdminOrder,
  useAdminRefund,
  useAdminForceCancel,
  useAdminReverseTransfer,
} from '@/lib/queries/use-admin';
import { ConfirmWithJustificationDialog } from '@/components/admin/confirm-with-justification-dialog';
import { AdminMessagesPanel } from '@/components/admin/admin-messages-panel';
import { useAuthStore } from '@/stores/auth';

type Action = 'refund' | 'force-cancel' | 'reverse';

function fmt(cents: number) {
  return `$${(cents / 100).toFixed(2)}`;
}

export function OrderDetailClient({ orderId }: { orderId: string }) {
  const { data, isLoading, isError } = useAdminOrder(orderId);
  const detail = data?.data;
  const refund = useAdminRefund(orderId);
  const forceCancel = useAdminForceCancel(orderId);
  const reverse = useAdminReverseTransfer(orderId);
  const adminUserId = useAuthStore((s) => s.user?.id ?? null);

  const [action, setAction] = useState<Action | null>(null);
  const [refundAmount, setRefundAmount] = useState<string>('');

  if (isLoading) return <div className="text-sm text-slate-400">Loading…</div>;
  if (isError || !detail)
    return (
      <p className="rounded bg-red-50 p-3 text-sm text-red-700">
        Couldn&apos;t load this order.
      </p>
    );

  const cancelled = !!detail.cancelled_at;
  const reversed = !!detail.transfer_reversed_at;

  const onConfirm = (justification: string) => {
    if (action === 'refund') {
      refund.mutate(
        { amountCents: Number(refundAmount), justification },
        { onSuccess: () => setAction(null) },
      );
    } else if (action === 'force-cancel') {
      forceCancel.mutate(justification, { onSuccess: () => setAction(null) });
    } else if (action === 'reverse') {
      reverse.mutate(justification, { onSuccess: () => setAction(null) });
    }
  };

  const lastError =
    refund.error?.message ?? forceCancel.error?.message ?? reverse.error?.message ?? null;

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">
        Order #{detail.id.slice(0, 8)}
      </h1>
      <p className="mt-1 text-sm text-slate-500">
        {detail.store.name} · {detail.status}
      </p>

      {lastError && (
        <p className="mt-4 rounded bg-red-50 p-3 text-sm text-red-700">
          Action failed: {lastError}
        </p>
      )}

      <section className="mt-4 rounded-lg border border-slate-200 bg-white p-4">
        <h2 className="font-semibold text-sm text-slate-700">Admin actions</h2>
        <div className="mt-2 flex gap-2">
          <button
            onClick={() => {
              setAction('refund');
              setRefundAmount(String(detail.total));
            }}
            className="rounded-md border border-slate-300 px-3 py-1 text-sm hover:bg-slate-50"
          >
            Issue refund
          </button>
          <button
            onClick={() => setAction('force-cancel')}
            disabled={cancelled}
            className="rounded-md border border-slate-300 px-3 py-1 text-sm hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Force cancel
          </button>
          <button
            onClick={() => setAction('reverse')}
            disabled={reversed || !detail.stripe_transfer_id}
            className="rounded-md border border-slate-300 px-3 py-1 text-sm hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Reverse transfer
          </button>
        </div>
      </section>

      <section className="mt-4 grid grid-cols-2 gap-4">
        <div className="rounded-lg border border-slate-200 bg-white p-4">
          <h2 className="font-semibold text-sm text-slate-700">Order summary</h2>
          <ul className="mt-2 text-sm text-slate-600 space-y-1">
            <li>Subtotal: {fmt(detail.subtotal)}</li>
            <li>Shipping: {fmt(detail.shipping_cost)}</li>
            <li className="font-semibold">Total: {fmt(detail.total)}</li>
          </ul>
        </div>
        <div className="rounded-lg border border-slate-200 bg-white p-4">
          <h2 className="font-semibold text-sm text-slate-700">Buyer</h2>
          <p className="mt-2 text-sm text-slate-600">
            {[detail.buyer.first_name, detail.buyer.last_name].filter(Boolean).join(' ') || (
              <span className="text-slate-400">Unknown</span>
            )}
          </p>
        </div>
      </section>

      <section className="mt-4 rounded-lg border border-slate-200 bg-white p-4">
        <h2 className="font-semibold text-sm text-slate-700">Line items</h2>
        {detail.items.length === 0 ? (
          <p className="mt-2 text-sm text-slate-400">No line items recorded for this order.</p>
        ) : (
          <ul className="mt-2 text-sm text-slate-600 divide-y divide-slate-100">
            {detail.items.map((it) => (
              <li key={it.id} className="py-2 flex justify-between">
                <span>{it.title_snapshot}</span>
                <span>{fmt(it.price_snapshot)}</span>
              </li>
            ))}
          </ul>
        )}
      </section>

      <section className="mt-4 rounded-lg border border-slate-200 bg-white p-4">
        <h2 className="font-semibold text-sm text-slate-700">Stripe state</h2>
        <ul className="mt-2 text-sm text-slate-600 space-y-1">
          <li>
            Transfer:{' '}
            {detail.stripe_transfer_id ? (
              reversed ? (
                <>
                  Reversed —{' '}
                  <span className="font-mono text-xs">
                    {detail.stripe_transfer_reversal_id ?? '(reversal id missing)'}
                  </span>
                </>
              ) : (
                <>
                  Transferred — <span className="font-mono text-xs">{detail.stripe_transfer_id}</span>
                </>
              )
            ) : (
              'Not transferred yet.'
            )}
          </li>
          <li>
            Refund:{' '}
            {detail.stripe_refund_id ? (
              <span className="font-mono text-xs">{detail.stripe_refund_id}</span>
            ) : (
              'No refund issued.'
            )}
          </li>
        </ul>
      </section>

      {adminUserId && (
        <AdminMessagesPanel
          orderId={detail.id}
          adminUserId={adminUserId}
          buyerLabel={
            [detail.buyer.first_name, detail.buyer.last_name?.[0]]
              .filter(Boolean)
              .join(' ') || 'Buyer'
          }
          storeLabel={detail.store.name}
        />
      )}

      <ConfirmWithJustificationDialog
        open={action === 'force-cancel'}
        title="Force-cancel this order?"
        description="The order will be marked Cancelled and a full refund will be issued."
        confirmLabel="Force cancel"
        onConfirm={onConfirm}
        onCancel={() => setAction(null)}
        isPending={forceCancel.isPending}
      />
      <ConfirmWithJustificationDialog
        open={action === 'reverse'}
        title="Reverse the Stripe Transfer?"
        description="The transferred funds will be clawed back from the seller's connected account."
        confirmLabel="Reverse transfer"
        onConfirm={onConfirm}
        onCancel={() => setAction(null)}
        isPending={reverse.isPending}
      />

      {action === 'refund' && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
            <h2 className="text-lg font-bold text-slate-900">Issue a refund</h2>
            <label className="mt-3 block text-sm">
              <span className="font-medium text-slate-700">Refund amount (cents)</span>
              <input
                aria-label="Refund amount (cents)"
                type="number"
                value={refundAmount}
                onChange={(e) => setRefundAmount(e.target.value)}
                className="mt-1 w-full rounded-md border border-slate-300 p-2 text-sm"
              />
            </label>
            <RefundJustification
              onConfirm={onConfirm}
              onCancel={() => setAction(null)}
              pending={refund.isPending}
            />
          </div>
        </div>
      )}
    </div>
  );
}

function RefundJustification({
  onConfirm,
  onCancel,
  pending,
}: {
  onConfirm: (j: string) => void;
  onCancel: () => void;
  pending: boolean;
}) {
  const [text, setText] = useState('');
  const disabled = text.trim().length < 20 || pending;
  return (
    <>
      <label className="mt-3 block text-sm">
        <span className="font-medium text-slate-700">Justification</span>
        <textarea
          aria-label="Justification"
          value={text}
          onChange={(e) => setText(e.target.value)}
          className="mt-1 w-full rounded-md border border-slate-300 p-2 text-sm"
          rows={4}
          placeholder="≥ 20 characters — recorded in the audit log"
        />
      </label>
      <div className="mt-4 flex gap-2">
        <button
          onClick={onCancel}
          className="flex-1 rounded-md border border-slate-300 px-3 py-2 text-sm"
        >
          Cancel
        </button>
        <button
          disabled={disabled}
          onClick={() => onConfirm(text.trim())}
          className="flex-1 rounded-md bg-slate-900 px-3 py-2 text-sm text-white disabled:opacity-50"
        >
          {pending ? 'Working…' : 'Confirm'}
        </button>
      </div>
    </>
  );
}
