"use client";
import { Input, Select, SelectItem } from "@nextui-org/react"
import { Company } from "prisma/generated/client"
import { useEffect } from "react"
import { SelectOption } from "@/common/types/select"
import { useResultStore } from "@/common/stores/useResultStore";
import getClientCredential from "@/common/libs/getClientCredential";
import { SHOWING_SELECTIONS } from "@/common/constants/result";

const Filter = () => {
  const { filter, updateFilter, companies, setCompanies } = useResultStore()

  const credential = getClientCredential()

  useEffect(() => {
    if (credential && !filter.company)
      updateFilter("company", credential.companyId.toString())
  }, [credential, updateFilter, filter])

  useEffect(() => {
    loadCompany().then((data: SelectOption[]) => {
      setCompanies(data)
    })
  }, [setCompanies])

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    updateFilter(name, value)
  }

  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const { name, value } = e.target
    updateFilter(name, value)
  }

  return (
    <div className="flex flex-wrap md:flex-nowrap gap-3">
      <div className="w-full md:w-10/12">
        <Input
          type="text"
          label="Pencarian"
          placeholder="Cari nama, sku, barcode, atau rak"
          name="search"
          onChange={handleInputChange}
          value={filter.search}
        />
      </div>
      <div className="flex-1 md:w-2/12">
        <Select
          label="Perusahaan"
          selectedKeys={filter.company}
          name="company"
          onChange={handleSelectChange}
          isLoading={!filter.company}
        >
          {companies.map((company) => (
            <SelectItem key={company.value}>{company.label}</SelectItem>
          ))}
        </Select>
      </div>
      <div className="flex-1 md:w-2/12">
        <Select
          label="Tampilkan"
          selectedKeys={filter.show}
          name="show"
          onChange={handleSelectChange}
        >
          {SHOWING_SELECTIONS.map((selection) => (
            <SelectItem key={selection.key}>{selection.label}</SelectItem>
          ))}
        </Select>
      </div>
    </div>
  )
}

const loadCompany = async () => {
  const response = await fetch(`/api/company`)
  const data: Company[] = await response.json() || []

  return data.map((company) => ({
    value: company.id,
    label: company.name
  }))
}

export default Filter