"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { AdminUser, ApiError, apiGet, apiPut, getStoredUser } from "@/lib/api";
import { isHoldingAdmin } from "@/lib/permissions";

export default function ForeignNationalsSettingsPage() {
  const user = useMemo(() => getStoredUser<AdminUser>(), []);
  const canManage = isHoldingAdmin();

  const [studentForeignNationalsEnabled, setStudentForeignNationalsEnabled] = useState(false);
  const [staffForeignNationalsEnabled, setStaffForeignNationalsEnabled] = useState(false);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!user) return;
    setLoading(true);
    setError(null);
    try {
      const [student, staff] = await Promise.all([
        apiGet<{ value: boolean }>(
          `/settings/resolve?key=students.foreign_nationals_enabled&organization_id=${user.organization_id}`,
        ).catch(() => ({ value: false })),
        apiGet<{ value: boolean }>(
          `/settings/resolve?key=staff.foreign_nationals_enabled&organization_id=${user.organization_id}`,
        ).catch(() => ({ value: false })),
      ]);
      setStudentForeignNationalsEnabled(Boolean(student.value));
      setStaffForeignNationalsEnabled(Boolean(staff.value));
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری");
    } finally {
      setLoading(false);
    }
  }, [user]);

  useEffect(() => {
    void load();
  }, [load]);

  const save = async () => {
    if (!user || !canManage) return;
    setSaving(true);
    setError(null);
    setMessage(null);
    try {
      const orgId = user.organization_id;
      await Promise.all([
        apiPut(`/organizations/${orgId}/settings`, {
          key: "students.foreign_nationals_enabled",
          value: studentForeignNationalsEnabled,
          module: "sis",
        }),
        apiPut(`/organizations/${orgId}/settings`, {
          key: "staff.foreign_nationals_enabled",
          value: staffForeignNationalsEnabled,
          module: "iam",
        }),
      ]);
      setMessage("تنظیمات اتباع ذخیره شد.");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ذخیره");
    } finally {
      setSaving(false);
    }
  };

  return (
    <AppShell title="امکان ثبت نام اتباع" subtitle="ثبت اتباع دانش‌آموز و کارمند در پنل">
      {error ? <Alert tone="error">{error}</Alert> : null}
      {message ? <Alert tone="success">{message}</Alert> : null}

      {!user ? (
        <Alert tone="warning">برای مشاهده تنظیمات وارد شوید.</Alert>
      ) : !canManage ? (
        <Alert tone="warning">فقط مدیرکل می‌تواند این تنظیمات را تغییر دهد.</Alert>
      ) : loading ? (
        <PageContentSkeleton rows={3} />
      ) : (
        <div className="max-w-xl space-y-4 rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
          <p className="text-sm text-[var(--muted)]">
            این موارد برای همه مدارس سازمان اعمال می‌شود. ثبت اتباع در پیش‌ثبت‌نام از صفحه تنظیمات
            پیش‌ثبت‌نام مدیریت می‌شود.
          </p>

          <label className="flex items-start gap-3 rounded-xl border border-[var(--border)] p-3 text-sm">
            <input
              type="checkbox"
              className="mt-1"
              checked={studentForeignNationalsEnabled}
              onChange={(e) => setStudentForeignNationalsEnabled(e.target.checked)}
            />
            <span>
              <span className="font-semibold">دانش‌آموز اتباع</span>
              <span className="mt-1 block text-xs leading-6 text-[var(--muted)]">
                با فعال بودن، چک‌باکس «دانش‌آموز اتباع» در ثبت دانش‌آموز پنل نمایش داده می‌شود.
              </span>
            </span>
          </label>

          <label className="flex items-start gap-3 rounded-xl border border-[var(--border)] p-3 text-sm">
            <input
              type="checkbox"
              className="mt-1"
              checked={staffForeignNationalsEnabled}
              onChange={(e) => setStaffForeignNationalsEnabled(e.target.checked)}
            />
            <span>
              <span className="font-semibold">کارمند اتباع</span>
              <span className="mt-1 block text-xs leading-6 text-[var(--muted)]">
                با فعال بودن، چک‌باکس «کارمند اتباع» در ثبت کارمند پنل نمایش داده می‌شود.
              </span>
            </span>
          </label>

          <Button loading={saving} onClick={() => void save()}>
            ذخیره تنظیمات
          </Button>
        </div>
      )}
    </AppShell>
  );
}
