import { Globe } from "lucide-react";

import { ListPageCard } from "@/app/dashboard/_components";
import { ErrorBanner } from "@/components/shared/error-banner";
import {
  masterFiltersToBackend,
  parseMasterListQuery,
} from "@/lib/server/parse-master-list-search-params";

import { CountriesTable } from "./_components/countries-table";
import { CountriesGoogleTranslate } from "./_components/countries-google-translate";
import { CountriesHeaderActions } from "./_components/list-header-actions";
import {
  parseCountryBulkModeFromSearchParams,
  parseCountryFiltersFromSearchParams,
} from "./_components/schema";
import { fetchBackendCountries } from "./_lib/countries-server-api";

type CountriesPageProps = {
  searchParams: Promise<Record<string, string | undefined>>;
};

export default async function CountriesPage({ searchParams }: CountriesPageProps) {
  const query = await searchParams;
  const { page, pageSize, filters } = parseMasterListQuery(
    query,
    parseCountryFiltersFromSearchParams,
  );
  const { bulkUpdate, lan } = parseCountryBulkModeFromSearchParams(query);
  const { rows, totalCount, pageCount, errorMessage } = await fetchBackendCountries({
    page,
    pageSize,
    filters: {
      ...masterFiltersToBackend(filters),
      ...(bulkUpdate && lan
        ? {
            bulk_update: "1",
            lan,
          }
        : {}),
    },
  });

  return (
    <ListPageCard
      icon={Globe}
      title="Countries"
      breadcrumb={[{ label: "Master" }, { label: "Countries" }]}
      description={
        bulkUpdate && lan
          ? `Bulk ${lan === "ar" ? "Arabic" : "Dutch"} name translations — same filters and pagination as the list.`
          : "Manage countries, ISO codes, shipping charges, and regional settings."
      }
      actions={<CountriesHeaderActions data={rows} />}
    >
      <ErrorBanner message={errorMessage} className="mb-4" />
      <div className="mb-3">
        <CountriesGoogleTranslate enabled={bulkUpdate} />
      </div>
      <CountriesTable
        data={rows}
        initialFilters={filters}
        pagination={{ page, pageSize, totalCount, pageCount }}
        bulkLan={lan}
      />
    </ListPageCard>
  );
}
