import React, { useEffect, useState } from "react";
import { useFeatures } from "../../hooks/useMasterRole";

import { useForm } from 'react-hook-form';
import { set, z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { MasterRespository } from "../../repositories/MastersRepository";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import showToast from "../../services/toastService";






const schema = z.object({
  role: z.string().min(1, { message: "Role is required" }),
  description: z.string().min(1, { message: "Description is required" })
  .max(255, { message: "Description cannot exceed 255 characters" }),

  selectedPermissions: z
    .array(z.string())
    .min(1, { message: "Please select at least one permission" }),
});


const CreateRole = ({modalType,onClose}) => {
 
 const[isLoading,setIsLoading] = useState(false)

 const {masterFeatures} = useFeatures()

 const {
  register,
  handleSubmit,
  formState: { errors },
  
} = useForm({
  resolver: zodResolver(schema),
  defaultValues: {
    role: "",
    description: "",
    selectedPermissions: [],
  },
});

const onSubmit = (values) => {
  setIsLoading(true)
  const result = {
    
    role: values.role,
    description: values.description,
    featuresPermission: values.selectedPermissions.map((id) => ({
      id,
      isEnabled: true,
    })),
  };

  MasterRespository.createRole(result).then((resp)=>{
    console.log(resp)
    setIsLoading(false)

    const cachedData = getCachedData( "Role" ); 
    console.log(cachedData)
    const updatedData = [...cachedData, resp]; 
    
    cacheData("Role", updatedData); 
    showToast("Role Added successfully.", "success");
    onClose()
  } ).catch( ( err ) =>
  {
    
    showToast(err?.response?.data?.message, "error");
    setIsLoading(false)
  })
 
 
};

 
  return (
  
    <form  className="row g-2" onSubmit={handleSubmit(onSubmit)}>
      
        <div className="col-12 col-md-12">
          <label className="form-label">Role</label>
          <input type="text" 
           {...register("role")} 
             className={`form-control ${errors.role ? 'is-invalids' : ''}`}
          />
          {errors.role && <p className="text-danger">{errors.role.message}</p>}
        </div>

        
        <div className="col-12 col-md-12">
          <label className="form-label" htmlFor="description">Description</label>
          <textarea
            rows="3"
            {...register("description")}
            className={`form-control ${errors.description ? 'is-invalids' : ''}`}
          ></textarea>
          {errors.description && (
            <p className="text-danger">{errors.description.message}</p>
          )}
        </div>

       
        <div className="col-12 col-md-12  border">

          
  {masterFeatures.map((feature) => (
    <React.Fragment key={feature.id}>
    <div className="row my-1" key={feature.id} style={{ marginLeft: "0px" }}>
      
     
      <div className="col-12 col-md-3 d-flex text-start align-items-start" style={{ wordWrap: 'break-word' }}>
        <span className="fs">{feature.name}</span>
      </div>
    
      <div className="col-12 col-md-1"></div>

   
      <div className="col-12 col-md-8 d-flex justify-content-start align-items-center flex-wrap">
        {feature.featurePermissions.map((perm) => (
          <div className="d-flex me-3 mb-2" key={perm.id}>
            <label className="form-check-label" htmlFor={perm.id}>
              <input
                type="checkbox"
                className="form-check-input mx-2"
                id={perm.id}
                value={perm.id}
                {...register("selectedPermissions")}
              />
              {perm.name}
            </label>
          </div>
        ))}
      </div>
      
    </div>
    <hr className="hr my-1 py-1" />
    </React.Fragment>
      
  ))}
  {errors.selectedPermissions && (
    <p className="text-danger">{errors.selectedPermissions.message}</p>
  )}
   {!masterFeatures && <p>Loading...</p>}
</div>
 

   {
      masterFeatures && (

        <div className="col-12 text-center">
        <button type="submit" className="btn btn-sm btn-primary me-3">           
         {isLoading? "Please Wait...":"Submit"}       
        </button>
        <button
          type="reset"
          className="btn btn-sm btn-label-secondary"
          data-bs-dismiss="modal"
          aria-label="Close"
        >
          Cancel
        </button>
      </div>
      )
   }
 
    </form>
  );
};

export default CreateRole;





