// import React, { useState,useEffect } from 'react';
// import { Box, Button, TextField, Select, MenuItem, FormControl, InputLabel, Checkbox, IconButton, Typography, FormControlLabel } from '@mui/material';
// import DeleteIcon from '@mui/icons-material/Delete';
// import { useNavigate } from 'react-router-dom';
// import Spinner from '../../UIComponants/Spinner';

// function DynamicForm() {
//   const [loading, setLoading] = useState(true);
//   const [components, setComponents] = useState([{ label: '', type: '', mapping: '', readonly: false, values: '' }]);
//   const [formDetails, setFormDetails] = useState({
//     formName: '',
//     formDescription: '',
//     relatedTo: '',
//     pageEvent: '',
//     buttonName: '',
//   });

//   useEffect(() => {
//     // Simulate loading data
//     setTimeout(() => {
//       setLoading(false);
//     }, 3000); // Simulated 3 seconds loading
//   }, []);

//   const navigate = useNavigate();

//   const handleFormChange = (e) => {
//     const { name, value } = e.target;
//     setFormDetails({ ...formDetails, [name]: value });
//   };

//   const handleComponentChange = (index, field, value) => {
//     const updatedComponents = components.map((component, i) => (i === index ? { ...component, [field]: value } : component));
//     setComponents(updatedComponents);
//   };

//   const addComponent = () => {
//     setComponents([...components, { label: '', type: '', mapping: '', readonly: false, values: '' }]);
//   };

//   const removeComponent = (index) => {
//     setComponents(components.filter((_, i) => i !== index));
//   };

//   const handleSubmit = (e) => {
//     e.preventDefault();
//     const formData = { ...formDetails, components };
//     navigate('/Dynamictable', { state: { formData } }); // Navigate to DynamicTable with formData
//   };

//   return (
//     <div>
//       {loading ? (
//         <Spinner/>
//       ):(
//         <Box sx={{ padding: '20px' }}>
//       <Typography variant="h4" gutterBottom>Dynamic Form Setup</Typography>
//       <form onSubmit={handleSubmit}>
//         <Box sx={{ display: 'flex', gap: '20px', marginBottom: '20px' }}>
//           <TextField
//             label="Form Name"
//             name="formName"
//             value={formDetails.formName}
//             onChange={handleFormChange}
//             fullWidth
//           />
//           <TextField
//             label="Form Description"
//             name="formDescription"
//             value={formDetails.formDescription}
//             onChange={handleFormChange}
//             fullWidth
//           />
//           <FormControl fullWidth>
//             <InputLabel>Related To</InputLabel>
//             <Select
//               name="relatedTo"
//               value={formDetails.relatedTo}
//               onChange={handleFormChange}
//             >
//               <MenuItem value=""><em>None</em></MenuItem>
//               <MenuItem value="Menu">Menu</MenuItem>
//               <MenuItem value="Related to">Related to</MenuItem>
//             </Select>
//           </FormControl>
//         </Box>
//         <Box sx={{ display: 'flex', gap: '20px', marginBottom: '20px' }}>
//           <FormControl fullWidth>
//             <InputLabel>Page Event</InputLabel>
//             <Select
//               name="pageEvent"
//               value={formDetails.pageEvent}
//               onChange={handleFormChange}
//             >
//               <MenuItem value="Onclick">Onclick</MenuItem>
//               <MenuItem value="Onblur">Onblur</MenuItem>
//             </Select>
//           </FormControl>
//           <TextField
//             label="Button Name"
//             name="buttonName"
//             value={formDetails.buttonName}
//             onChange={handleFormChange}
//             fullWidth
//           />
//         </Box>
//         <Typography variant="h6" gutterBottom>Component Details</Typography>
//         {components.map((component, index) => (
//           <Box key={index} sx={{ display: 'flex', gap: '10px', alignItems: 'center', marginBottom: '10px' }}>
//             <TextField
//               label="Label"
//               value={component.label}
//               onChange={(e) => handleComponentChange(index, 'label', e.target.value)}
//               fullWidth
//             />
//             <FormControl fullWidth>
//               <InputLabel>Type</InputLabel>
//               <Select
//                 value={component.type}
//                 onChange={(e) => handleComponentChange(index, 'type', e.target.value)}
//               >
//                 <MenuItem value=""><em>None</em></MenuItem>
//                 <MenuItem value="textfield">TextField</MenuItem>
//                 <MenuItem value="checkbox">Checkbox</MenuItem>
//                 <MenuItem value="select">Select</MenuItem>
//               </Select>
//             </FormControl>
//             <TextField
//               label="Mapping"
//               value={component.mapping}
//               onChange={(e) => handleComponentChange(index, 'mapping', e.target.value)}
//               fullWidth
//             />
//             <FormControlLabel
//               control={
//                 <Checkbox
//                   checked={component.readonly}
//                   onChange={(e) => handleComponentChange(index, 'readonly', e.target.checked)}
//                 />
//               }
//               label="Readonly"
//             />
//             <TextField
//               label="Enter Values"
//               value={component.values}
//               onChange={(e) => handleComponentChange(index, 'values', e.target.value)}
//               fullWidth
//             />
//             <IconButton onClick={() => removeComponent(index)}>
//               <DeleteIcon />
//             </IconButton>
//           </Box>
//         ))}
//         <Button onClick={addComponent} variant="contained" sx={{ marginBottom: '20px' }}>Add Component</Button>
//         <Button type="submit" variant="contained" color="primary">Submit</Button>
//       </form>
//     </Box>
//       )}
//     </div>

//   );
// }

// export default DynamicForm;

import React, { useState, useEffect } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrash } from "@fortawesome/free-solid-svg-icons";
import {
  Button,
  Form,
  FormGroup,
  Label,
  Input,
  FormText,
  Row,
  Col,
  Card,
  CardBody,
  CardTitle,
} from "reactstrap";
import { useNavigate } from "react-router-dom";
import Spinner from "UIComponants/Spinner";
import { buildForm } from '../../../APIServices/DynamicFormAPI';
import { toast } from "react-toastify";


function DynamicFormAdd() {
  const [loading, setLoading] = useState(true);
  const [components, setComponents] = useState([
    { label: "", type: "", mapping: "", readonly: false, values: "" },
  ]);
  const [formDetails, setFormDetails] = useState({
    formName: "",
    formDescription: "",
    relatedTo: "",
    pageEvent: "",
    buttonName: "",
  });

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 3000); // Simulated 3 seconds loading
  }, []);

  const navigate = useNavigate();

  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setFormDetails({ ...formDetails, [name]: value });
  };

  const handleComponentChange = (index, field, value) => {
    const updatedComponents = components.map((component, i) =>
      i === index ? { ...component, [field]: value } : component
    );
    setComponents(updatedComponents);
  };

  const addComponent = () => {
    setComponents([
      ...components,
      { label: "", type: "", mapping: "", readonly: false, values: "" },
    ]);
  };

  const removeComponent = (index) => {
    setComponents(components.filter((_, i) => i !== index));
  };

  // const handleSubmit = async (id) => {
  //   try {
  //     const {status} = await buildForm(id);
  //     if(status >= 200 && status <= 209){
  //       console.log("Form built successfully");
  //     toast.success('Form built successfully');
  //     const formData = { ...formDetails, components };
  //     navigate("/admin/dynamic-form", { state: { formData } });
  //     }else{
  //       toast.error('Error building form');
  //       console.log("Error building form");
  //     }
  //   } catch (error) {
      
  //     console.error("Error saving form:", error);
  //     toast.error(error || 'Error saving form');
  //   }
  // };

  // const handleSubmit = async (id) => {
  //   try {
  //     console.log("Form data to be submitted:", formDetails, components);
  //     const { status } = await buildForm(id); // Ensure `id` is defined
  //     if (status >= 200 && status <= 209) {
  //       console.log("Form built successfully");
  //       toast.success("Form built successfully");
  //       const formData = { ...formDetails, components };
  //       navigate("/admin/dynamic-form", { state: { formData } });
  //     } else {
  //       toast.error("Error building form");
  //       console.log("Error response status:", status);
  //     }
  //   } catch (error) {
  //     console.error("Error submitting form:", error);
  //     toast.error("Error submitting form");
  //   }
  // };

  const handleSubmit = async (e) => {
    e.preventDefault();
  
    try {
      // Combine formDetails and components for the API payload
      const formData = {
        ...formDetails,
        components,
      };
  
      console.log("Form data to be submitted:", formData);
  
      const { status } = await buildForm(formData); // Pass formData to the API call
      if (status >= 200 && status <= 209) {
        toast.success("Form built successfully");
        navigate("/admin/dynamic-form", { state: { formData } });
      } else {
        toast.error("Error building form");
        console.log("Error response status:", status);
      }
    } catch (error) {
      console.error("Error submitting form:", error);
      toast.error("Error submitting form");
    }
  };
  
  

  return (
    <div style={{ marginTop: "11rem" }}>
      {loading ? (
       <Spinner/>
      ) : (
        <Card className="p-4 mb-7">
          <CardBody>
            <CardTitle tag="h4">Dynamic Form Setup</CardTitle>
            <Form onSubmit={handleSubmit}>
              <Row className="mb-3">
                <Col md={4}>
                  <FormGroup>
                    <Label for="formName">Form Name</Label>
                    <Input
                      type="text"
                      id="formName"
                      name="formName"
                      value={formDetails.formName}
                      onChange={handleFormChange}
                    />
                  </FormGroup>
                </Col>
                <Col md={4}>
                  <FormGroup>
                    <Label for="formDescription">Form Description</Label>
                    <Input
                      type="text"
                      id="formDescription"
                      name="formDescription"
                      value={formDetails.formDescription}
                      onChange={handleFormChange}
                    />
                  </FormGroup>
                </Col>
                <Col md={4}>
                  <FormGroup>
                    <Label for="relatedTo">Related To</Label>
                    <Input
                      type="select"
                      id="relatedTo"
                      name="relatedTo"
                      value={formDetails.relatedTo}
                      onChange={handleFormChange}
                    >
                      <option value="">Select</option>
                      <option value="Menu">Menu</option>
                      <option value="Related to">Related to</option>
                    </Input>
                  </FormGroup>
                </Col>
              </Row>
              <Row className="mb-3">
                <Col md={6}>
                  <FormGroup>
                    <Label for="pageEvent">Page Event</Label>
                    <Input
                      type="select"
                      id="pageEvent"
                      name="pageEvent"
                      value={formDetails.pageEvent}
                      onChange={handleFormChange}
                    >
                      <option value="Onclick">Onclick</option>
                      <option value="Onblur">Onblur</option>
                    </Input>
                  </FormGroup>
                </Col>
                <Col md={6}>
                  <FormGroup>
                    <Label for="buttonName">Button Name</Label>
                    <Input
                      type="text"
                      id="buttonName"
                      name="buttonName"
                      value={formDetails.buttonName}
                      onChange={handleFormChange}
                    />
                  </FormGroup>
                </Col>
              </Row>
              <h5>Component Details</h5>
              {components.map((component, index) => (
                <Row key={index} className="align-items-center mb-3">
                  <Col md={2}>
                    <FormGroup>
                      <Input
                        type="text"
                        placeholder="Label"
                        value={component.label}
                        onChange={(e) =>
                          handleComponentChange(index, "label", e.target.value)
                        }
                      />
                    </FormGroup>
                  </Col>
                  <Col md={2}>
                    <FormGroup>
                      <Input
                        type="select"
                        value={component.type}
                        onChange={(e) =>
                          handleComponentChange(index, "type", e.target.value)
                        }
                      >
                        <option value="">Type</option>
                        <option value="textfield">TextField</option>
                        <option value="checkbox">Checkbox</option>
                        <option value="select">Select</option>
                      </Input>
                    </FormGroup>
                  </Col>
                  <Col md={2}>
                    <FormGroup>
                      <Input
                        type="text"
                        placeholder="Mapping"
                        value={component.mapping}
                        onChange={(e) =>
                          handleComponentChange(
                            index,
                            "mapping",
                            e.target.value
                          )
                        }
                      />
                    </FormGroup>
                  </Col>
                  <Col md={2}>
                    <FormGroup check>
                      <Label check>
                        <Input
                          type="checkbox"
                          checked={component.readonly}
                          onChange={(e) =>
                            handleComponentChange(
                              index,
                              "readonly",
                              e.target.checked
                            )
                          }
                        />{" "}
                        Readonly
                      </Label>
                    </FormGroup>
                  </Col>
                  <Col md={2}>
                    <FormGroup>
                      <Input
                        type="text"
                        placeholder="Values"
                        value={component.values}
                        onChange={(e) =>
                          handleComponentChange(index, "values", e.target.value)
                        }
                      />
                    </FormGroup>
                  </Col>
                  <Col md={2}>
                    <FontAwesomeIcon
                      icon={faTrash}
                      className="text-danger cursor-pointer"
                      onClick={() => removeComponent(index)}
                      title="Remove"
                    />
                  </Col>
                </Row>
              ))}
              <Button color="primary" onClick={addComponent} className="me-3">
                Add Component
              </Button>
              <Button color="success" type="submit" onClick={handleSubmit}>
                Submit
              </Button>
            </Form>
          </CardBody>
        </Card>
      )}
    </div>
  );
}

export default DynamicFormAdd;
