---
import { localizedPath } from '../../i18n/utils';
import { and, eq } from 'drizzle-orm';
import { getDb, schema } from '../../db';
import { getSkillsForCvs, getLanguagesForCvs } from '../../lib/cvs/tags';
import PageLayout from '../../layouts/PageLayout.astro';
import CVFilter from './CVFilter.tsx';
import CTABand from '../sections/CTABand.astro';
import { t } from '../../i18n/ui';
import {
  cvProfessionLabels,
  cvMaritalLabels,
  cvEducationLabels,
  cvReligionLabels,
  cvServiceTypeLabels,
  cvPriceTypeLabels,
  type CvServiceTypeSlug,
} from '../../content.config';
import { getCountryLabelsMap } from '../../lib/countries';
import { whatsappLink, whatsappMessage } from '../../data/contact';
import type { Locale } from '../../data/site';

interface Props {
  locale: Locale;
  serviceType?: CvServiceTypeSlug;
}

const { locale: lang, serviceType } = Astro.props;

const ui = t(lang);
const countryLabelsMap = await getCountryLabelsMap();
const serviceTypeInfo = serviceType ? cvServiceTypeLabels[serviceType] : null;

const db = getDb();
const conditions = [eq(schema.cvs.locale, lang)];
if (serviceType) conditions.push(eq(schema.cvs.serviceType, serviceType));
const cvRows = await db.select().from(schema.cvs).where(and(...conditions));
const cvIds = cvRows.map((row) => row.id);
const skillsByCvId = await getSkillsForCvs(db, cvIds);
const languagesByCvId = await getLanguagesForCvs(db, cvIds);

const cvs = cvRows.map((row) => {
  const countryInfo = countryLabelsMap[row.country] ?? { ar: row.country, en: row.country, isoCode: '' };
  const professionInfo = cvProfessionLabels[row.profession];
  const maritalInfo = row.maritalStatus ? cvMaritalLabels[row.maritalStatus] : null;
  const educationInfo = row.educationLevel ? cvEducationLabels[row.educationLevel] : null;
  const religionInfo = row.religion ? cvReligionLabels[row.religion] : null;
  const rowServiceTypeInfo = cvServiceTypeLabels[row.serviceType];
  const priceTypeInfo = cvPriceTypeLabels[row.priceType];

  return {
    slug: row.slug,
    name: row.name,
    photo: row.photo ?? undefined,
    country: row.country,
    countryLabel: countryInfo[lang],
    countryIsoCode: countryInfo.isoCode,
    profession: row.profession,
    professionLabel: professionInfo[lang],
    age: row.age,
    experienceYears: row.experienceYears,
    experienceNote: row.experienceNote ?? undefined,
    educationLevelLabel: educationInfo ? educationInfo[lang] : undefined,
    religionLabel: religionInfo ? religionInfo[lang] : undefined,
    maritalStatusLabel: maritalInfo ? maritalInfo[lang] : undefined,
    serviceType: row.serviceType,
    serviceTypeLabel: rowServiceTypeInfo[lang],
    skills: skillsByCvId.get(row.id) ?? [],
    languages: languagesByCvId.get(row.id) ?? [],
    salary: row.salary ?? undefined,
    priceType: row.priceType,
    priceTypeLabel: priceTypeInfo[lang],
    hasVideo: row.hasVideo,
    featured: row.featured,
    bio: row.bio ?? undefined,
    waHref: whatsappLink(whatsappMessage(lang, `cv:${row.name}`)),
  };
});

const initialCv = Astro.url.searchParams.get('cv') ?? '';
const initialProfession = Astro.url.searchParams.get('profession') ?? '';
const countryParam = Astro.url.searchParams.get('country');
const initialCountry = countryParam && countryParam in countryLabelsMap ? countryParam : '';

const filterLabels = {
  countryLabels: countryLabelsMap,
  professionLabels: cvProfessionLabels as unknown as Record<string, { ar: string; en: string }>,
  viewCv: ui.viewCv,
  experience: ui.experience,
  age: ui.age,
  salary: ui.salary,
  skills: ui.skills,
  languages: ui.languages,
  filterBy: ui.filterBy,
  nationality: ui.nationality,
  profession: ui.profession,
  allNationalities: ui.allNationalities,
  allProfessionsFilter: ui.allProfessionsFilter,
  serviceType: ui.serviceType,
  noResults: ui.noResults,
  yearsExp: lang === 'ar' ? 'سنوات خبرة' : 'years experience',
  yrs: lang === 'ar' ? 'سنة' : 'yrs',
  perMonth: lang === 'ar' ? 'شهريًا' : 'per month',
  featured: lang === 'ar' ? 'مميز' : 'Featured',
  video: lang === 'ar' ? 'فيديو' : 'Video',
  bookViaWhatsApp: ui.bookViaWhatsApp,
  requestViaForm: ui.requestViaForm,
  musanedNote: ui.musanedNote,
  maritalStatus: ui.maritalStatus,
  educationLevel: ui.educationLevel,
  close: lang === 'ar' ? 'إغلاق' : 'Close',
  basicInfo: lang === 'ar' ? 'المعلومات الأساسية' : 'Basic Information',
  religion: ui.religion,
  videoAvailable: lang === 'ar' ? 'فيديو متاح' : 'Video Available',
  years: lang === 'ar' ? 'سنة' : 'years',
  showFilters: ui.showFilters,
  hideFilters: ui.hideFilters,
  clearFilters: ui.clearFilters,
  results: ui.results,
};

const pageTitle = serviceTypeInfo ? serviceTypeInfo[lang] : ui.cvs;
const pageDescription = serviceTypeInfo
  ? lang === 'ar'
    ? `تصفح السير الذاتية المتاحة ضمن ${serviceTypeInfo.ar}`
    : `Browse available CVs for ${serviceTypeInfo.en}`
  : lang === 'ar'
    ? 'تصفح السير الذاتية للعمالة المنزلية المتاحة من الفلبين وكينيا وإثيوبيا والهند'
    : 'Browse available domestic worker CVs from Philippines, Kenya, Ethiopia and India';
const heroSubtitle = serviceTypeInfo
  ? lang === 'ar'
    ? `تصفح السير الذاتية المتاحة ضمن ${serviceTypeInfo.ar} فقط`
    : `Browse CVs available for ${serviceTypeInfo.en} only`
  : lang === 'ar'
    ? 'اختر من بين مجموعة واسعة من السير الذاتية للعمالة المنزلية والسائقين ومقدمي الرعاية'
    : 'Choose from a wide selection of domestic workers, drivers and caregivers ready for recruitment';
---

<PageLayout
  locale={lang}
  title={pageTitle}
  description={pageDescription}
  breadcrumbs={[
    { label: ui.home, href: localizedPath(lang, '') },
    { label: ui.cvs, href: serviceTypeInfo ? localizedPath(lang, 'cvs') : undefined },
    ...(serviceTypeInfo ? [{ label: serviceTypeInfo[lang] }] : []),
  ]}
>
  <section class="page-hero">
    <div class="container-site">
      <h1 class="text-4xl font-bold">{pageTitle}</h1>
      <p class="mt-3 max-w-2xl text-lg text-primary-content/80">
        {heroSubtitle}
      </p>
    </div>
  </section>

  <section id="browse" class="pt-8 section-padding scroll-mt-24">
    <div class="container-site">
      <CVFilter
        client:load
        locale={lang}
        cvs={cvs}
        labels={filterLabels}
        initialProfession={initialProfession}
        initialCountry={initialCountry}
        initialCv={initialCv}
      />
    </div>
  </section>

  <CTABand locale={lang} />
</PageLayout>
