'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { api } from '@/lib/api';

type Reason = 'sold_locally' | 'item_damaged' | 'other';
const REASONS: { value: Reason; label: string }[] = [
  { value: 'sold_locally', label: 'Sold locally (in store)' },
  { value: 'item_damaged', label: 'Item damaged / unsellable' },
  { value: 'other',         label: 'Other' },
];

export function CancelOrderDialog({ storeId, orderId }: { storeId: string; orderId: string }) {
  const [open, setOpen] = useState(false);
  const [reason, setReason] = useState<Reason>('sold_locally');
  const [note, setNote] = useState('');
  const qc = useQueryClient();

  const mut = useMutation({
    mutationFn: () =>
      api.orders.storeCancel(storeId, orderId, { reason, note: note || null }),
    onSuccess: (response) => {
      qc.invalidateQueries({ queryKey: ['seller-order', storeId, orderId] });
      qc.invalidateQueries({ queryKey: ['seller-orders', storeId] });
      // Keep the dialog open if Stripe failed so the seller sees the warning;
      // close on full success.
      if (!response?.warning?.stripe_error) {
        setOpen(false);
      }
    },
  });

  const stripeWarning = mut.data?.warning?.stripe_error ?? null;

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <button className="rounded border border-terracotta/30 px-3 py-1.5 text-sm text-terracotta hover:bg-terracotta/5">
          Cancel order
        </button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Cancel this order?</DialogTitle>
          <DialogDescription>
            The buyer will be refunded and items will be relisted.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-3">
          <label className="flex flex-col text-sm">
            <span className="mb-1 text-xs uppercase tracking-wide text-ink/60">Reason</span>
            <select
              value={reason}
              onChange={(e) => setReason(e.target.value as Reason)}
              className="rounded border border-forest/20 bg-white px-2 py-1.5"
            >
              {REASONS.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}
            </select>
          </label>
          <label className="flex flex-col text-sm">
            <span className="mb-1 text-xs uppercase tracking-wide text-ink/60">Note (optional)</span>
            <textarea
              value={note}
              onChange={(e) => setNote(e.target.value.slice(0, 500))}
              rows={3}
              className="rounded border border-forest/20 bg-white px-2 py-1.5"
            />
            <span className="mt-1 text-xs text-ink/40">{note.length}/500</span>
          </label>
          {mut.isError && <p className="text-sm text-terracotta">Cancellation failed. Try again.</p>}
          {stripeWarning && (
            <p className="rounded bg-amber-50 p-2 text-xs text-amber-800">
              Cancellation recorded, but the buyer&apos;s refund couldn&apos;t be processed
              automatically. The platform will reconcile this — no further action
              required from you.
            </p>
          )}
        </div>
        <DialogFooter>
          <button onClick={() => setOpen(false)} className="rounded px-3 py-1.5 text-sm text-ink/70 hover:bg-bone">
            Keep order
          </button>
          <button
            onClick={() => mut.mutate()}
            disabled={mut.isPending}
            className="rounded bg-terracotta px-3 py-1.5 text-sm font-semibold text-white hover:bg-terracotta/90 disabled:opacity-50"
          >
            {mut.isPending ? 'Cancelling…' : 'Cancel order'}
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
