"use client";

// Read-only view of GET /timer/options — the option sets the app uses to build
// the meditation timer (durations, intervals, default bells, etc.). The exact
// shape is backend-defined, so we render it generically: primitive values as a
// definition list, arrays of objects as small tables.

import { useItem } from "@/lib/useResource";
import { Button, Card, PageHeader, Spinner, Badge, EmptyState } from "@/components/ui";
import { toFa } from "@/lib/utils";

function Primitive({ value }: { value: unknown }) {
  if (typeof value === "boolean") {
    return <Badge tone={value ? "success" : "neutral"}>{value ? "بله" : "خیر"}</Badge>;
  }
  if (value === null || value === undefined) return <span className="text-muted">—</span>;
  return <span>{toFa(String(value))}</span>;
}

function ArrayBlock({ items }: { items: unknown[] }) {
  if (!items.length) return <EmptyState message="موردی وجود ندارد." />;

  // Array of objects -> table of their union of keys.
  if (items.every((it) => it && typeof it === "object" && !Array.isArray(it))) {
    const keys = Array.from(
      new Set(items.flatMap((it) => Object.keys(it as object))),
    );
    return (
      <div className="overflow-x-auto rounded-xl border border-border">
        <table className="w-full text-right text-sm">
          <thead>
            <tr className="border-b border-border bg-surface-muted text-muted">
              {keys.map((k) => (
                <th key={k} className="px-3 py-2 font-medium">
                  {k}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {items.map((it, i) => (
              <tr key={i} className="border-b border-border last:border-0">
                {keys.map((k) => (
                  <td key={k} className="px-3 py-2">
                    <Primitive value={(it as Record<string, unknown>)[k]} />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  // Array of primitives -> chips.
  return (
    <div className="flex flex-wrap gap-2">
      {items.map((it, i) => (
        <Badge key={i}>{toFa(String(it))}</Badge>
      ))}
    </div>
  );
}

export default function TimerOptionsPage() {
  const { data, loading, error, reload } = useItem<Record<string, unknown>>(
    "/timer/options",
  );

  return (
    <div>
      <PageHeader
        title="گزینه‌های تایمر"
        subtitle="مقادیر پیش‌فرض و فهرست‌هایی که اپلیکیشن برای ساخت تایمر مدیتیشن استفاده می‌کند."
      />

      {loading ? (
        <div className="flex justify-center py-16">
          <Spinner className="h-8 w-8" />
        </div>
      ) : error ? (
        <EmptyState
          icon="⚠️"
          title="خطا در دریافت اطلاعات"
          message={error}
          action={
            <Button variant="secondary" onClick={reload}>
              تلاش دوباره
            </Button>
          }
        />
      ) : !data || typeof data !== "object" || !Object.keys(data).length ? (
        <EmptyState
          title="گزینه‌ای موجود نیست"
          message="هیچ گزینه‌ای از سرور دریافت نشد."
        />
      ) : (
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
          {Object.entries(data).map(([key, value]) => (
            <Card key={key}>
              <h2 className="mb-3 font-bold text-foreground">{key}</h2>
              {Array.isArray(value) ? (
                <ArrayBlock items={value} />
              ) : value && typeof value === "object" ? (
                <dl className="flex flex-col gap-2 text-sm">
                  {Object.entries(value as Record<string, unknown>).map(
                    ([k, v]) => (
                      <div key={k} className="flex justify-between gap-3 border-b border-border pb-1.5 last:border-0">
                        <dt className="text-muted">{k}</dt>
                        <dd>
                          <Primitive value={v} />
                        </dd>
                      </div>
                    ),
                  )}
                </dl>
              ) : (
                <Primitive value={value} />
              )}
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
