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

import {  useFeatures} from "../../hooks/useMasterRole";
import { MasterRespository } from "../../repositories/MastersRepository";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import showToast from "../../services/toastService";








const updateSchema = 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" }),
  permissions: z.record(z.boolean()).refine((permission) => Object.values(permission).includes(true), {
    message: "At least one permission must be selected", 
  }),
});



const  EditMaster=({master,onClose})=> {
  const [isLoading,setIsLoading] = useState(false)
  const {masterFeatures} = useFeatures()

  const buildDefaultPermissions = () => {
    const defaults = {};
    masterFeatures.forEach((feature) => {
      feature.featurePermissions.forEach((perm) => {
        const existing = master?.item?.featurePermission?.find(
          (p) => p.id === perm.id
        );
        defaults[perm.id] = existing ? existing.isEnabled : false;
      });
    });
    return defaults;
    
  };


  const initialPermissions = buildDefaultPermissions();
 
  

  
  const {
    register,
    handleSubmit,
    formState: { errors, dirtyFields },
    setError,reset
  } = useForm({
    resolver: zodResolver(updateSchema),
    defaultValues: {
      role: master?.item?.role,
      description: master?.item?.description,
      permissions: initialPermissions,
    },
  });

  const onSubmit = (data) => {
     setIsLoading(true)
    const existingIds = new Set(
      master?.item?.featurePermission?.map((p) => p.id)
    );

    
    const updatedPermissions = Object.entries(data.permissions)
      .filter(([id, value]) => {
        if (existingIds.has(id)) return true;
       
        return (
          value === true ||
          (dirtyFields.permissions && dirtyFields.permissions[id])
        );
      })
      .map(([id, value]) => ({ id, isEnabled: value }));

    
    if (updatedPermissions.length === 0) {
      setError("permissions", {
        type: "manual",
        message: "At least one permission must be selected.",
      });
      return;
    }

    const updatedRole = {
      id:master?.item?.id,
      role: data.role,
      description: data.description,
      featuresPermission: updatedPermissions,
    };
    MasterRespository.updateRoles(master?.item?.id, updatedRole).then((resp)=>{ 
      setIsLoading( false )
      

      const cachedData = getCachedData("Application Role");
  
        if (cachedData) {
      
          const updatedData = cachedData.map((role) =>
            role.id === resp.data?.id ? { ...role, ...resp.data } : role
            );
                
            cacheData("Application Role", updatedData);
        }
      showToast( "Application Role Updated successfully.", "success" );
      setIsLoading(false)
      onClose()
    }).catch((Err)=>{
      showToast( Err.message, "error" );
      setIsLoading(false)
    })

  };

  useEffect(() => {
    reset({
      role: master?.item?.role,
      description: master?.item?.description,
      permissions: initialPermissions,
    });
    setDescriptionLength(master?.item?.description?.length || 0);
  }, [master, reset]);
  
  const [descriptionLength, setDescriptionLength] = useState(master?.item?.description?.length || 0);
  const maxDescriptionLength = 255;


  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-invalid' : ''}`}
          />
          {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' : ''}`}
          onChange={(e) => {
            setDescriptionLength(e.target.value.length);
            register("description").onChange(e);
          }}
        ></textarea>
        <div className="text-end small text-muted">
          {maxDescriptionLength - descriptionLength} characters left
        </div>
        {errors.description && (
          <p className="text-danger">{errors.description.message}</p>
        )}
        </div>  

        <div className="col-12 col-md-12 mx-2s " >
         
          {masterFeatures.map((feature) => (
             <div className="row my-3" key={feature.id} style={{marginLeft:"0px"}}>
            
            <div className="col-12 col-md-3 d-flex text-start align-items-center" 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}
                      {...register(`permissions.${perm.id}`, { 
                        value: initialPermissions[perm.id] || false 
                      })}
                    />
                   
                      {perm.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>
          ))}
          {errors.permissions && (
            <p className="text-danger">{errors.permissions.message}</p>
          )}
        </div>

        <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 EditMaster;
