import {
    Button,
    Icon,
    Grid,
    Radio,
    RadioGroup,
    FormControlLabel,
    Checkbox,
    Box,
    Divider,
    Typography,
    Slide,
    MenuItem,
    Table,
    TableHead,
    TableRow,
    TableCell,
    TableBody,
} from '@mui/material'
import { styled } from '@mui/system'
import CompanyService from 'app/services/istar/CompanyService'
import QuestionService from 'app/services/istar/QuestionService'
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'

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

const Form = () => {
    const navigate = useNavigate()
    const { id } = useParams()
    const [state, setState] = useState({ options: [] })
    const [error, setError] = React.useState('')
    const [open, setOpen] = React.useState(false)
    const [companies, setCompanies] = React.useState([])
    const [newOption, setNewOption] = React.useState({})
    const [allQuestions, setAllQuestions] = React.useState([])
    const [oneQuestion, setOneQuestion] = React.useState({})

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

    React.useEffect(() => {
        if (id) {
            QuestionService.getSingleRecord(id).then((res) => {
                setOneQuestion(res)
                setState({
                    ...state,
                    question: res.question,
                    company: res.company,
                    options: res.answers,
                })
            })
        }
    }, [id])

    React.useEffect(() => {
        if (state.company) {
            QuestionService.getCompanyQuestions({
                companyId: state.company,
            })
                .then((res) => {
                    console.log('RES: ', res)
                    setAllQuestions(res)
                })
                .catch((err) => console.log('ERR: ', err))
        }
    }, [state.company])

    const handleSubmit = async (event) => {
        console.log('STATE: ', state)
        if (state.options.length <= 0) {
            setError(
                'Please press add button to add answer and there should be atleast one answer'
            )
            return
        }
        setError('')
        try {
            if (id) {
                QuestionService.updateRecord(id, {
                    question: state.question,
                    answers: state.options,
                    company,
                })
                    .then((record) => {
                        console.log('record: ', record)
                        toast.success('Data Saved')
                        navigate('/admin/questions/all')
                    })
                    .catch((err) => {
                        console.log('ERR : ', err)
                        toast.error(error)
                    })
            } else {
                QuestionService.addRecord({
                    question: state.question,
                    answers: state.options,
                    company,
                })
                    .then((record) => {
                        console.log('record: ', record)
                        toast.success('Data Saved')
                        navigate('/admin/questions/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 { question, company } = 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="Question"
                            onChange={handleChange}
                            type="text"
                            name="question"
                            variant="outlined"
                            value={question || ''}
                            validators={['required']}
                            errorMessages={['this field is required']}
                        />
                    </Grid>
                    <Grid item lg={12} md={12} 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={12} md={12} sm={12} xs={12}>
                        <Grid container xs={12}>
                            <Table>
                                <TableHead>
                                    <TableRow>
                                        <TableCell>Answer</TableCell>
                                        <TableCell>Link Question</TableCell>
                                        <TableCell>Actions</TableCell>
                                    </TableRow>
                                </TableHead>
                                <TableBody>
                                    <TableRow>
                                        <TableCell>
                                            <TextField
                                                label="Answer"
                                                onChange={(e) => {
                                                    setNewOption({
                                                        ...newOption,
                                                        title: e.target.value,
                                                    })
                                                }}
                                                type="text"
                                                name="title"
                                                variant="outlined"
                                                value={newOption.title}
                                                // validators={['required']}
                                                // errorMessages={[
                                                //     'this field is required',
                                                // ]}
                                            />

                                            {/* <TextField
                                                fullWidth
                                                value={newOption.title}
                                                onChange={(e) => {
                                                    setNewOption({
                                                        ...newOption,
                                                        title: e.target.value,
                                                    })
                                                }}
                                            /> */}
                                        </TableCell>
                                        <TableCell>
                                            <SelectValidator
                                                // required
                                                value={
                                                    newOption.linkQuestion || ''
                                                }
                                                label="linkQuestion"
                                                onChange={(e) => {
                                                    setNewOption({
                                                        ...newOption,
                                                        linkQuestion:
                                                            e.target.value,
                                                    })
                                                }}
                                                name="linkQuestion"
                                                variant="outlined"
                                                style={{ width: '100%' }}
                                            >
                                                {allQuestions.map(
                                                    (c, index) => (
                                                        <MenuItem
                                                            key={index}
                                                            value={c._id}
                                                        >
                                                            {c.question}
                                                        </MenuItem>
                                                    )
                                                )}

                                                {/* <MenuItem key="1" value="1">
                                                    ONE
                                                </MenuItem> */}
                                            </SelectValidator>
                                        </TableCell>
                                        <TableCell>
                                            <Button
                                                variant="contained"
                                                color="primary"
                                                onClick={(e) => {
                                                    setState({
                                                        ...state,
                                                        options: [
                                                            newOption,
                                                            ...state.options,
                                                        ],
                                                    })
                                                }}
                                            >
                                                Add
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                    {state.options.map((option, index) => (
                                        <TableRow key={index}>
                                            <TableCell>
                                                {option.title}
                                            </TableCell>
                                            <TableCell>
                                                {option.linkQuestion}
                                            </TableCell>
                                            <TableCell>
                                                <Button
                                                    variant="contained"
                                                    color="secondary"
                                                    onClick={(e) => {
                                                        let newOptions = [
                                                            ...state.options,
                                                        ]
                                                        newOptions.splice(
                                                            index,
                                                            1
                                                        )
                                                        setState({
                                                            ...state,
                                                            options: newOptions,
                                                        })
                                                    }}
                                                >
                                                    Delete
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </Grid>
                    </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
