import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  TextButton,
  FormComboboxInput,
  Input,
  Button
} from "ikoncomponents";
import React, { useEffect } from "react";
import { useForm } from "react-hook-form";

export default function ResourceModal({ tasks, setResourceModal ,addMultipleRows}: { tasks: any[], setResourceModal: any, addMultipleRows: any }) {

  const form = useForm({
    defaultValues: {
      rows: 1,
      selectAll: false,
      sheets: []
    }
  });
    const { register, watch, setValue } = form;

    const selectAll = watch("selectAll");
    const sheets = watch("sheets");
    const tasksLength = tasks?.length || 0;

    // 1. Single Effect: Sync "Select All" checkbox UI when individual items change
useEffect(() => {
  const allSelected = sheets.length === tasksLength && tasksLength > 0;
  // Use { shouldValidate: true } if you have validation rules
  setValue("selectAll", allSelected); 
}, [sheets, tasksLength, setValue]);

// 2. Manual Handler: When "Select All" is clicked
const handleSelectAllChange = (e) => {
  const isChecked = e.target.checked;
  setValue("selectAll", isChecked);
  
  if (isChecked) {
    setValue("sheets", tasks.map((t) => t.taskName));
  } else {
    setValue("sheets", []);
  }
};

    const handleOnSubmit = async (data) => {
        console.log(data);
        // for(var i in data.sheets)
          await addMultipleRows(data.rows, data.sheets);
        setResourceModal(false);
    };

  const setClose = () => {
    // Logic to close the modal
    form.reset(); // Reset form values when closing
    setResourceModal(false);

  }

  return (
    <Dialog open={true} onOpenChange={() => {setClose()}}>
      <DialogContent className="w-[600px]">
        <DialogHeader>
          <DialogTitle className="text-xl font-bold">Add multiple rows</DialogTitle>
        </DialogHeader>

        <form
          onSubmit={form.handleSubmit(handleOnSubmit)}
          id="resource-form"
          className="space-y-4"
        >
          {/* Row count */}
          <div className="flex gap-4 flex-col ">
            <label className="font-medium ">
              No. of Row(s) to be Inserted
            </label> 
            {/* <Input 
              form={form}
              placeholder="No. of Row(s) to be Inserted"
              name="rows"
              type="number"
            /> */}
            <Input 
              type="number"
              {...form.register("rows")}
              className="border rounded px-2 py-1 "
            />
          </div>
          <hr className="border-gray-200" />
          {/* Select All */}
          <div className="flex items-center gap-2">
            <input type="checkbox" {...form.register("selectAll")} onChange={handleSelectAllChange}/>
            <label>Select All</label>
          </div>

          {/* Sheet list */}
          <div className="pl-6 space-y-2">
            {tasks.map((task) => (
              <div key={task.id} className="flex items-center gap-2">
                <input
                  type="checkbox"
                  value={task.taskName}
                  {...form.register("sheets")}
                />
                <label>{task.taskName}</label>
              </div>
            ))}
          </div>
        </form>

        <DialogFooter className="flex gap-2">
          <Button variant={"outline"} type="submit" form="resource-form">
            Add
          </Button>
        </DialogFooter>

      </DialogContent>
    </Dialog>
  );
}