import { cookies } from 'next/headers';
import { BillManagementClient } from '@/components/accounting/BillManagement/BillManagementClient';
import type { BillRecord, BillApiData } from '@/components/accounting/BillManagement/types';
import { transformApiToFrontend } from '@/components/accounting/BillManagement/types';

interface BillsPageProps {
  searchParams: Promise<{
    vendorId?: string;
    type?: string;
    page?: string;
  }>;
}

async function getApiHeaders(): Promise<HeadersInit> {
  const cookieStore = await cookies();
  const token = cookieStore.get('access_token')?.value;

  return {
    'Accept': 'application/json',
    'Authorization': token ? `Bearer ${token}` : '',
    'X-API-KEY': process.env.API_KEY || '',
  };
}

async function getBills(params: {
  billType?: string;
  page?: number;
}): Promise<{
  data: BillRecord[];
  pagination: {
    currentPage: number;
    lastPage: number;
    perPage: number;
    total: number;
  };
}> {
  try {
    const headers = await getApiHeaders();
    const queryParams = new URLSearchParams();

    if (params.billType && params.billType !== 'all') {
      queryParams.append('bill_type', params.billType);
    }
    if (params.page) {
      queryParams.append('page', String(params.page));
    }
    queryParams.append('per_page', '20');

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bills?${queryParams.toString()}`,
      { method: 'GET', headers, cache: 'no-store' }
    );

    if (!response.ok) {
      console.error('[BillsPage] Fetch error:', response.status);
      return {
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
      };
    }

    const result = await response.json();

    if (!result.success) {
      return {
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
      };
    }

    const paginatedData = result.data as {
      data: BillApiData[];
      current_page: number;
      last_page: number;
      per_page: number;
      total: number;
    };

    return {
      data: paginatedData.data.map(transformApiToFrontend),
      pagination: {
        currentPage: paginatedData.current_page,
        lastPage: paginatedData.last_page,
        perPage: paginatedData.per_page,
        total: paginatedData.total,
      },
    };
  } catch (error) {
    console.error('[BillsPage] Fetch error:', error);
    return {
      data: [],
      pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
    };
  }
}

export default async function BillsPage({ searchParams }: BillsPageProps) {
  const params = await searchParams;
  const vendorId = params.vendorId;
  const billType = params.type || 'received';
  const page = params.page ? parseInt(params.page) : 1;

  const { data, pagination } = await getBills({ billType, page });

  return (
    <BillManagementClient
      initialData={data}
      initialPagination={pagination}
      initialVendorId={vendorId}
      initialBillType={billType}
    />
  );
}
