"use client";

import * as React from "react";
import { Trash2Icon } from "lucide-react";

import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { Typography } from "@/components/ui/typography";
import { useDeletePackage } from "@/hooks/catalog/useDeletePackage";
import { useTranslation } from "@/hooks/useTranslation";
import type { WashPackage } from "@/types/catalog";

interface PackageDeleteDialogProps {
  /** The package to delete, or null when no dialog should be shown */
  target: WashPackage | null;
  onClose: () => void;
}

/**
 * Confirms removing a package from the catalog.
 *
 * The backend soft-deletes: the row survives with `isDeleted: true` and
 * providers keep their `ProviderService` rows, but the package disappears from
 * every listing — including the customer app. The copy says that rather than
 * implying the data is gone.
 *
 * Deliberately NOT in `requireReason` mode: `DELETE /catalog/admin/packages/:id`
 * takes no body, and the backend rejects unknown keys — a reason collected here
 * could not be persisted.
 */
export function PackageDeleteDialog({
  target,
  onClose,
}: PackageDeleteDialogProps) {
  const { t } = useTranslation();
  const deletePackage = useDeletePackage();

  // Retain the last target so the dialog keeps its copy while it animates out
  // (`target` is nulled the moment the dialog starts closing). React's "adjust
  // state during render" pattern — a ref would be read during render, which the
  // compiler rules correctly reject.
  const [lastTarget, setLastTarget] = React.useState<WashPackage | null>(null);
  if (target && target !== lastTarget) setLastTarget(target);

  const shown = target ?? lastTarget;
  if (!shown) return null;

  return (
    <ConfirmDialog
      open={!!target}
      onOpenChange={(next) => {
        if (!next) onClose();
      }}
      icon={<Trash2Icon />}
      destructive
      title={t("catalog.confirm.deleteTitle")}
      description={
        <span className="flex flex-col gap-2">
          <span>
            {t("catalog.confirm.deleteDescription", { name: shown.name })}
          </span>
          <Typography as="span" variant="caption" color="secondary">
            {t("catalog.confirm.deleteNote")}
          </Typography>
        </span>
      }
      confirmLabel={t("catalog.actions.delete")}
      // Rejecting keeps the dialog open; the hook's onError toast explains why.
      onConfirm={() => deletePackage.mutateAsync(shown.id)}
    />
  );
}
