"use client";

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

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

interface ServiceOptOutDialogProps {
  /** The package to stop offering, or null when no dialog should be shown */
  target: ProviderPackage | null;
  onClose: () => void;
}

/**
 * Confirms that this provider stops offering a catalog package.
 *
 * Opting out HARD-deletes the `ProviderService` row backend-side, so the price
 * is gone rather than remembered — re-enabling later means entering a new one.
 * The copy warns about that, since the switch otherwise looks reversible.
 *
 * It can also fail outright: the row is referenced by `BookingItem` without a
 * cascade, so a package with past bookings answers 400. `mutateAsync` keeps the
 * dialog open in that case and the hook's toast explains why.
 */
export function ServiceOptOutDialog({
  target,
  onClose,
}: ServiceOptOutDialogProps) {
  const { t } = useTranslation();
  const toggleService = useToggleProviderPackage();

  // Retain the last target so the dialog keeps its copy while it animates out.
  // 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<ProviderPackage | 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={<BanIcon />}
      destructive
      title={t("catalog.myServices.confirm.optOutTitle")}
      description={
        <span className="flex flex-col gap-2">
          <span>
            {t("catalog.myServices.confirm.optOutDescription", {
              name: shown.name,
            })}
          </span>
          <Typography as="span" variant="caption" color="secondary">
            {t("catalog.myServices.confirm.optOutNote")}
          </Typography>
        </span>
      }
      confirmLabel={t("catalog.myServices.actions.stopOffering")}
      onConfirm={async () => {
        await toggleService.mutateAsync({ packageId: shown.id, optIn: false });
      }}
    />
  );
}
