"use client";

import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import Button from "@/components/ui/Button";
import { isNotFoundError } from "@/lib/api/errors";
import { getLearnServePaymentStatus } from "../services/learnServe";
import { cancelledCourseRefundState, publisherRefundAllKey, refundStateFromDetail, shouldReadCancelledCourseRefund } from "../cancelledCourseRefund";
import type { LearnServeOpportunityData } from "./learnServeDetailsTypes";

/**
 * «ملغاة» with the participant's own refund state under it (client answers p.2,
 * item 9), or, for the publisher, the state of their refund-all request.
 */
export default function CancelledCourseRefundNotice({
  opportunityId,
  data,
  isCreator,
}: {
  opportunityId: string;
  data: LearnServeOpportunityData | null | undefined;
  isCreator: boolean;
}) {
  const { t } = useTranslation();
  const enabled = shouldReadCancelledCourseRefund(data, isCreator);
  const fromDetail = refundStateFromDetail(data?.refund_status);
  const payment = useQuery({
    queryKey: ["learn-serve-payment-status", opportunityId],
    queryFn: () => getLearnServePaymentStatus(opportunityId),
    enabled: enabled && fromDetail === undefined,
    retry: false,
  });
  const publisherKey = publisherRefundAllKey(data, isCreator);
  if (publisherKey) {
    return (
      <div role="status" className="mx-auto mb-8 w-fit rounded-2xl border border-red-200 bg-red-50 px-6 py-4 text-center">
        <p className="font-bold text-red-700">{t("COMMON.CANCELLED")}</p>
        <p className="mt-1 text-sm text-red-700">{t(publisherKey)}</p>
      </div>
    );
  }
  if (!enabled) return null;
  // Older API only (the detail carries `refund_status` since bf3140b): a failed
  // read must not drop the participant's money line silently. A 404 means no
  // payment of theirs on this course, which is the same as nothing to show.
  if (fromDetail === undefined && payment.isError && !isNotFoundError(payment.error)) {
    return (
      <div role="alert" className="mx-auto mb-8 w-fit rounded-2xl border border-red-200 bg-red-50 px-6 py-4 text-center">
        <p className="font-bold text-red-700">{t("COMMON.CANCELLED")}</p>
        <p className="mt-1 text-sm text-red-700">{t("COMMON.REFUND_STATE_LOAD_FAILED")}</p>
        <Button size="small" className="mt-2" onClick={() => void payment.refetch()}>{t("COMMON.RETRY")}</Button>
      </div>
    );
  }
  const state = fromDetail !== undefined ? fromDetail : cancelledCourseRefundState(payment.data?.data);
  if (!state) return null;
  return (
    <div role="status" className="mx-auto mb-8 w-fit rounded-2xl border border-red-200 bg-red-50 px-6 py-4 text-center">
      <p className="font-bold text-red-700">{t("COMMON.CANCELLED")}</p>
      <p className="mt-1 text-sm text-red-700">
        {t(state === "refunded" ? "COMMON.REFUND_COMPLETED" : "COMMON.REFUND_IN_PROGRESS")}
      </p>
    </div>
  );
}
