"use client";

import { LocationContext } from "@/components/locationContext";
import { useContext, useState } from "react";
import Grouping from "./Grouping";

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

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

type Group = {
  id: number;
  jobs: number[];
};
export default function GroupCreator({ allJobs }: Props) {
  const locationContext = useContext(LocationContext);
  const [usedJobs, setUsedJobs] = useState<number[]>([]);
  const [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 };
      }),
    );
  }

  function submit() {} //TODO! submit group

  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="rounded-md bg-green-300 p-2" onClick={submit}>
          ยืนยัน
        </button>
      </div>
    </div>
  );
}
