import {
    Button,
    Icon,
    Grid,
    Radio,
    RadioGroup,
    FormControlLabel,
    Checkbox,
    Box,
    Divider,
    Typography,
    Slide,
    MenuItem,
    FormLabel,
    InputLabel,
} from '@mui/material'
import { styled } from '@mui/system'
import React, { useState, useEffect } from 'react'
import { ValidatorForm, TextValidator } 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'

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({})
    const [error, setError] = React.useState('')
    const [open, setOpen] = React.useState(false)
    const [selectedImage, setSelectedImage] = React.useState(null)
    const [colorSelectedOne, setColorSelectedOne] = React.useState('')
    const [colorSelectedTwo, setColorSelectedTwo] = React.useState('')
    const [company, setCompany] = React.useState({})

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

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

    React.useEffect(() => {
        if (id) {
            CompanyService.getSingleRecord(id).then((res) => {
                console.log('RES: ', id, res)
                setState({
                    ...state,
                    name: res?.name,
                    email: res?.email,
                    logo: res?.logo,
                })
                setColorSelectedOne(res?.colorOne)
                setColorSelectedTwo(res?.colorTwo)
                setCompany(res)
            })
        }
    }, [id])

    function bytesToSize(bytes) {
        var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
        if (bytes == 0) return '0 Byte'
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)))
        return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]
    }

    const handleFileChange = (e) => {
        if (e.target.files[0].size > 2097152) {
            // alert("File size should be less than 2mb");
            setError('File size should be less than 2mb')
        } else {
            setError('')
            setState({
                ...state,
                [e.target.name]: e.target.files[0],
            })
        }
    }

    const handleSubmit = async (event) => {
        console.log('STATE: ', state)
        if (!state.logo) {
            setError('Logo is required')
            toast.error('Logo is required')
            return
        }

        if (!colorSelectedOne) {
            setError('Select Colors')
            toast.error('Select Colors')
            return
        }
        if (!colorSelectedTwo) {
            setError('Select Colors')
            toast.error('Select Colors')
            return
        }
        setError('')
        try {
            if (id) {
                let logoKey = null
                if (state.logo != company.logo) {
                    logoKey = await mediaService.uploadMedia(state.logo)
                } else {
                    logoKey = company.logo
                }
                CompanyService.updateRecord(id, {
                    name: state.name,
                    email: state.email,
                    colorOne: colorSelectedOne.hex,
                    colorTwo: colorSelectedTwo.hex,
                    logo: S3URL + logoKey,
                })
                    .then((record) => {
                        console.log('record: ', record)
                        toast.success('Data Saved')
                        navigate('/admin/companies/all')
                    })
                    .catch((err) => {
                        console.log('ERR : ', err)
                        toast.error(error)
                    })
                return
            } else {
                let logoKey = await mediaService.uploadMedia(state.logo)
                console.log('LOGOKEY:', logoKey)
                CompanyService.addRecord({
                    name: state.name,
                    email: state.email,
                    colorOne: colorSelectedOne.hex,
                    colorTwo: colorSelectedTwo.hex,
                    logo: S3URL + logoKey,
                })
                    .then((record) => {
                        console.log('record: ', record)
                        toast.success('Data Saved')
                        navigate('/admin/companies/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, logo, colorOne, icon } = 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={12} md={12} 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={12} md={12} 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}>
                        <InputLabel>
                            <b>Color One</b>
                        </InputLabel>
                        <SketchPicker
                            color={colorSelectedOne}
                            onChangeComplete={(colorvalue) => {
                                // console.log('colorvalue: ', colorvalue)
                                setColorSelectedOne(colorvalue)
                            }}
                        />
                    </Grid>
                    <Grid item lg={6} md={6} sm={12} xs={12}>
                        <InputLabel>
                            <b>Color Two</b>
                        </InputLabel>
                        <SketchPicker
                            color={colorSelectedTwo}
                            onChangeComplete={(colorvalue) => {
                                // console.log('colorvalue: ', colorvalue)
                                setColorSelectedTwo(colorvalue)
                            }}
                        />
                    </Grid>
                    <Grid item lg={12} md={12} sm={12} xs={12}>
                        <label htmlFor="icon">
                            <input
                                accept="image/*"
                                id="icon"
                                name="logo"
                                style={{ display: 'none' }}
                                type="file"
                                onChange={handleFileChange}
                            />
                            <Button
                                style={{ width: '100%' }}
                                color="primary"
                                variant="outlined"
                                component="span"
                            >
                                Upload Logo
                            </Button>
                        </label>
                        {logo && logo.name ? (
                            <a
                                onClick={() => {
                                    setSelectedImage(URL.createObjectURL(logo))
                                    handleClickOpen()
                                }}
                            >
                                {logo.name +
                                    ' (' +
                                    bytesToSize(logo.size) +
                                    ')'}
                            </a>
                        ) : logo ? (
                            <a
                                onClick={() => {
                                    setSelectedImage(logo)
                                    handleClickOpen()
                                }}
                            >
                                {logo}
                            </a>
                        ) : null}
                    </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>
            {/* <ViewImage
                onClose={handleClose}
                selectedImage={selectedImage}
                open={open}
            /> */}
        </div>
    )
}

export default Form
