import { useEffect, useState } from "react";
import { JobCategory } from "./GroupCreator";

type Props = {
  availableJobs: JobCategory[];
  selectJob: (id: number) => void;
  removeJob: (id: number) => void;
  updateGroup: (id: number[]) => void;
};

export default function Grouping({
  availableJobs,
  selectJob,
  removeJob,
  updateGroup,
}: Props) {
  let [selectedJob, setSelectedJob] = useState<JobCategory[]>([]);
  function addJob(id: string) {
    let _id = parseInt(id);
    let job = availableJobs.find((j) => j.id == _id);
    if (job == undefined) return;
    setSelectedJob((old) => [...old, job]);
    selectJob(_id);
  }
  function removeJobFromGroup(id: number) {
    setSelectedJob((old) => old.filter((j) => j.id != id));
    removeJob(id);
  }
  useEffect(() => {
    updateGroup(selectedJob.map((j) => j.id));
  }, [selectedJob, updateGroup]);
  return (
    <div className="m-2 flex w-full flex-col gap-2 rounded-md border border-black p-2 shadow-md">
      {selectedJob.map((j) => (
        <div className="flex justify-between gap-2 p-2" key={j.id}>
          <p>{j.name}</p>
          <button
            onClick={() => removeJobFromGroup(j.id)}
            className="text-red-400"
          >
            นำออก
          </button>
        </div>
      ))}
      {selectedJob.length < 5 && (
        <select onChange={(e) => addJob(e.currentTarget.value)}>
          <option value={undefined} hidden>
            None
          </option>
          {availableJobs.map((j) => (
            <option value={j.id} key={j.id}>
              {j.name}
            </option>
          ))}
        </select>
      )}
    </div>
  );
}
