import * as React from 'react';
import Grid from '@mui/material/Grid';
import { Button, Container, Dialog, DialogActions, DialogContent, DialogTitle, TextField, Typography } from '@mui/material';
import MUIDataTable from "mui-datatables";
import { useAxios } from './axios';
import { useMutation, useQuery, useQueryClient } from 'react-query';


function StudentDialog({
    open,
    onClose,
    student,
}) {
    const client = useAxios();
    const queryClient = useQueryClient()

    const [uid, setUid] = React.useState(student ? student.uid : null);
    const [firstName, setFirstName] = React.useState(student['first_name'] ?? '');
    const [lastName, setLastName] = React.useState(student['last_name'] ?? '');
    const [middleName, setMiddleName] = React.useState(student['middle_name'] ?? '');
    const [discipline, setDiscipline] = React.useState(student['discipline'] ?? '');
    const [mark, setMark] = React.useState(student['mark'] ?? '');

    const commitCreate = useMutation(async (payload) => client.post('/api/students', payload), {
        onSuccess: () => {
            queryClient.invalidateQueries('students');
            onClose();
        }
    });

    const commitUpdate = useMutation(async (payload) => client.put(`/api/students/${student['uid']}`, payload), {
        onSuccess: () => {
            queryClient.invalidateQueries('students');
            queryClient.invalidateQueries(['student', student['uid']]);
            onClose();
        }
    });

    const handleFormSubmit = (event) => {
        event.preventDefault();
        const data = {
            first_name: firstName,
            last_name: lastName,
            middle_name: middleName,
            discipline: discipline,
            mark: mark,
        };
        if (student['uid']) {
            commitUpdate.mutate(data);
        }
        else {
            commitCreate.mutate(data);
        }
        onClose();
    };

    const loadData = () => {
        console.log(student);
        setUid(student['uid'] ?? null);
        setFirstName(student['first_name'] ?? '');
        setLastName(student['last_name'] ?? '');
        setMiddleName(student['middle_name'] ?? '');
        setDiscipline(student['discipline'] ?? '');
        setMark(student['mark'] ?? '');
    };

    return (
        <Dialog
            open={open}
            onClose={onClose}
            fullWidth
            maxWidth="md"
            TransitionProps={{
                onEnter: loadData
            }}
        >
            <DialogTitle>Студент</DialogTitle>
            <form onSubmit={handleFormSubmit}>
                <DialogContent dividers>
                    <Grid container spacing={3}>
                        <Grid item xs={12}>
                            <TextField
                                id="first_name"
                                label="Имя"
                                value={firstName}
                                onChange={(event) => setFirstName(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                id="last_name"
                                label="Фамилия"
                                value={lastName}
                                onChange={(event) => setLastName(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                id="middle_name"
                                label="Отчество"
                                value={middleName}
                                onChange={(event) => setMiddleName(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                id="discipline"
                                label="Дисциплина"
                                value={discipline}
                                onChange={(event) => setDiscipline(event.target.value)}
                                fullWidth
                                required
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                id="mark"
                                label="Оценка"
                                value={mark}
                                onChange={(event) => setMark(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                    </Grid>
                </DialogContent>
                <DialogActions>
                    <Button onClick={onClose}>Отмена</Button>
                    <Button type="submit" color="primary">Сохранить</Button>
                </DialogActions>

            </form>

        </Dialog>
    );
}
export default StudentDialog;
