"use client";

import { LocationContext } from "@/components/locationContenxt";
import { useContext, useEffect, useState } from "react";
import Grouping from "./Grouping";
import { unique } from "drizzle-orm/mysql-core";

type Props = {
  allJobs: JobCategory[];
};

export type JobCategory = {
  id: number;
  name: string;
};

type Group = {
  id: number;
  jobs: number[];
};
export default function GroupCreator({ allJobs }: Props) {
  let locationContext = useContext(LocationContext);
  let [usedJobs, setUsedJobs] = useState<number[]>([]);
  let [groups, setGroup] = useState<Group[]>(
    [...Array(4).keys()].map((i) => ({ id: i + 1, jobs: [] }))
  );
  function useJob(id: number) {
    setUsedJobs((u) => [...u, id]);
  }

  function freeJob(id: number) {
    setUsedJobs((u) => u.filter((j) => j != id));
  }

  function updateGroup(id: number, jobs: number[]) {
    setGroup((groups) =>
      groups.map((g) => {
        if (g.id != id) return g;
        else return { id, jobs };
      })
    );
  }

  useEffect(() => {
    console.log(groups);
  }, [groups]);

  if (
    locationContext?.zone[0] == undefined ||
    locationContext?.province[0] == undefined
  ) {
    return undefined;
  }
  return (
    <div>
      {groups.map((g) => (
        <div className="flex flex-col items-center" key={g.id}>
          <p>สายที่: {g.id}</p>
          <Grouping
            availableJobs={allJobs.filter((j) => !usedJobs.includes(j.id))}
            selectJob={useJob}
            removeJob={freeJob}
            updateGroup={(ids) => updateGroup(g.id, ids)}
          />
        </div>
      ))}

      <div className="flex justify-center">
        <button className="bg-green-300 rounded-md p-2">ยืนยัน</button>
      </div>
    </div>
  );
}
