// import React,{useState,useEffect} from 'react'
// import { useForm, useFieldArray } from "react-hook-form";
// import { useNavigate } from "react-router-dom";
// import { toast } from "react-toastify";
// import "react-toastify/dist/ReactToastify.css";
// import { Badge } from "reactstrap";

// const DashboardbuilderAdd = () => {

//     const [moduleId, setModuleId] = useState(null);
//     const [techStacks, setTechStacks] = useState([]);
//     const objectTypes = ["form", "bi", "report", "api"];
//     const subObjectTypes = [
//       "only header",
//       "only line",
//       "header line",
//       "header multiline",
//       "workflow",
//       "setup",
//       "std report",
//       "bi report",
//       "rest api",
//     ];

//     const fieldModels = {
//       dashboard: [
//         {
//           cols: 4,
//           rows: 5,
//           x: 0,
//           y: 0,
//           name: "Radar Chart",
//           component: "Radar Chart",
//         },
//       ],
//     };

//     const navigate = useNavigate();
//     const {
//       register,
//       handleSubmit,
//       control,
//       formState: { errors },
//     } = useForm({
//       defaultValues: {
//         dashboard_name: "",
//         description: "",
//         secuirity_profile: "",
//         module_id: null,
//         tech_Stack: "",
//         object_type: "",
//         sub_object_type: "",
//         add_to_home: true,
//         dashbord1_Line: [
//           {
//             model: JSON.stringify(fieldModels),
//           },
//         ],
//       },
//     });

//     const { fields } = useFieldArray({
//       control,
//       name: "dashbord1_Line",
//     });

//     useEffect(() => {
//       // Simulate module ID fetching logic
//       setModuleId("exampleModuleId");
//     }, []);

//     const onSubmit = (data) => {
//       console.log("Form Data:", data);
//       if (!data.dashboard_name || !data.secuirity_profile || !data.description) {
//         toast.error("Please fill out all required fields.");
//         return;
//       }

//       data.module_id = moduleId;

//     //   DashboardService.create(data)
//     //     .then((response) => {
//     //       console.log(response);
//     //       toast.success("Added successfully");
//     //       navigate("../all");
//     //     })
//     //     .catch((error) => {
//     //       console.error(error);
//     //       toast.error("Error while adding dashboard");
//     //     });
//     };

//     const onValid = (data) => {
//       console.log('Form Submitted Successfully:', data);
//     };

//   return (
//     <div className="container">
//     <h4 style={{ fontWeight: 300, display: "inline" }}>
//       <b>Define Dashboard</b>
//     </h4>
//     <Badge
//       color="info" // This sets the blue color
//       style={{ display: "inline", marginLeft: 10 }}
//     >
//       Add Mode
//     </Badge>
//     <hr />
//     <br />

//     <form onSubmit={handleSubmit(onSubmit)}>
//       <div className="row">
//         <div className="col-md-6 col-sm-12">
//           <label htmlFor="dashboard_name">Dashboard Name</label>
//           <input
//             id="dashboard_name"
//             type="text"
//             {...register("dashboard_name", { required: true })}
//             className="form-control"
//             placeholder="Enter dashboard name"
//           />
//           {errors.dashboard_name && <p className="text-danger">This field is required.</p>}
//         </div>

//         <div className="col-md-6 col-sm-12">
//           <label htmlFor="secuirity_profile">Security Profile</label>
//           <input
//             id="secuirity_profile"
//             type="text"
//             {...register("secuirity_profile", { required: true })}
//             className="form-control"
//             placeholder="Enter security profile"
//           />
//           {errors.secuirity_profile && <p className="text-danger">This field is required.</p>}
//         </div>

//         <div className="col-md-6 col-sm-12">
//           <label htmlFor="description">Description</label>
//           <textarea
//             id="description"
//             {...register("description", { required: true })}
//             className="form-control"
//             placeholder="Enter description"
//           />
//           {errors.description && <p className="text-danger">This field is required.</p>}
//         </div>

//         <div className="col-md-6 col-sm-12" >
//           <label htmlFor="add_to_home" style={{ marginTop: "1rem"}}>Add to Dashboard</label>
//           <input
//             type="checkbox"
//             {...register("add_to_home")}
//             className="form-check-input"
//             style={{marginTop:"3rem" , marginLeft:"-8rem"}}
//           />
//         </div>
//       </div>
//       <br />

//       <div className="text-center">
//         <button
//           type="button"
//           className="btn btn-outline-secondary"
//           onClick={() => navigate("/admin/dashboard-new-all")}
//         >
//           Back
//         </button>
//         <button type="submit" className="btn btn-primary" onClick={handleSubmit()}>
//           Submit
//         </button>
//       </div>
//     </form>
//   </div>
//   )
// }

// export default DashboardbuilderAdd

import React, { useState, useEffect } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { Badge } from "reactstrap";
import DashboardBuilderService from  "../../../../APIServices/DashboardBuilderService";

const DashboardbuilderAdd = () => {
  const [moduleId, setModuleId] = useState(null);
  const [techStacks, setTechStacks] = useState([]);
  const objectTypes = ["form", "bi", "report", "api"];
  const subObjectTypes = [
    "only header",
    "only line",
    "header line",
    "header multiline",
    "workflow",
    "setup",
    "std report",
    "bi report",
    "rest api",
  ];
  const [dashboards, setDashboards] = useState([]);

  const fieldModels = {
    dashboard: [
      {
        cols: 4,
        rows: 5,
        x: 0,
        y: 0,
        name: "Radar Chart",
        component: "Radar Chart",
      },
    ],
  };

  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    control,
    formState: { errors },
  } = useForm({
    defaultValues: {
      dashboard_name: "",
      description: "",
      secuirity_profile: "",
      module_id: null,
      tech_Stack: "",
      object_type: "",
      sub_object_type: "",
      add_to_home: true,
      dashbord1_Line: [
        {
          model: JSON.stringify(fieldModels),
        },
      ],
    },
  });

  const { fields } = useFieldArray({
    control,
    name: "dashbord1_Line",
  });

  useEffect(() => {
    // Simulate module ID fetching logic
    setModuleId("exampleModuleId");
  }, []);

  // #############
  const onSubmit = (data) => {
  
    console.log("Form Data:", data);
    if (!data.dashboard_name || !data.secuirity_profile || !data.description) {
      toast.error("Please fill out all required fields.");
      return;
    }
  
    const newDashboard = {
      ...data,
      // module_id: Number(moduleId), // Ensure this is an integer
      // id: Date.now(), // Simulate a unique ID
    };
  
    console.log("New Dashboard:", newDashboard);
    const existingDashboards =
      JSON.parse(localStorage.getItem("dashboards")) || [];
    console.log("Existing Dashboards:", existingDashboards);
  
    localStorage.setItem(
      "dashboards",
      JSON.stringify([...existingDashboards, newDashboard])
    );
  
    setDashboards((prevDashboards) => [...prevDashboards, newDashboard]);
    
   
  
    // API call to save the new dashboard
    DashboardBuilderService.create(newDashboard)
      .then((response) => {
        console.log(response);
        toast.success("Dashboard Added successfully");
        navigate("/admin/dashboard-new-all");
      })
      .catch((error) => {
        console.error(error);
        toast.error("Error while adding dashboard");
      });
  };
  
  return (
    <div className="container">
      <h4 style={{ fontWeight: 300, display: "inline" }}>
        <b>Define Dashboard</b>
      </h4>
      <Badge
        color="info" // This sets the blue color
        style={{ display: "inline", marginLeft: 10 }}
      >
        Add Mode
      </Badge>
      <hr />
      <br />

      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="row">
          <div className="col-md-6 col-sm-12">
            <label htmlFor="dashboard_name">Dashboard Name</label>
            <input
              id="dashboard_name"
              type="text"
              {...register("dashboard_name", { required: true })}
              className="form-control"
              placeholder="Enter dashboard name"
            />
            {errors.dashboard_name && (
              <p className="text-danger">This field is required.</p>
            )}
          </div>

          <div className="col-md-6 col-sm-12">
            <label htmlFor="secuirity_profile">Security Profile</label>
            <input
              id="secuirity_profile"
              type="text"
              {...register("secuirity_profile", { required: true })}
              className="form-control"
              placeholder="Enter security profile"
            />
            {errors.secuirity_profile && (
              <p className="text-danger">This field is required.</p>
            )}
          </div>

          <div className="col-md-6 col-sm-12">
            <label htmlFor="description">Description</label>
            <textarea
              id="description"
              {...register("description", { required: true })}
              className="form-control"
              placeholder="Enter description"
            />
            {errors.description && (
              <p className="text-danger">This field is required.</p>
            )}
          </div>

          <div className="col-md-6 col-sm-12">
            <label htmlFor="add_to_home" style={{ marginTop: "1rem" }}>
              Add to Dashboard
            </label>
            <input
              type="checkbox"
              {...register("add_to_home")}
              className="form-check-input"
              style={{ marginTop: "3rem", marginLeft: "-8rem" }}
            />
          </div>
        </div>
        <br />

        <div className="text-center">
          <button
            type="button"
            className="btn btn-outline-secondary"
            onClick={() => navigate("/admin/dashboard-new-all")}
          >
            Back
          </button>
          <button type="submit" className="btn btn-primary">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
};

export default DashboardbuilderAdd;
