'use client';
// @design-system: admin/SlugRegenerateButton/SlugRegenerateButton

/**
 * SlugRegenerateButton — confirmation modal + API call to regenerate a translation slug.
 * Writes a redirect row then re-enqueues title translation.
 */

import { useState } from 'react';
import { Button } from '@/components/ui/primitives/Button';
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from '@/components/ui/overlays/AlertDialog';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip/Tooltip';
import { useT } from '@/lib/i18n/react';
import { getCsrfToken } from '@/lib/csrf';
import { captureCaught } from '@/lib/observability';
import { fetchWithRefresh } from '@/lib/api/refresh-on-401';

export interface SlugRegenerateButtonProps {
  dealId: string;
  locale: string;
  onDone?: () => void;
}

export function SlugRegenerateButton({ dealId, locale, onDone }: SlugRegenerateButtonProps) {
  const t = useT('admin_translations');
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  async function handleConfirm() {
    setLoading(true);
    try {
      await fetchWithRefresh(`/api/admin/translations/${dealId}/regenerate-slug`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-csrf-token': getCsrfToken() },
        body: JSON.stringify({ locale }),
      });
      setOpen(false);
      onDone?.();
    } catch (err) {
      captureCaught(err, { scope: 'SlugRegenerateButton.handleConfirm', severity: 'warning' });
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger asChild>
            <Button variant="ghost" size="sm" onClick={() => setOpen(true)}>
              {t('regen_slug')}
            </Button>
          </TooltipTrigger>
          <TooltipContent>{t('regen_slug_tooltip')}</TooltipContent>
        </Tooltip>
      </TooltipProvider>

      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('regen_slug_title')}</AlertDialogTitle>
            <AlertDialogDescription>{t('regen_slug_description')}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={loading}>{t('cancel')}</AlertDialogCancel>
            <AlertDialogAction onClick={handleConfirm} disabled={loading}>
              {loading ? t('saving') : t('confirm_regen')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
