import React, { useEffect } from 'react';
import { Grid, TextField, MenuItem, Button, Stack, Typography, Autocomplete } from '@mui/material';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import AddressAutocomplete from 'components/nearle_components/AddressAutocomplete';
import { useSelector } from 'react-redux';
import axios from 'axios';
import OpenToast from 'components/nearle_components/OpenToast';
import Titlecard from 'components/nearle_components/Titlecard';
import MainCard from 'components/MainCard';
import { useNavigate } from 'react-router';
import { useTheme } from '@mui/material/styles';
import { useQuery } from '@tanstack/react-query';
import { getRiderShifts } from '../api/api';

const roles = [
  { label: 'Staff', value: 2, configid: 1 },
  { label: 'Delivery', value: 3, configid: 6 }
];
const CreateUsers = () => {
  const userdata = useSelector((state) => state.userinfo.userdata);
  const navigate = useNavigate();
  const theme = useTheme();

  const initialValues = {
    firstname: '',
    contactno: '',
    email: '',
    authname: '',
    roleid: '',
    shiftid: '',
    address: '',
    suburb: '',
    city: '',
    state: '',
    postcode: '',
    tenantid: +userdata?.tenantid || 0,
    locationid: +userdata?.locationid || 0,
    applocationid: +userdata?.applocationid || 0,
    moduleid: +userdata?.moduleid || 0
  };

  const validationSchema = Yup.object({
    firstname: Yup.string().required('Required'),
    contactno: Yup.string()
      .required('Required')
      .matches(/^\d{10}$/, 'Contact number must be exactly 10 digits'),
    email: Yup.string().email('Invalid email').required('Required'),
    roleid: Yup.number().required('Select a role'),
    shiftid: Yup.number().required('Select Riders Shift'),
    // shiftid: Yup.number().when('roleid', {
    //   is: 3,
    //   then: (schema) => schema.required('Select Riders Shift'),
    //   otherwise: (schema) => schema.notRequired()
    // }),
    address: Yup.string().required('Address required'),
    suburb: Yup.string().required('Suburb required'),
    city: Yup.string().required('City required'),
    state: Yup.string().required('State required'),
    postcode: Yup.string().required('Postcode required')
  });

  const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit: async (values) => {
      console.log('Submitted values:', values);
      try {
        const createUserRes = await axios.post(`${process.env.REACT_APP_URL2}/users/create`, values);
        if (createUserRes.data.status) {
          console.log('createUserRes', createUserRes.data.message);
          OpenToast(createUserRes.data.message, 'success', 1500);
          navigate('/users');
        } else {
          OpenToast(createUserRes.data.message, 'error', 1500);
        }
      } catch (err) {
        console.log('createUserRes', err.message);
        OpenToast(err.message, 'error', 1500);
      }
    }
  });

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

  const handleAddressSelect = (data) => {
    console.log('address data',data)
    if (!data || !data.address) return;
    formik.setFieldValue('address', data?.address);
    formik.setFieldValue('suburb', data?.suburb);
    formik.setFieldValue('city', data?.city);
    formik.setFieldValue('state', data?.state);
    formik.setFieldValue('postcode', data?.postcode);
  };
  // Sync authname to email automatically
  useEffect(() => {
    if (formik.values.email !== formik.values.authname) {
      formik.setFieldValue('authname', formik.values.email);
    }
  }, [formik.values.email]);

  return (
    <form onSubmit={formik.handleSubmit} noValidate>
      <Titlecard title="Create User"></Titlecard>
      <MainCard sx={{ maxHeight: 'calc(100vh - 150px)', overflowY: 'scroll' }}>
        <Grid container spacing={3} sx={{ p: 2 }}>
          {/* Basic Inputs */}
          {['firstname', 'contactno', 'email'].map((field) => (
            <Grid item xs={12} sm={6} key={field}>
              <TextField
                fullWidth
                label={field.charAt(0).toUpperCase() + field.slice(1)}
                type={field === 'password' ? 'password' : 'text'}
                name={field}
                value={formik.values[field]}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                error={formik.touched[field] && Boolean(formik.errors[field])}
                helperText={formik.touched[field] && formik.errors[field]}
              />
            </Grid>
          ))}

          {/* Role Dropdown */}
          <Grid item xs={12} sm={6}>
            <TextField
              select
              fullWidth
              label="Role"
              name="roleid"
              value={formik.values.roleid}
              onChange={(e) => {
                const value = e.target.value;
                console.log(value);
                formik.setFieldValue('roleid', value);
                formik.setFieldValue('configid', value == 2 ? 1 : 6);
              }}
              onBlur={formik.handleBlur}
              error={formik.touched.roleid && Boolean(formik.errors.roleid)}
              helperText={formik.touched.roleid && formik.errors.roleid}
            >
              {roles.map((role) => (
                <MenuItem key={role.value} value={role.value}>
                  {role.label}
                </MenuItem>
              ))}
            </TextField>
          </Grid>

          <Grid item xs={12}>
            <Autocomplete
              fullWidth
              name="Ridershifts"
              options={riderShifts || []}
              getOptionLabel={(option) => {
                return `${option.shiftname} -  (${option.shifthours} hrs)` || '';
              }}
              noOptionsText="No shifts found, contact admin"
              onChange={(_, shift) => {
                formik.setFieldValue('shiftid', shift.shiftid);
                formik.setFieldValue('shiftname', shift.shiftname);
                formik.setFieldValue('basefare', shift.basefare);
                formik.setFieldValue('additionalkm', shift.additionalkm);
                formik.setFieldValue('starttime', shift.starttime);
                formik.setFieldValue('endtime', shift.endtime);
                console.log(shift);
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  placeholder="Select Rider Shift"
                  error={formik.touched.shiftid && Boolean(formik.errors.shiftid)}
                  helperText={formik.touched.shiftid && formik.errors.shiftid}
                />
              )}
            />
          </Grid>

          {/* Google Address Autocomplete */}

          <Grid item xs={12}>
            <AddressAutocomplete onSelect={handleAddressSelect} />
            {formik.touched.address && formik.errors.address && (
              <Typography variant="caption" color="error">
                {formik.errors.address}
              </Typography>
            )}
          </Grid>

          {/* Auto-filled fields from Autocomplete */}
          {['suburb', 'city', 'state', 'postcode']?.map((field) => (
            <Grid item xs={12} sm={6} key={field} sx={{ overflowY: 'hidden' }}>
              <TextField
                fullWidth
                label={field.charAt(0).toUpperCase() + field.slice(1)}
                name={field}
                value={formik.values[field]}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                error={formik.touched[field] && Boolean(formik.errors[field])}
                helperText={formik.touched[field] && formik.errors[field]}
              />
            </Grid>
          ))}
        </Grid>
      </MainCard>
      <Stack
        direction="row"
        justifyContent="flex-end"
        spacing={2}
        sx={{
          backgroundColor: `white`,
          p: 2,
          position: 'sticky',
          bottom: 0,
          zIndex: 10,
          py: 2,
          mt: 1,
          border: `1.5px solid ${theme.palette.divider}`
        }}
      >
        <Button variant="contained" color="secondary" onClick={() => navigate('/users')}>
          Back
        </Button>
        <Button type="submit" variant="contained">
          Create User
        </Button>
      </Stack>
    </form>
  );
};

export default CreateUsers;
