import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import {
  Box,
  Button,
  Card,
  CardContent,
  Checkbox,
  FormControl,
  FormControlLabel,
  TextField,
  Typography,
  Chip
} from '@mui/material';
import {
  Save as SaveIcon,
  ArrowBack as ArrowBackIcon
} from '@mui/icons-material';
import DashboardBuilderService from "../../../ApiServices/DashboardBuilderServices";

const DashboardbuilderAdd = () => {
  const [moduleId, setModuleId] = useState(null);
  const navigate = useNavigate();
  const { register, handleSubmit, 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({
          dashboard: [{
            cols: 4,
            rows: 5,
            x: 0,
            y: 0,
            name: "Radar Chart",
            component: "Radar Chart",
          }],
        })
      }],
    },
  });

  useEffect(() => {
    setModuleId("exampleModuleId");
  }, []);

  const onSubmit = (data) => {
    if (!data.dashboard_name || !data.secuirity_profile || !data.description) {
      toast.error("Please fill out all required fields.");
      return;
    }
  
    const newDashboard = {
      ...data,
    };
  
    DashboardBuilderService.create(newDashboard)
      .then((response) => {
        toast.success("Dashboard Added successfully");
        navigate("/dashboard/dashboard-new-all");
      })
      .catch((error) => {
        console.error(error);
        toast.error("Error while adding dashboard");
      });
  };
  
  return (
    <Card sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <Typography variant="h5" sx={{ fontWeight: 500 }}>
          Define Dashboard
        </Typography>
        <Chip
          label="Add Mode"
          color="primary"
          size="small"
          sx={{ ml: 2 }}
        />
      </Box>

      <Box component="form" onSubmit={handleSubmit(onSubmit)}>
        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 3, mb: 3 }}>
          <FormControl fullWidth>
            <TextField
              label="Dashboard Name"
              variant="outlined"
              {...register("dashboard_name", { required: true })}
              error={!!errors.dashboard_name}
              helperText={errors.dashboard_name ? "This field is required" : ""}
            />
          </FormControl>

          <FormControl fullWidth>
            <TextField
              label="Security Profile"
              variant="outlined"
              {...register("secuirity_profile", { required: true })}
              error={!!errors.secuirity_profile}
              helperText={errors.secuirity_profile ? "This field is required" : ""}
            />
          </FormControl>

          <FormControl fullWidth sx={{ gridColumn: '1 / -1' }}>
            <TextField
              label="Description"
              variant="outlined"
              multiline
              rows={3}
              {...register("description", { required: true })}
              error={!!errors.description}
              helperText={errors.description ? "This field is required" : ""}
            />
          </FormControl>

          <FormControlLabel
            control={
              <Checkbox
                defaultChecked
                {...register("add_to_home")}
                color="primary"
              />
            }
            label="Add to Dashboard"
          />
        </Box>

        <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2 }}>
          <Button
            variant="outlined"
            startIcon={<ArrowBackIcon />}
            onClick={() => navigate("/dashboard/dashboard-new-all")}
          >
            Back
          </Button>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            startIcon={<SaveIcon />}
          >
            Submit
          </Button>
        </Box>
      </Box>
    </Card>
  );
};

export default DashboardbuilderAdd;