import React, { useState } from 'react';
import { Stack, Button, Chip, Grid, InputLabel, TextField, Typography } from '@mui/material';
import Titlecard from 'components/nearle_components/Titlecard';
import { ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import { useSelector } from 'react-redux';
import OpenToast from 'components/nearle_components/OpenToast';
import MainCard from 'components/MainCard';
import AddressAutocomplete from 'components/nearle_components/AddressAutocomplete';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { TimePicker } from '@mui/x-date-pickers/TimePicker';
import dayjs from 'dayjs';
import axios from 'axios';

const CreateLocation = () => {
  const navigate = useNavigate();
  const userdata = useSelector((state) => state.userinfo.userdata);
  const [opentime, setOpentime] = useState(dayjs('09:00 AM', 'hh:mm A'));
  const [closetime, setClosetime] = useState(dayjs('11:00 PM', 'hh:mm A'));

  const initialValues = {
    locationname: '',
    email: '',
    contactno: '',
    address: '',
    suburb: '',
    city: '',
    state: '',
    postcode: '',
    latitude: '',
    longitude: '',
    opentime: opentime,
    closetime: closetime,
    tenantid: +userdata?.tenantid || 0,
    applocationid: +userdata?.applocationid || 0,
    moduleid: +userdata?.moduleid || 0
  };
  const validationSchema = Yup.object({
    locationname: Yup.string().required('Required'),
    contactno: Yup.string()
      .required('Required')
      .matches(/^\d+$/, 'Only numbers are allowed')
      .min(10, 'Contact number must  10 digits')
      .max(10, 'Contact number must be  10 digits'),
    email: Yup.string().email('Invalid email').required('Required'),
    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').matches(/^\d+$/, 'Only numbers are allowed'),
    latitude: Yup.string()
      .required('Latitude required')
      .matches(/^-?\d+(\.\d+)?$/, 'Must Enter be a valid latitude'),
    longitude: Yup.string()
      .required('Longitude required')
      .matches(/^-?\d+(\.\d+)?$/, 'Must Enter be a valid longitude'),
    opentime: Yup.string().required('Opentime is required'),
    closetime: Yup.string().nullable().required('Closetime required')
  });

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

  const handleAddressSelect = (data) => {
    console.log('handleAddressSelect', 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);
    formik.setFieldValue('latitude', data?.latitude);
    formik.setFieldValue('longitude', data?.longitude);
  };

  return (
    <Stack>
      <form onSubmit={formik.handleSubmit} noValidate>
        <Titlecard title="Create Location">
          <Chip
            variant="outlined"
            color="secondary"
            size="large"
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate('/locations')}
            label={'Back'}
          />
          <Button type="submit" variant="contained" color="primary" startIcon={<PlusOutlined />}>
            Create
          </Button>
        </Titlecard>
        <MainCard>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>Location Name</InputLabel>
              <TextField
                name="locationname"
                placeholder="Enter Product name"
                fullWidth
                value={formik.values.locationname}
                onChange={formik.handleChange}
                error={formik.touched.locationname && Boolean(formik.errors.locationname)}
                helperText={formik.touched.locationname && formik.errors.locationname}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>Contact Number</InputLabel>
              <TextField
                name="contactno"
                type="number"
                placeholder="Enter Contact Number "
                fullWidth
                value={formik.values.contactno}
                // onChange={formik.handleChange}
                onChange={(e) => {
                  formik.setFieldValue('contactno', e.target.value.toString());
                }}
                error={formik.touched.contactno && Boolean(formik.errors.contactno)}
                helperText={formik.touched.contactno && formik.errors.contactno}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>Email</InputLabel>
              <TextField
                name="email"
                placeholder="Enter Email Id"
                fullWidth
                value={formik.values.email}
                onChange={formik.handleChange}
                error={formik.touched.email && Boolean(formik.errors.email)}
                helperText={formik.touched.email && formik.errors.email}
              />
            </Grid>
            <Grid item xs={12} sm={12}>
              <InputLabel sx={{ mb: 1 }}>Address</InputLabel>
              <AddressAutocomplete onSelect={handleAddressSelect} />
              {formik.touched.address && formik.errors.address && (
                <Typography variant="caption" color="error">
                  {formik.errors.address}
                </Typography>
              )}
            </Grid>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>Location</InputLabel>
              <TextField
                name="suburb"
                placeholder="Enter Location"
                fullWidth
                value={formik.values.suburb}
                onChange={formik.handleChange}
                error={formik.touched.suburb && Boolean(formik.errors.suburb)}
                helperText={formik.touched.suburb && formik.errors.suburb}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>City</InputLabel>
              <TextField
                name="city"
                placeholder="Enter City "
                fullWidth
                value={formik.values.city}
                onChange={formik.handleChange}
                error={formik.touched.city && Boolean(formik.errors.city)}
                helperText={formik.touched.city && formik.errors.city}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>State</InputLabel>
              <TextField
                name="state"
                placeholder="Enter State "
                fullWidth
                value={formik.values.state}
                onChange={formik.handleChange}
                error={formik.touched.state && Boolean(formik.errors.state)}
                helperText={formik.touched.state && formik.errors.state}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>PostCode</InputLabel>
              <TextField
                name="postcode"
                type="number"
                placeholder="Enter PostCode "
                fullWidth
                value={formik.values.postcode}
                // onChange={formik.handleChange}
                onChange={(e) => {
                  formik.setFieldValue('postcode', e.target.value.toString());
                }}
                error={formik.touched.postcode && Boolean(formik.errors.postcode)}
                helperText={formik.touched.postcode && formik.errors.postcode}
              />
            </Grid>

            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>Latitude</InputLabel>
              <TextField
                name="latitude"
                type="number"
                placeholder="Enter Latitude "
                fullWidth
                value={formik.values.latitude}
                // onChange={formik.handleChange}
                onChange={(e) => {
                  formik.setFieldValue('latitude', e.target.value.toString());
                }}
                error={formik.touched.latitude && Boolean(formik.errors.latitude)}
                helperText={formik.touched.latitude && formik.errors.latitude}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <InputLabel sx={{ mb: 1 }}>Longitude</InputLabel>
              <TextField
                name="longitude"
                type="number"
                placeholder="Enter Longitude "
                fullWidth
                value={formik.values.longitude}
                // onChange={formik.handleChange}
                onChange={(e) => {
                  formik.setFieldValue('longitude', e.target.value.toString());
                }}
                error={formik.touched.longitude && Boolean(formik.errors.longitude)}
                helperText={formik.touched.longitude && formik.errors.longitude}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <InputLabel sx={{ mb: 1 }}>Opentime</InputLabel>
              <LocalizationProvider dateAdapter={AdapterDayjs}>
                <TimePicker
                  sx={{ width: '100%' }}
                  value={formik.values.opentime || ''}
                  onChange={(newValue) => {
                    if (newValue) {
                      const formatted = dayjs(newValue).format('hh:mm A');
                      console.log('open formatted', formatted);
                      setOpentime(formatted);
                    }
                  }}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      name="opentime"
                      fullWidth
                      error={formik.touched.opentime && Boolean(formik.errors.opentime)}
                      helperText={formik.touched.opentime && formik.errors.opentime}
                    />
                  )}
                />
              </LocalizationProvider>
            </Grid>

            <Grid item xs={12} sm={6}>
              <InputLabel sx={{ mb: 1 }}>Closetime</InputLabel>
              <LocalizationProvider dateAdapter={AdapterDayjs}>
                <TimePicker
                  sx={{ width: '100%' }}
                  value={formik.values.closetime || ''}
                  onChange={(newValue) => {
                    if (newValue) {
                      const formatted = dayjs(newValue).format('hh:mm A');
                      console.log('close formatted', formatted);
                      setClosetime(formatted);
                    }
                  }}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      name="closetime"
                      fullWidth
                      error={formik.touched.closetime && Boolean(formik.errors.closetime)}
                      helperText={formik.touched.closetime && formik.errors.closetime}
                    />
                  )}
                />
              </LocalizationProvider>
            </Grid>
          </Grid>
        </MainCard>
      </form>
    </Stack>
  );
};

export default CreateLocation;
