"use client";

import { useCallback, useEffect, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { ApiError, apiGet, apiPost } from "@/lib/api";
import { isHoldingAdmin } from "@/lib/permissions";

type UpdatePackageRow = {
  code: string;
  title: string;
  description: string;
  depends_on: string[];
  handlers: string[];
  status: "pending" | "applied" | "blocked";
  missing_dependencies: string[];
  can_apply: boolean;
  applied_at: string | null;
  summary: Record<string, unknown> | null;
};

const statusLabel: Record<UpdatePackageRow["status"], string> = {
  pending: "اعمال‌نشده",
  applied: "اعمال‌شده",
  blocked: "منتظر وابستگی",
};

export default function SchoolUpdatesPage() {
  const allowed = isHoldingAdmin();
  const [rows, setRows] = useState<UpdatePackageRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [applying, setApplying] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setRows(await apiGet<UpdatePackageRow[]>("/system-updates"));
      setError(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری به‌روزرسانی‌ها");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (allowed) {
      void load();
    } else {
      setLoading(false);
    }
  }, [allowed, load]);

  const apply = async (code: string) => {
    setApplying(code);
    setError(null);
    setMessage(null);
    try {
      await apiPost(`/system-updates/${encodeURIComponent(code)}/apply`, {});
      setMessage("به‌روزرسانی اعمال شد.");
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "اعمال به‌روزرسانی ناموفق بود.");
    } finally {
      setApplying(null);
    }
  };

  return (
    <AppShell title="به‌روزرسانی‌ها" subtitle="محتوای مصوب را پس از بررسی توضیح، روی این هلدینگ اعمال کنید">
      {error ? <Alert tone="error">{error}</Alert> : null}
      {message ? <Alert tone="success">{message}</Alert> : null}
      {!allowed ? (
        <Alert tone="warning">فقط مدیر هلدینگ می‌تواند به‌روزرسانی‌ها را ببیند و اعمال کند.</Alert>
      ) : loading ? (
        <p className="text-sm text-[var(--muted)]">در حال بارگذاری…</p>
      ) : rows.length === 0 ? (
        <p className="text-sm text-[var(--muted)]">بسته‌ای روی این سرور نصب نشده است.</p>
      ) : (
        <div className="space-y-3">
          {rows.map((row) => (
            <article
              key={row.code}
              className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card"
            >
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <h2 className="text-base font-semibold">{row.title}</h2>
                  <p className="mt-1 text-xs text-[var(--muted)]">{row.code}</p>
                </div>
                <span className="rounded-full bg-[var(--muted-bg,theme(colors.slate.100))] px-3 py-1 text-xs">
                  {statusLabel[row.status]}
                </span>
              </div>
              {row.description ? (
                <p className="mt-3 whitespace-pre-wrap text-sm leading-6 text-[var(--foreground)]">
                  {row.description}
                </p>
              ) : null}
              {row.missing_dependencies.length > 0 ? (
                <p className="mt-2 text-sm text-amber-800">
                  ابتدا این بسته‌ها را اعمال کنید: {row.missing_dependencies.join("، ")}
                </p>
              ) : null}
              {row.applied_at ? (
                <p className="mt-2 text-xs text-[var(--muted)]">آخرین اعمال: {row.applied_at}</p>
              ) : null}
              <div className="mt-4">
                <Button
                  disabled={!row.can_apply || applying === row.code}
                  onClick={() => void apply(row.code)}
                >
                  {row.status === "applied" ? "اعمال مجدد" : "اعمال به‌روزرسانی"}
                </Button>
              </div>
            </article>
          ))}
        </div>
      )}
    </AppShell>
  );
}
