"use client";

import React, { useState, useEffect } from "react";
import {
  Card,
  Box,
  Typography,
  Button,
  TextField,
  FormControl,
  
} from "@mui/material";

import 'react-toastify/dist/ReactToastify.css';
import withAuth from "@/withAuth";
import routes from "@/routes";
import {RoleEnum} from '@constant/StaticData';
import SettingsService, {Setting} from "@/service/SettingsService";
import { useCookies } from 'react-cookie';
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useFormik  } from 'formik';
import { GeneralSettingsFormValues, GeneralSettingsValidationSchema, GeneralSettingsTouchFields  } from '@lib/ValidationSchemas';
import { ToastContainer, toast} from 'react-toastify';


const GeneralSettings: React.FC = () => {
  
  const [cookies, setCookie, removeCookie] = useCookies();
  const [systemSettings, setSystemSettings] = useState<Setting | undefined>(undefined);

  const fetchData = async () => {
    try {		  
      const systemSettingsData = await SettingsService.getSettingsFind();

      if(systemSettingsData != undefined && systemSettingsData != null && systemSettingsData?.SettingFind){
        setSystemSettings(systemSettingsData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchData, "Error during fetch data");
    }
  };

  useEffect(() => {
    fetchData();
  },[]);

  const formik = useFormik<GeneralSettingsFormValues>({
    initialValues: {
      id : 0,
      website_banner : "",
      key:""
    },
    validationSchema: GeneralSettingsValidationSchema,
    onSubmit: async(values) => {
      handleSubmit(values);
    },
  });

  const setFormikValues = () => {
    if (systemSettings ) {
      formik.setValues({
        website_banner: systemSettings?.SettingFind?.rows?.[0].fr_setting_preference?.[0]?.plain_value || systemSettings?.SettingFind?.rows?.[0]?.default_plain_value || "",
        id: systemSettings?.SettingFind?.rows?.[0]?.fr_setting_preference?.[0]?.id || 0,
        key: systemSettings?.SettingFind?.rows?.[0]?.key || "",
      });
    } 
  }

  useEffect(() => {
    setFormikValues();
  },[systemSettings]);

  const handleSubmit = async(values:any) =>{
    console.log(values);
    try {
      const response = await SettingsService.SettingPreferenceUpdate(values.key, values.website_banner);
      toast.success("Updated settings successfully !!", {
          position: "bottom-left",
          autoClose: 2000,
      });
    } catch (err) {
      toast.error("Some entries failed to update. Please check the logs.", {
        position: "bottom-left",
        autoClose: 2000,
      });
    }
  };

  return (
    <>
      <Card
        sx={{
          boxShadow: "none",
          borderRadius: "7px",
          mb: "25px",
          padding: { xs: "18px", sm: "20px", lg: "25px" },
        }}
        className="rmui-card"
      >
        <Box component="form" onSubmit={formik.handleSubmit}>

        <input
          type="hidden"
          name="id"
          value={formik.values.id}
        />

        <input
          type="hidden"
          name="key"
          value={formik.values.key}
        />
          
          <Box
            sx={{
              display: "flex",
              flexWrap: "wrap",
              gap: { xs: "16px", sm: "20px" },
              justifyContent: "space-between",
            }}
          >
            <Box
              sx={{
                flexBasis: { xs: "100%", sm: "48%", md: "48%", lg: "48%", xl: "48%" },
              }}
            >
              <FormControl fullWidth>
                <Typography
                  component="label"
                  sx={{
                    fontWeight: "500",
                    fontSize: "14px",
                    mb: "10px",
                    display: "block",
                  }}
                  className="text-black"
                >
                  Website Banner
                </Typography>

                <TextField
                  id="website_banner"
                  name="website_banner"
                  value = {formik.values.website_banner}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={Boolean(formik.touched.website_banner && formik.errors.website_banner)}
                  helperText={formik.touched.website_banner && formik.errors.website_banner}
                  sx={{
                    "& .MuiInputBase-root": {
                      border: "1px solid #D5D9E2",
                      backgroundColor: "#fff",
                      borderRadius: "7px",
                      color: "#000",
                      fontWeight: "500",
                    },
                    "& .MuiInputBase-root::before": {
                      border: "none",
                    },
                    "& .MuiInputBase-root:hover::before": {
                      border: "none",
                    },
                  }}
                />
              </FormControl>
            </Box>

            <Box
              sx={{
                width: "100%",
                display: "flex",
                justifyContent: "flex-end",
                gap: "20px",
                mb: "25px",
              }}
            >

              <Button
                type="submit"
                variant="contained"
                sx={{
                  textTransform: "capitalize",
                  borderRadius: "6px",
                  fontWeight: "500",
                  fontSize: { xs: "13px", sm: "16px" },
                  padding: { xs: "10px 20px", sm: "10px 24px" },
                  color: "#fff !important",
                  boxShadow: "none",
                }}
              >
                <i className="material-symbols-outlined">check</i> Save
              </Button>
            </Box>
          </Box>
        </Box>
      </Card>
      <ToastContainer/>
  </>
  );
};

export default withAuth(GeneralSettings, routes.generalsettings.auth, RoleEnum.ADMIN);