import { useFormik } from 'formik';
import * as Yup from 'yup';
import { Grid, InputLabel, TextField, Button, Stack } from '@mui/material';
import { useEffect, useState } from 'react';
import axios from 'axios';
import { useSelector } from 'react-redux';
import Loader from 'components/Loader';

import OpenToast from 'components/nearle_components/OpenToast';
import Titlecard from 'components/nearle_components/Titlecard';
import MainCard from 'components/MainCard';

const initialData = {
  tenantname: '',
  companyname: '',
  registrationno: '',
  primarycontact: '',
  primaryemail: '',
  address: '',
  suburb: '',
  city: '',
  state: '',
  postcode: ''
};

const Accountsettings = () => {
  const userdata = useSelector((state) => state.userinfo.userdata);
  const [initialValues, setInitialValues] = useState(initialData);
  const [loading, setLoading] = useState(false);
  const [formChanged, setFormChanged] = useState(false);

  const formik = useFormik({
    initialValues,
    enableReinitialize: true,
    validationSchema: Yup.object({
      tenantname: Yup.string().required('Tenant Name is required'),
      companyname: Yup.string().required('Company Name is required'),
      registrationno: Yup.string().required('Registration No is required'),
      primarycontact: Yup.string().required('Phone is required'),
      state: Yup.string().required('State is required'),
      primaryemail: Yup.string().email('Invalid email').required('Email is required'),
      city: Yup.string().required('City is required'),
      suburb: Yup.string(),
      postcode: Yup.string().required('Zip Code is required'),
      address: Yup.string().required('Address is required')
    }),
    onSubmit: async (values) => {
      const changedFields = Object.keys(values).reduce((acc, key) => {
        if (values[key] !== initialValues[key]) {
          acc[key] = values[key];
        }
        return acc;
      }, {});

      console.log('Changed fields only:', changedFields);
      try {
        const updateres = await axios.put(`${process.env.REACT_APP_URL}/tenants/update`, {
          ...changedFields,
          tenantid: userdata?.tenantid
        });
        if (updateres.status) {
          console.log(updateres);
          OpenToast(updateres.data.message, 'success', 1500);
          fetchTenantInfo();
        }
        console.log(updateres.data);
      } catch (err) {
        console.log(err.message);
      }
    }
  });

  const fetchTenantInfo = async () => {
    setLoading(true);
    try {
      const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantinfo/?tenantid=${userdata?.tenantid}`);
      if (res.data.status) {
        setInitialValues(res.data.details); // ✅ Formik auto-updates due to enableReinitialize
      }
    } catch (err) {
      console.error(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (userdata?.tenantid) fetchTenantInfo();
  }, [userdata]);

  useEffect(() => {
    const isModified = Object.keys(initialValues).some((key) => formik.values[key] !== initialValues[key]);
    setFormChanged(isModified);
  }, [formik.values, initialValues]);

  if (loading) return <Loader />;

  return (
    <form onSubmit={formik.handleSubmit} noValidate>
      <Titlecard title="Account Settings" />
      <MainCard>
        <Grid container spacing={2}>
          {Object.keys(initialData).map((fieldKey) => (
            <Grid item xs={12} sm={6} key={fieldKey}>
              <InputLabel sx={{ mb: 1 }}>{fieldKey.slice(0, 1).toUpperCase() + fieldKey.slice(1)}</InputLabel>
              <TextField
                fullWidth
                name={fieldKey}
                value={formik.values[fieldKey] || ''}
                onChange={formik.handleChange}
                error={formik.touched[fieldKey] && Boolean(formik.errors[fieldKey])}
                helperText={formik.touched[fieldKey] && formik.errors[fieldKey]}
              />
            </Grid>
          ))}
        </Grid>
      </MainCard>

      <Stack sx={{ position: 'sticky', bottom: 0, alignItems: 'flex-end', width: '100%', mt: 3, backgroundColor: 'border.light' }}>
        <Button
          type="submit"
          variant="contained"
          color="primary"
          disabled={!formChanged}
          sx={{ width: 'auto', mx: 3, my: 1 }} // prevents full-width
        >
          Save Changes
        </Button>
      </Stack>
    </form>
  );
};

export default Accountsettings;
