import { verifySession } from "@/lib/auth";
import { pgGetExpenses, pgGetSettings } from "@/lib/postgres/data-access";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import ListManager from "@/components/admin/list-manager";
import type { ProductionItem, RealEstateProject } from "@/lib/types";

export default async function ManageExpensesPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global ?? {};
  const tLists = t.ItemLists ?? {};
  const currencySymbol = await getCurrencySymbolAsync();

  if (!user || user.role !== 'admin') {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.accessDenied ?? "Access Denied"}</h1>
        <p>{tGlobal?.noPermission ?? "You do not have permission to view this page."}</p>
      </div>
    );
  }

  const expenses: ProductionItem[] = (await pgGetExpenses({ page: 1, pageSize: 5000 })).items as ProductionItem[];
  const settings = await pgGetSettings();
  const realEstateProjectsResult = await (await import('@/lib/actions')).handleGetRealEstateProjects();
  const realEstateProjects: RealEstateProject[] = realEstateProjectsResult && 'success' in realEstateProjectsResult && realEstateProjectsResult.success
    ? (((realEstateProjectsResult as any).items || []) as RealEstateProject[])
    : [];

  return (
    <ListManager
      items={expenses}
      title={tLists?.manageExpenses ?? "إدارة المصاريف"}
      description={tLists?.manageExpensesDescription ?? "إضافة وتعديل وحذف المصاريف المستخدمة في تقارير الإنتاج."}
      itemType="expense"
      realEstateProjects={realEstateProjects}
      t={tLists}
      tGlobal={tGlobal}
      currencySymbol={currencySymbol}
    />
  );
}
