'use client';

/**
 * CancelReturnButtonIsland
 *
 * Renders a "Cancel request" button when a return is in 'requested' status.
 * Shows an AlertDialog to confirm before POSTing to POST /api/returns/:id/cancel.
 * Redirects the buyer back to the purchase page on success.
 */

import { useState } from 'react';
import { Button } from '@/components/ui/primitives/Button';
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/overlays/AlertDialog';
import { useT } from '@/lib/i18n/react';
import { getCsrfToken } from '@/lib/csrf';
import { captureCaught } from '@/lib/observability';

interface CancelReturnButtonIslandProps {
  returnId: string;
  purchaseId: string;
}

export function CancelReturnButtonIsland({ returnId, purchaseId }: CancelReturnButtonIslandProps) {
  const t = useT('returns');
  const [open, setOpen] = useState(false);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleConfirm() {
    setIsPending(true);
    setError(null);
    try {
      const res = await fetch(`/api/returns/${returnId}/cancel`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-csrf-token': getCsrfToken(),
        },
      });
      if (res.ok) {
        location.assign(`/purchases/${purchaseId}`);
      } else {
        setError(t('cancelReturnError'));
        setIsPending(false);
      }
    } catch (err) {
      captureCaught(err, {
        scope: 'features.returns.CancelReturnButtonIsland',
        severity: 'warning',
      });
      setError(t('cancelReturnError'));
      setIsPending(false);
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>
        <Button variant="danger" size="md" className="w-full">
          {t('cancelReturn')}
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{t('cancelReturn')}</AlertDialogTitle>
          <AlertDialogDescription>{t('cancelReturnDesc')}</AlertDialogDescription>
        </AlertDialogHeader>
        {error && (
          <p role="alert" className="text-danger-600 mt-2 text-sm">
            {error}
          </p>
        )}
        <AlertDialogFooter>
          <Button
            type="button"
            variant="danger"
            disabled={isPending}
            aria-busy={isPending}
            onClick={handleConfirm}
          >
            {t('confirmCancel')}
          </Button>
          <AlertDialogCancel disabled={isPending}>{t('cancelReturnKeep')}</AlertDialogCancel>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
