import React, { useState, useEffect } from "react";
import { 
  Button, 
  Container, 
  Grid, 
  TextField, 
  Typography, 
  Paper,
  Box,
  LinearProgress
} from "@mui/material";
import { toast } from "react-toastify";
import { addSysParameter } from "../../../ApiServices/SytemparameterApi";
import { useSystemParameters } from "../../../context/SystemParameterContext";

const SystemParameterForm = () => {
  const { systemParameters, loading: contextLoading } = useSystemParameters();

  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: "",
  });

  useEffect(() => {
    if (systemParameters) {
      setFormData((prevForm) => ({
        ...prevForm,
        ...systemParameters,
      }));
    }
  }, [systemParameters]);

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

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

  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({
      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 formatLabel = (key) => {
    return key
      .split(/(?=[A-Z])/)
      .join(" ")
      .replace(/\b\w/g, (l) => l.toUpperCase());
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 10, mb: 4 }}>
      {contextLoading ? (
        <LinearProgress />
      ) : (
        <Paper elevation={3} sx={{ p: 4 }}>
          <Typography 
            variant="h4" 
            component="h1" 
            align="center" 
            sx={{ 
              mb: 4,
              color: 'primary.main',
              fontWeight: 'bold'
            }}
          >
            System Parameter Settings
          </Typography>
          
          <Box component="form" onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={6}>
                <Typography variant="h6" color="text.secondary">
                  Setup Code
                </Typography>
              </Grid>
              <Grid item xs={6}>
                <Typography variant="h6" color="text.secondary">
                  Value
                </Typography>
              </Grid>

              {Object.keys(formData).map((key, index) =>
                key !== "upload_Logo" ? (
                  <React.Fragment key={index}>
                    <Grid item xs={6} sx={{ display: 'flex', alignItems: 'center' }}>
                      <Typography>{formatLabel(key)}</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <TextField
                        fullWidth
                        name={key}
                        value={formData[key]}
                        onChange={handleInputChange}
                        variant="outlined"
                        size="small"
                      />
                    </Grid>
                  </React.Fragment>
                ) : (
                  <React.Fragment key={index}>
                    <Grid item xs={6} sx={{ display: 'flex', alignItems: 'center' }}>
                      <Typography>Upload Logo</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <TextField
                        fullWidth
                        type="file"
                        onChange={handleFileChange}
                        variant="outlined"
                        size="small"
                        InputProps={{
                          inputProps: {
                            accept: "image/*"
                          }
                        }}
                      />
                    </Grid>
                  </React.Fragment>
                )
              )}
            </Grid>

            <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 4 }}>
              <Button
                variant="contained"
                type="submit"
                sx={{ mr: 2 }}
              >
                Save
              </Button>
              <Button
                variant="outlined"
                onClick={handleClear}
              >
                Clear
              </Button>
            </Box>
          </Box>
        </Paper>
      )}
    </Container>
  );
};

export default SystemParameterForm;