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

const EditFormNewDash = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const [header, setHeader] = useState({
    dashboard_name: '',
    secuirity_profile: '',
    description: '',
    add_to_home: false,
  });

  useEffect(() => {
    if (location.state?.dashboard) {
      setHeader(location.state.dashboard);
    } else {
      getById(id);
    }
  }, [id, location.state]);

  const getById = (id) => {
    DashboardBuilderService.getById(id)
      .then((data) => {
        setHeader(data);
      })
      .catch((err) => {
        console.error("Error fetching dashboard by ID:", err);
        toast.error('Failed to fetch dashboard data.');
      });
  };

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

  const update = async () => {
    try {
      const updatedDashboard = await DashboardBuilderService.updateDash(header);
      if (updatedDashboard) {
        toast.success('Dashboard updated successfully');
        navigate('/dashboard/dashboard-new-all');
      }
    } catch (error) {
      console.error("Error updating dashboard:", error);
      toast.error('Failed to update dashboard.');
    }
  };

  const onSubmit = (e) => {
    e.preventDefault();
    update();
  };

  const onBack = () => {
    navigate('/dashboard/dashboard-new-all');
  };

  return (
    <Card sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <Typography variant="h5">Dashboard</Typography>
        <Chip
          label="Edit Mode"
          color="info"
          size="small"
          sx={{ ml: 2 }}
        />
      </Box>

      <Box component="form" onSubmit={onSubmit}>
        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 3, mb: 3 }}>
          <FormControl fullWidth>
            <TextField
              label="Dashboard Name"
              name="dashboard_name"
              value={header.dashboard_name || ''}
              onChange={handleInputChange}
              required
            />
          </FormControl>

          <FormControl fullWidth>
            <TextField
              label="Security Profile"
              name="secuirity_profile"
              value={header.secuirity_profile || ''}
              onChange={handleInputChange}
              required
            />
          </FormControl>

          <FormControl fullWidth sx={{ gridColumn: '1 / -1' }}>
            <TextField
              label="Description"
              name="description"
              value={header.description || ''}
              onChange={handleInputChange}
              multiline
              rows={3}
              required
            />
          </FormControl>

          <FormControlLabel
            control={
              <Checkbox
                name="add_to_home"
                checked={header.add_to_home || false}
                onChange={handleInputChange}
                color="primary"
              />
            }
            label="Add to Dashboard"
          />
        </Box>

        <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2 }}>
          <Button
            variant="outlined"
            startIcon={<ArrowBackIcon />}
            onClick={onBack}
          >
            Back
          </Button>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            startIcon={<SaveIcon />}
          >
            Update
          </Button>
        </Box>
      </Box>
    </Card>
  );
};

export default EditFormNewDash;