import React, { useState, useEffect } from "react";
import Avatar from "../common/Avatar";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

export const roleSchema = z.object({
  jobRole: z.string().min(1, "Job Role is required"),
  isChecked: z.literal(true, {
    errorMap: () => ({ message: "You must check the box first" }),
  }),
});

const AssignEmployeeTable = ({
  employee,
  jobRoles,
  isChecked,
  onRoleChange,
  onCheckboxChange,
}) => {
  const [currentJobRole, setCurrentJobRole] = useState(
    employee.jobRoleId?.toString() || ""
  );
  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    trigger,
    getValues,
  } = useForm({
    resolver: zodResolver(roleSchema),
    defaultValues: {
      jobRole: currentJobRole,
      isChecked: isChecked || false,
    },
  });

  useEffect(() => {
    const jobRoleStr = employee.jobRoleId?.toString() || "";
    setCurrentJobRole(jobRoleStr);
    setValue("jobRole", jobRoleStr);
    setValue("isChecked", isChecked);
  }, [employee.jobRoleId, isChecked, setValue]);

  const onSubmit = (data) => {
    setCurrentJobRole(data.jobRole);
    onRoleChange(employee.id, data.jobRole);
  };

  const handleRoleSelect = async (e) => {
    const value = e.target.value;
    setValue("jobRole", value);
    const isValid = await trigger(); // Validate the form
    if (isValid) {
      const values = getValues();
      onRoleChange(employee.id, values.jobRole);
    }
  };

  const handleCheckboxChange = async () => {
    if (!employee.isActive) {
      setValue("isChecked", !isChecked);
      const isValid = await trigger(); // Validate after setting value
      if (isValid) {
        const values = getValues();
        onCheckboxChange(employee.id);
        onRoleChange(employee.id, values.jobRole); // Update role if it changed
      }
    }
  };

  return (
    <tr className="odd py-0">
      <td className="sorting_1 py-0" colSpan={2}>
        <div className="d-flex justify-content-start align-items-center user-name py-0">
          <Avatar firstName={employee.firstName} lastName={employee.lastName} />
          <div className="d-flex flex-column">
            <span className="text-heading text-truncate cursor-pointer fw-normal">
              {employee.firstName} {employee.middleName} {employee.lastName}
            </span>
          </div>
        </div>
      </td>

      <td className="text-end justify-content-end d-none d-sm-table-cell">
        <div className="d-flex justify-content-end">
          <select
            className={`form-select form-select-sm w-auto border-none rounded-0 py-1 px-auto ${
              errors.jobRole ? "is-invalid" : ""
            }`}
            {...register("jobRole")}
            onChange={handleRoleSelect}
          >
            {/* <option value="">Select a Job Role</option> */}
            {jobRoles?.map((role) => (
              <option key={role.id} value={role.id}>
                {role.name}
              </option>
            ))}
          </select>
        </div>
        {errors.jobRole && (
          <div className="invalid-feedback">{errors.jobRole.message}</div>
        )}
        {errors.isChecked && (
          <div className="invalid-feedback d-block">
            {errors.isChecked.message}
          </div>
        )}
      </td>

      <td className="text-start d-none d-sm-table-cell">
        <input
          className="form-check-input ms-3"
          type="checkbox"
          checked={isChecked}
          disabled={employee.isActive}
          onChange={handleCheckboxChange}
        />
      </td>
    </tr>
  );
};

export default AssignEmployeeTable;
