
import DashboardLayout from "@/components/layout/dashboard-layout";
import ProductionForm from "@/components/admin/production-form";
import { verifySession } from "@/lib/auth";
import { hasEmployeePermission } from "@/lib/employee-permissions";
import { getCurrentLocale, getTranslations } from "@/lib/i18n";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { format } from "date-fns";
import { ProductionReportList } from "@/components/admin/production-report-list";
import type { Customer, ProductionItem, ProductionReport } from "@/lib/types";

export default async function ProductionPage({
  searchParams,
}: {
  searchParams?: { date?: string };
}) {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();

  if (!user || !hasEmployeePermission(user, settings, 'admin.production')) {
    return (
        <DashboardLayout>
            <div className="text-center">
                <h1 className="text-2xl font-bold">{t.Global.accessDenied}</h1>
                <p>{t.Global.noPermission}</p>
            </div>
        </DashboardLayout>
    );
  }

  const customers = (await (await import('@/lib/postgres/data-access')).pgGetCustomers({ page: 1, pageSize: 5000 })).items as Customer[];
  const materials = (await (await import('@/lib/postgres/data-access')).pgGetMaterials({ page: 1, pageSize: 5000 })).items as ProductionItem[];

  let expenses: ProductionItem[] = [];
  let reports: ProductionReport[] = [];
  
  
  const { pgGetExpenses, pgGetProductionReports } = await import('@/lib/postgres/data-access');
  const [expensesResult, reportsResult] = await Promise.all([
  pgGetExpenses({ page: 1, pageSize: 5000 }),
  pgGetProductionReports({ page: 1, pageSize: 5000 })
  ]);
  expenses = (expensesResult.items || []) as ProductionItem[];
  reports = (reportsResult.items || []) as ProductionReport[];
  
  
  // Find report for selected date or today
  const selectedDate = searchParams?.date ? new Date(searchParams.date) : new Date();
  const selectedDateString = format(selectedDate, "yyyy-MM-dd");
  const reportForDate = reports.find(r => r.id === selectedDateString);

  const tProduction = t.Production || {};
  const tGlobal = t.Global || {};
  const currencySymbol = await getCurrencySymbolAsync();

  return (
    <DashboardLayout>
      <div className="w-full max-w-4xl mx-auto space-y-8 mb-8">
        <ProductionForm 
          t={tProduction}
          tGlobal={tGlobal}
          customers={customers}
          materials={materials}
          expenses={expenses}
          user={user}
          initialData={reportForDate}
          selectedDate={selectedDate}
          locale={locale}
          currencySymbol={currencySymbol}
        />
        <ProductionReportList reports={reports} t={tProduction} locale={locale} />
      </div>
    </DashboardLayout>
  );
}
