import {
    Button,
    Icon,
    Grid,
    Radio,
    RadioGroup,
    FormControlLabel,
    Checkbox,
    Box,
    Divider,
    Typography,
    Slide,
    MenuItem,
    Switch,
} from '@mui/material'
import { styled } from '@mui/system'
import React, { useState, useEffect } from 'react'
import {
    ValidatorForm,
    TextValidator,
    SelectValidator,
} from 'react-material-ui-form-validator'
import { useNavigate, useParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { themeColors } from 'app/components/MatxTheme/themeColors'
import mediaService from 'app/services/istar/MediaService'
import CompanyService from 'app/services/istar/CompanyService'
import { SketchPicker } from 'react-color'
import CompanyUserService from 'app/services/istar/CompanyUserService'

const S3URL = 'https://istar-bucket.s3.ap-southeast-2.amazonaws.com/'

const TextField = styled(TextValidator)(() => ({
    width: '100%',
    marginBottom: '16px',
}))

const Form = () => {
    const navigate = useNavigate()
    const { id } = useParams()
    const [state, setState] = useState({
        keoskMode: false,
    })
    const [error, setError] = React.useState('')
    const [open, setOpen] = React.useState(false)
    const [selectedImage, setSelectedImage] = React.useState(null)
    const [colorSelected, setColorSelected] = React.useState('')
    const [companies, setCompanies] = React.useState([])

    const handleClickOpen = () => {
        setOpen(true)
    }

    const handleClose = () => {
        setOpen(false)
    }

    React.useEffect(() => {
        if (id) {
            CompanyUserService.getSingleRecord(id)
                .then((res) => {
                    console.log(res)
                    setState(res)
                })
                .catch((err) => {
                    toast.error(err?.message?.data?.message)
                })
        }
    }, [id])

    React.useEffect(() => {
        CompanyService.getAllRecords().then((res) => {
            setCompanies(res)
        })
    }, [])

    const handleSubmit = async (event) => {
        console.log('STATE:', state)
        try {
            if (id) {
                CompanyUserService.updateRecord(id, {
                    name,
                    email,
                    password,
                    company,
                    phoneNumber,
                    country,
                    keoskMode,
                })
                    .then((record) => {
                        console.log('record: ', record)
                        toast.success('Data Saved')
                        navigate('/admin/company-users/all')
                    })
                    .catch((err) => {
                        console.log('ERR : ', err)
                        toast.error(error)
                    })
            } else {
                CompanyUserService.addRecord({
                    name,
                    email,
                    password,
                    company,
                    phoneNumber,
                    country,
                    keoskMode,
                })
                    .then((record) => {
                        console.log('record: ', record)
                        toast.success('Data Saved')
                        navigate('/admin/company-users/all')
                    })
                    .catch((err) => {
                        console.log('ERR : ', err)
                        toast.error(error)
                    })
            }
        } catch (error) {
            console.log(error)
            toast.error(error)
        }
    }

    const handleChange = (event) => {
        event.preventDefault()
        setState({
            ...state,
            [event.target.name]: event.target.value,
        })
    }

    const { name, email, password, company, phoneNumber, country, keoskMode } =
        state

    return (
        <div>
            <Typography className="mb-4 center" style={{ color: '#e30505' }}>
                {error}
            </Typography>
            <ValidatorForm onSubmit={handleSubmit} onError={() => null}>
                <Grid container spacing={2}>
                    <Grid item lg={6} md={6} sm={12} xs={12}>
                        <TextField
                            label="Name"
                            onChange={handleChange}
                            type="text"
                            name="name"
                            variant="outlined"
                            value={name || ''}
                            validators={['required']}
                            errorMessages={['this field is required']}
                        />
                    </Grid>
                    <Grid item lg={6} md={6} sm={12} xs={12}>
                        <TextField
                            label="Email"
                            onChange={handleChange}
                            type="text"
                            name="email"
                            variant="outlined"
                            value={email || ''}
                            validators={['required']}
                            errorMessages={['this field is required']}
                        />
                    </Grid>
                    <Grid item lg={6} md={6} sm={12} xs={12}>
                        <TextField
                            label="Phone Number"
                            onChange={handleChange}
                            type="number"
                            name="phoneNumber"
                            variant="outlined"
                            value={phoneNumber || ''}
                            validators={['required']}
                            errorMessages={['this field is required']}
                        />
                    </Grid>
                    {!id && (
                        <Grid item lg={6} md={6} sm={12} xs={12}>
                            <TextField
                                label="Password"
                                onChange={handleChange}
                                type="password"
                                name="password"
                                variant="outlined"
                                value={password || ''}
                                validators={['required']}
                                errorMessages={['this field is required']}
                            />
                        </Grid>
                    )}

                    <Grid item lg={6} md={6} sm={12} xs={12}>
                        <SelectValidator
                            required
                            value={country || ''}
                            label="Country"
                            onChange={handleChange}
                            name="country"
                            variant="outlined"
                            style={{ width: '100%' }}
                        >
                            <MenuItem key="uk" value="United States">
                                United States
                            </MenuItem>
                            <MenuItem key="australia" value="Australia">
                                Australia
                            </MenuItem>
                        </SelectValidator>
                    </Grid>
                    <Grid item lg={6} md={6} sm={12} xs={12}>
                        <SelectValidator
                            required
                            value={company || ''}
                            label="Company"
                            onChange={handleChange}
                            name="company"
                            variant="outlined"
                            style={{ width: '100%' }}
                        >
                            {companies.map((c, index) => (
                                <MenuItem key={index} value={c._id}>
                                    {c.name}
                                </MenuItem>
                            ))}
                        </SelectValidator>
                    </Grid>
                    <Grid item lg={6} md={6} sm={12} xs={12}>
                        <FormControlLabel
                            control={
                                <Checkbox
                                    checked={keoskMode}
                                    onChange={(e) => {
                                        setState({
                                            ...state,
                                            [e.target.name]: e.target.checked,
                                        })
                                    }}
                                    name="keoskMode"
                                />
                            }
                            label={
                                keoskMode
                                    ? 'Keosek Mode Enable! Unheckbox to make it disable'
                                    : 'Keosek Mode Disable! Checkbox to make it enable'
                            }
                        />
                        {/* <Switch
                            name="keoskMode"
                            color="primary"
                            checked={keoskMode}
                            value={keoskMode}
                            onChange={(e) => {
                                setState({
                                    ...state,
                                    [e.target.name]: e.target.checked,
                                })
                            }}
                        /> */}
                    </Grid>
                </Grid>

                <Box mt={3}>
                    <Button color="primary" variant="contained" type="submit">
                        <Icon>send</Icon>
                        <span className="pl-2 capitalize">Submit</span>
                    </Button>
                </Box>
            </ValidatorForm>
        </div>
    )
}

export default Form
