"use client";

import { LoadingState, ErrorState, EmptyState } from "@/components/ds";
import {
  ExperienceApiError,
  formatExperienceError,
} from "@/modules/experience/services/experience-api";
import { PermissionDeniedState } from "@/src/shared/ui";

export function ExperiencePageLoader({ label = "در حال بارگذاری…" }: { label?: string }) {
  return <LoadingState label={label} />;
}

export function ExperiencePageError({
  error,
  onRetry,
}: {
  error: unknown;
  onRetry?: () => void;
}) {
  if (error instanceof ExperienceApiError && error.status === 403) {
    return (
      <PermissionDeniedState
        message={formatExperienceError(error, "مجوز لازم برای این عملیات وجود ندارد.")}
      />
    );
  }
  return (
    <ErrorState
      message={formatExperienceError(error, "خطا در دریافت داده‌ها")}
      onRetry={onRetry}
    />
  );
}

export function ExperienceEmptyState({
  title = "موردی یافت نشد",
  description = "هنوز داده‌ای ثبت نشده است.",
  action,
}: {
  title?: string;
  description?: string;
  action?: React.ReactNode;
}) {
  return <EmptyState title={title} description={description} action={action} />;
}

export function exportToCsv(title: string, rows: Record<string, unknown>[], columns: string[]) {
  if (rows.length === 0) return;
  const header = columns.join(",");
  const body = rows
    .map((r) => columns.map((c) => JSON.stringify(r[c] ?? "")).join(","))
    .join("\n");
  const blob = new Blob(["\uFEFF" + header + "\n" + body], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${title}-export.csv`;
  a.click();
  URL.revokeObjectURL(url);
}
