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

import Loader from 'components/Loader';
import OpenToast from 'components/nearle_components/OpenToast';
import Titlecard from 'components/nearle_components/Titlecard';
import MainCard from 'components/MainCard';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getRiderShifts } from '../api/api';
import { useQuery } from '@tanstack/react-query';

const fieldLabels = {
  firstname: 'User Name',
  contactno: 'Contact Number',
  email: 'Email',
  roleid: 'Role ID',
  shiftid: 'Rider Shift',
  address: 'Address',
  suburb: 'Suburb',
  city: 'City',
  state: 'State',
  postcode: 'Postcode'
};

const EditUsers = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const user = location.state?.user;
  console.log('user', user);

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

  const defaultValues = {
    firstname: '',
    contactno: '',
    email: '',
    shiftid: '',
    address: '',
    suburb: '',
    city: '',
    state: '',
    postcode: ''
  };

  const [initialValues, setInitialValues] = useState({ ...defaultValues, ...user });

  const validationSchema = Yup.object({
    firstname: Yup.string().required('First name is required'),
    contactno: Yup.string()
      .matches(/^\d{10}$/, 'Contact number must be exactly 10 digits')
      .required('Contact number is required'),
    email: Yup.string().email('Invalid email').required('Email is required'),
    roleid: Yup.number().required('Role is required'),
    shiftid: Yup.number().nullable(),
    address: Yup.string().required('Address is required'),
    suburb: Yup.string().required('Suburb is required'),
    city: Yup.string().required('City is required'),
    state: Yup.string().required('State is required'),
    postcode: Yup.string().required('Postcode is required')
  });

  const formik = useFormik({
    initialValues,
    enableReinitialize: true,
    validationSchema,
    onSubmit: async (values) => {
      const changedFields = Object.keys(values).reduce((acc, key) => {
        if (values[key] !== initialValues[key]) {
          acc[key] = values[key];
        }
        return acc;
      }, {});

      try {
        const response = await axios.put(`${process.env.REACT_APP_URL}/users/update`, {
          ...changedFields,
          userid: user?.userid,
          tenantid: userdata?.tenantid
        });

        if (response.data.status) {
          OpenToast(response.data.message, 'success', 1500);
          // You can navigate or refetch here if needed
          navigate('/users');
        } else {
          OpenToast(response.data.message, 'error', 1500);
        }
      } catch (err) {
        OpenToast(err.message, 'error', 1500);
      }
    }
  });

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

  const { data: riderShifts = [] } = useQuery({
    queryKey: ['userlist'],
    queryFn: getRiderShifts
  });

  if (loading) return <Loader />;

  return (
    <form onSubmit={formik.handleSubmit} noValidate>
      <Titlecard title="Edit User" />
      <MainCard sx={{}}>
        <Grid container spacing={2}>
          {Object.keys(defaultValues).map((fieldKey) => (
            <Grid item xs={12} sm={fieldKey === 'address' ? 12 : 6} key={fieldKey}>
              <InputLabel sx={{ mb: 1 }}>{fieldLabels[fieldKey]}</InputLabel>
              {fieldKey === 'shiftid' ? (
                <Autocomplete
                  options={riderShifts}
                  getOptionLabel={(option) => (option && option.shiftname ? `${option.shiftname} (${option.shifthours} hrs)` : '')}
                  value={riderShifts.find((opt) => opt.shiftid === formik.values.shiftid) || null}
                  onChange={(_, selected) => {
                    formik.setFieldValue('shiftid', selected?.shiftid || null);
                  }}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      fullWidth
                      placeholder="Select Rider Shift"
                      error={formik.touched.shiftid && Boolean(formik.errors.shiftid)}
                      helperText={formik.touched.shiftid && formik.errors.shiftid}
                    />
                  )}
                />
              ) : (
                <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
        direction={'row'}
        alignItems={'center'}
        justifyContent={'end'}
        sx={{
          position: 'sticky',
          bottom: 0,
          alignItems: 'flex-end',
          width: '100%',
          mt: 3,
          backgroundColor: 'border.light'
        }}
      >
        <Button
          startIcon={<ArrowLeftOutlined />}
          variant="contained"
          color="secondary"
          sx={{ width: 'auto', mx: 3, my: 1 }}
          onClick={() => navigate('/users')}
        >
          Back
        </Button>
        <Button type="submit" variant="contained" color="primary" disabled={!formChanged} sx={{ width: 'auto', mx: 3, my: 1 }}>
          Save Changes
        </Button>
      </Stack>
    </form>
  );
};

export default EditUsers;
