import React, { useState, useEffect } from 'react';
import { useNavigate, useParams,useLocation } from 'react-router-dom';
import {toast} from 'react-toastify'; // You can use a different notification system if needed
import DashboardBuilderService from  "../../../../APIServices/DashboardBuilderService"; // Update with your service path
import { Badge } from "reactstrap";

const EditFormNewDash = () => {
  const { id } = useParams(); // Access the id from the URL params
 const navigate = useNavigate();
 const location = useLocation();
  const [header, setHeader] = useState({
    dashboard_name: '',
    secuirity_profile: '',
    description: '',
    add_to_home: false,
  });
  const [updated, setUpdated] = useState(false);
  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",
  ];

  // Fetch data by ID when component mounts
  // useEffect(() => {
  //   if (id) {
  //     getById(id);
  //   }
  // }, [id]);

  useEffect(() => {
    if (location.state?.dashboard) {
      setHeader(location.state.dashboard);
    } else {
      // Fetch data if not passed in state
      getById(id);
    }
  }, [id, location.state]);

  // Get dashboard data by ID
  // const getById = (id) => {
  //   DashboardService.getById(id)
  //     .then((data) => {
  //       console.log(data);
  //       setHeader(data);
  //     })
  //     .catch((err) => {
  //       console.log(err);
  //     });
  // };

  const getById = (id,data) => {
    
    DashboardBuilderService.getById(id)
      .then((data) => {
        console.log("get dashbord by id: ",data);
        setHeader(data);
      })
      .catch((err) => {
        // Static error handling
        console.error("Error fetching dashboard by ID:", err);
        toast.error('Failed to fetch dashboard data. Please try again later.');
      });
  };

 
  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setHeader((prev) => ({
      ...prev,
      ...header,
      [name]: type === 'checkbox' ? checked : value,
    }));
  };

  const update = async () => {
    
    console.log("Submitted Data:", header); // Log the data to verify it's correct
  const staticTestData = { ...header}; // Mock updated data with additional fields if needed
  console.log("Static Updated Data:", staticTestData);
  toast.success('Dashboard updated successfully');
  // navigate('/admin/dashboard-new-all',{ state: { updatedDashboard: staticTestData } });
  
  try {
    const updatedDashboard = await DashboardBuilderService.updateDash(header); // Await the API response

    if (updatedDashboard) {
      setUpdated(true);
      toast.success('Dashboard updated successfully');
      navigate('/admin/dashboard-new-all'); // Pass updated data to the next page
    } else {
      throw new Error("No response from server");
    }
  } catch (error) {
    console.error("Error updating dashboard:", error);
    toast.error('Failed to update the dashboard. Please try again later.');
  }
};
  

  // Handle form submission
  const onSubmit = (e) => {
    e.preventDefault();
    setUpdated(true);
    update();
  };

  // Handle the back button
  const onBack = () => {
    navigate('/admin/dashboard-new-all');
  };

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

      <form onSubmit={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"
              name="dashboard_name"
              value={header.dashboard_name  || ''}
              // onChange={(e) => setHeader({ ...header, dashboard_name: e.target.value })}
              onChange={handleInputChange}
              placeholder="Enter Dashboard Name"
              className="form-control"
            />
          </div>
          <div className="col-md-6 col-sm-12">
            <label htmlFor="secuirity_profile">Security Profile</label>
            <input
              id="secuirity_profile"
              type="text"
              name="secuirity_profile"
              value={header.secuirity_profile || ''}
              // onChange={(e) => setHeader({ ...header, secuirity_profile: e.target.value })}
              onChange={handleInputChange}
              placeholder="Enter Security Profile"
              className="form-control"
            />
          </div>
          <div className="col-md-6 col-sm-12">
            <label htmlFor="description">Description</label>
            <textarea
              cols="10"
              rows="2"
              name="description"
              value={header.description || ''}
              // onChange={(e) => setHeader({ ...header, description: e.target.value })}
              onChange={handleInputChange}
              placeholder="Enter Description"
              className="form-control"
            />
          </div>
          <div className="col-md-6 col-sm-12">
            <label htmlFor="workflow_name"  style={{ marginTop: "1rem" }}>Add to Dashboard</label>
            <input
              type="checkbox"
              name="add_to_home"
              checked={header.add_to_home || ''}
              // onChange={(e) => setHeader({ ...header, add_to_home: e.target.checked })}
              onChange={handleInputChange}
             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={onBack}>BACK</button>
          <button type="submit" className="btn btn-primary">Update</button>
        </div>
      </form>
    </div>
  );
};

export default EditFormNewDash;
