import { redirect } from 'next/navigation';
import { verifySession } from '@/lib/auth';

import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import CampaignEditorPage from '@/components/admin/campaign-editor-page';
import type { Campaign, ChartOfAccount, CustomerCategory, ProductionItem } from '@/lib/types';

type EditCampaignPageProps = {
  params: Promise<{ id: string }>;
};

export default async function EditCampaignPage({ params }: EditCampaignPageProps) {
  const session = await verifySession();
  if (!session?.user || session.user.role !== 'admin') {
    redirect('/login');
  }

  const { id } = await params;
  const campaignId = String(id || '').trim();
  if (!campaignId) {
    redirect('/admin/data/campaigns');
  }

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tCampaigns = (t as any).Campaigns ?? {};
  const tGlobal = (t as any).Global ?? {};

  let campaigns: Campaign[] = [];
  let materials: ProductionItem[] = [];
  let customerCategories: CustomerCategory[] = [];
  let accounts: ChartOfAccount[] = [];

  
  const dataAccess = await import('@/lib/postgres/data-access');
  const [campaignRows, materialRows, customerCategoryRows, accountRows] = await Promise.all([
  dataAccess.pgGetCampaigns(),
  dataAccess.pgGetMaterials({ page: 1, pageSize: 10000 }),
  dataAccess.pgGetCustomerCategories({ page: 1, pageSize: 5000 }),
  dataAccess.pgGetChartOfAccounts({ page: 1, pageSize: 10000 }),
  ]);

  campaigns = (campaignRows || []) as Campaign[];
  materials = (materialRows.items || []) as ProductionItem[];
  customerCategories = (customerCategoryRows.items || []) as CustomerCategory[];
  accounts = (accountRows.items || []) as ChartOfAccount[];
  

  const campaign = (campaigns || []).find((entry) => String(entry.id || '').trim() === campaignId) || null;
  if (!campaign) {
    redirect('/admin/data/campaigns');
  }

  const customerCategoryOptions = Array.from(
    new Map(
      (customerCategories || [])
        .map((category) => ({
          id: String(category?.id || '').trim(),
          name: String(category?.name || category?.id || '').trim(),
        }))
        .filter((option) => option.id.length > 0)
        .map((option) => [option.id, option]),
    ).values(),
  );

  return (
    <div className="container mx-auto py-6 px-4 max-w-7xl">
      <CampaignEditorPage
        mode="edit"
        campaign={campaign}
        materials={materials}
        accounts={accounts}
        customerCategoryOptions={customerCategoryOptions}
        t={tCampaigns}
        tGlobal={tGlobal}
      />
    </div>
  );
}
