"use client"

import { useReducer } from "react"
import { useIntl } from "react-intl"

import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"

import JobylonCard from "../JobylonCard"
import Filter from "./Filter"
import { init, reducer } from "./reducer"

import styles from "./jobList.module.css"

import type { Key } from "react-aria-components"

import { ActionType } from "@/types/components/blocks/jobylonFeed"
import type { JobylonFilterKey } from "@/types/enums/jobylonFeed"
import type { JobylonItem } from "@/types/trpc/routers/jobylon"

interface JobListProps {
  allJobs: JobylonItem[]
}

export default function JobList({ allJobs }: JobListProps) {
  const intl = useIntl()
  const [state, dispatch] = useReducer(reducer, { allJobs }, init)

  function handleFilterChange(filter: JobylonFilterKey, value: Key) {
    const payload = { filter, value }
    dispatch({ type: ActionType.UPDATE_FILTER, payload })
  }

  const countryFilters = [
    {
      label: intl.formatMessage({
        defaultMessage: "All countries",
      }),
      value: "",
    },
    ...state.countryFilters,
  ]
  const cityFilters = [
    {
      label: intl.formatMessage({
        defaultMessage: "All locations",
      }),
      value: "",
    },
    ...state.cityFilters,
  ]
  const departmentFilters = [
    {
      label: intl.formatMessage({
        defaultMessage: "All hotels and offices",
      }),
      value: "",
    },
    ...state.departmentFilters,
  ]
  const categoryFilters = [
    {
      label: intl.formatMessage({
        defaultMessage: "All categories",
      }),
      value: "",
    },
    ...state.categoryFilters,
  ]

  return (
    <div className={styles.jobList}>
      <Filter
        onFilterChange={handleFilterChange}
        countryFilters={countryFilters}
        cityFilters={cityFilters}
        departmentFilters={departmentFilters}
        categoryFilters={categoryFilters}
      />
      <Subtitle type="two">
        {intl.formatMessage(
          {
            defaultMessage: "{count, plural, one {# Result} other {# Results}}",
          },
          { count: state.jobs.length }
        )}
      </Subtitle>
      <ul className={styles.list}>
        {state.jobs.map((job) => (
          <li key={job.id}>
            <JobylonCard job={job} />
          </li>
        ))}
      </ul>
    </div>
  )
}
