// import React, { useState } from "react";
// import { Button, Form, Container, Row, Col } from "react-bootstrap";
// import "bootstrap/dist/css/bootstrap.min.css";

// const SystemParameterForm = () => {
//   const [formData, setFormData] = useState({
//     schedulerTimer: "",
//     leaseTaxCode: "",
//     vesselConfirmationProcessLimit: "",

//     rowToDisplay: "",
//     linkToDisplay: "",
//     rowToAdd: "",
//     lovRowToDisplay: "",
//     lovLinkToDisplay: "",
//     oldServerName: "",
//     oldBase: "",
//     oldAdminUser: "",
//     oldServerPort: "",
//     userDefaultGroup: "",
//     defaultDepartment: "",
//     defaultPosition: "",
//     singleCharge: "",
//     firstDayOfWeek: "",
//     hourPerShift: "",
//     cnBillingFrequency: "",
//     billingDepartmentCode: "",
//     basePriceList: "",
//     nonContainerServiceOrderAutoApprovalDeptCode: "",
//     ediMAESchedulerOnOff: "",
//     ediSchedulerOnOff: "",
//     logo: null,
//     companyDisplayName: "",
//   });

//   const handleInputChange = (event) => {
//     const { name, value } = event.target;
//     setFormData((prevState) => ({
//       ...prevState,
//       [name]: value,
//     }));
//   };

//   const handleFileChange = (event) => {
//     setFormData((prevState) => ({
//       ...prevState,
//       logo: event.target.files[0],
//     }));
//   };

//   const handleSubmit = (event) => {
//     event.preventDefault();
//     alert("Form submitted successfully!");
//     console.log("Form Data:", formData);
//   };

//   const handleClear = () => {
//     setFormData({
//       schedulerTimer: "",
//       leaseTaxCode: "",
//       vesselConfirmationProcessLimit: "",

//       rowToDisplay: "",
//       linkToDisplay: "",
//       rowToAdd: "",
//       lovRowToDisplay: "",
//       lovLinkToDisplay: "",
//       oldServerName: "",
//       oldBase: "",
//       oldAdminUser: "",
//       oldServerPort: "",
//       userDefaultGroup: "",
//       defaultDepartment: "",
//       defaultPosition: "",
//       singleCharge: "",
//       firstDayOfWeek: "",
//       hourPerShift: "",
//       cnBillingFrequency: "",
//       billingDepartmentCode: "",
//       basePriceList: "",
//       nonContainerServiceOrderAutoApprovalDeptCode: "",
//       ediMAESchedulerOnOff: "",
//       ediSchedulerOnOff: "",
//       logo: null,
//       companyDisplayName: "",
//     });
//   };

//   return (
//     <Container className="mt-5">
//       <Form onSubmit={handleSubmit}>
//         <Row className="mb-3">
//           <Col xs={6}>
//             <h5>Setup Code</h5>
//           </Col>
//           <Col xs={6}>
//             <h5>Value</h5>
//           </Col>
//         </Row>
//         {Object.keys(formData).map((key, index) =>
//           key !== "logo" ? (
//             <Row className="mb-3" key={index}>
//               <Col xs={6}>
//                 <Form.Label>
//                   {key
//                     .split(/(?=[A-Z])/)
//                     .join(" ")
//                     .replace(/\b\w/g, (l) => l.toUpperCase())}
//                 </Form.Label>
//               </Col>
//               <Col xs={6}>
//                 <Form.Control
//                    style={{ borderColor: '#343a40' }}
//                   type="text"
//                   name={key}
//                   value={formData[key]}
//                   onChange={handleInputChange}
//                 />
//               </Col>
//             </Row>
//           ) : (
//             <Row className="mb-3" key={index}>
//               <Col xs={6}>
//                 <Form.Label>Upload Logo</Form.Label>
//               </Col>
//               <Col xs={6}>
//                 <Form.Control style={{ borderColor: '#343a40' }} type="file" onChange={handleFileChange} />
//               </Col>
//             </Row>
//           )
//         )}
//         <div className="d-flex justify-content-end">
//           <Button variant="secondary" type="submit" className="me-2">
//             Save
//           </Button>
//           <Button variant="secondary" onClick={handleClear}>
//             Clear
//           </Button>
//         </div>
//       </Form>
//     </Container>
//   );
// };

// export default SystemParameterForm;

import React, { useState, useEffect } from "react";
import { Button, Form, Container, Row, Col } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "../Dashboard/CSS/CSS/CommonStyle.css";
import { toast } from "react-toastify";
import Spinner from "../../UIComponants/Spinner";
import {getSysParameter,addSysParameter} from "../../APIServices/SystemparameterApi";

const SystemParameterForm = () => {
  const [formData, setFormData] = useState({
    schedulerTime: "",
    leaseTaxCode: "",
    vesselConfProcessLimit: "",
    rowToDisplay: "",
    linkToDisplay: "",
    rowToAdd: "",
    lovRowToDisplay: "",
    lovLinkToDisplay: "",
    oidserverName: "",
    oidBase: "",
    oidAdminUser: "",
    oidServerPort: "",
    userDefaultGroup: "",
    defaultDepartment: "",
    defaultPosition: "",
    singleCharge: "",
    firstDayOftheWeek: "",
    hourPerShift: "",
    cnBillingFrequency: "",
    billingDepartmentCode: "",
    basePriceList: "",
    nonContainerServiceOrder: "",
    ediMaeSchedulerONOFF: "",
    ediSchedulerONOFF: "",
    upload_Logo: null,
    company_Display_Name: "",
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Simulate loading data
    setTimeout(() => {
      setLoading(false);
    }, 3000); // Simulated 3 seconds loading
  }, []);
  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const handleFileChange = (event) => {
    setFormData((prevState) => ({
      ...prevState,
      logo: event.target.files[0],
    }));
  };

  // const handleSubmit = (event) => {
  //   event.preventDefault();

  //   toast.success("Form submitted successfully!");
  //   // alert("Form submitted successfully!");
  //   console.log("Form Data:", formData);
  // };

  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
        console.log("Form Data:", formData);
        const sysParamData = await addSysParameter(formData);
        console.log("API Response:", sysParamData);

        toast.success("Form submitted successfully!");
    } catch (error) {
        console.error("Error:", error.response ? error.response.data : error.message);
        toast.error("Failed to submit the form. Please try again.");
    }
};

  const handleClear = () => {
    setFormData({
      schedulerTimer: "",
      leaseTaxCode: "",
      vesselConfirmationProcessLimit: "",

      rowToDisplay: "",
      linkToDisplay: "",
      rowToAdd: "",
      lovRowToDisplay: "",
      lovLinkToDisplay: "",
      oldServerName: "",
      oldBase: "",
      oldAdminUser: "",
      oldServerPort: "",
      userDefaultGroup: "",
      defaultDepartment: "",
      defaultPosition: "",
      singleCharge: "",
      firstDayOfWeek: "",
      hourPerShift: "",
      cnBillingFrequency: "",
      billingDepartmentCode: "",
      basePriceList: "",
      nonContainerServiceOrderAutoApprovalDeptCode: "",
      ediMAESchedulerOnOff: "",
      ediSchedulerOnOff: "",
      logo: null,
      companyDisplayName: "",
    });
  };

  return (
    <div
      style={{
        marginTop: "10rem",
        marginBottom: "2rem",
        boxSizing: "border-box",
      }}
    >
      {loading ? (
        <Spinner />
      ) : (
        <Container
          className="system_parameter mt-5 p-4 bg-light shadow-sm rounded"
          
        >
          <h2
            className="title_main text-center mb-4"
            style={{ color: "#0E6591", fontWeight: "bold" }}
          >
            System Parameter Settings
          </h2>
          <Form onSubmit={handleSubmit}>
            <Row className="  mb-3">
              <Col xs={6}>
                <h6 className="heading_main text-secondary">Setup Code</h6>
              </Col>
              <Col xs={6}>
                <h6 className="heading_main text-secondary">Value</h6>
              </Col>
            </Row>

            {Object.keys(formData).map((key, index) =>
              key !== "upload_Logo" ? (
                <Row className="mb-3" key={index}>
                  <Col xs={6} className="d-flex align-items-center">
                    <Form.Label className="mb-0">
                      {key
                        .split(/(?=[A-Z])/)
                        .join(" ")
                        .replace(/\b\w/g, (l) => l.toUpperCase())}
                    </Form.Label>
                  </Col>
                  <Col xs={6}>
                    <Form.Control
                      className="p-2  custom-hover-border"
                      style={{ borderColor: "#ced4da" }}
                      type="text"
                      name={key}
                      value={formData[key]}
                      onChange={handleInputChange}
                    />
                  </Col>
                </Row>
              ) : (
                <Row className="mb-3" key={index}>
                  <Col xs={6} className="d-flex align-items-center">
                    <Form.Label className="mb-0">Upload Logo</Form.Label>
                  </Col>
                  <Col xs={6}>
                    <Form.Control
                      className="p-2 "
                      style={{ borderColor: "#ced4da" }}
                      type="file"
                      onChange={handleFileChange}
                    />
                  </Col>
                </Row>
              )
            )}

            <div className="d-flex justify-content-end mt-4">
              <Button
                variant="primary"
                type="submit"
                className="me-2 px-4 py-2 custom_button"
              >
                Save
              </Button>
              <Button
                variant="outline"
                onClick={handleClear}
                className="px-4 py-2 custom_button"
              >
                Clear
              </Button>
            </div>
          </Form>
        </Container>
      )}
    </div>
  );
};

export default SystemParameterForm;
