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 ContactDialog({
    open,
    onClose,
    contact,
}) {
    const client = useAxios();
    const queryClient = useQueryClient()

    const [uid, setUid] = React.useState(contact ? contact.uid : null);
    const [firstName, setFirstName] = React.useState(contact['first_name'] ?? '');
    const [lastName, setLastName] = React.useState(contact['last_name'] ?? '');
    const [middleName, setMiddleName] = React.useState(contact['middle_name'] ?? '');
    const [telephone, setTelephone] = React.useState(contact['telephone'] ?? '');
    const [street, setStreet] = React.useState(contact['street'] ?? '');
    const [build, setBuild] = React.useState(contact['build'] ?? '');
    const [buildK, setBuildK] = React.useState(contact['build_k'] ?? '');
    const [apartment, setApartment] = React.useState(contact['apartment'] ?? '');

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

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

    const handleFormSubmit = (event) => {
        event.preventDefault();
        const data = {
            first_name: firstName,
            last_name: lastName,
            middle_name: middleName,
            telephone: telephone,
            street: street,
            build: build,
            build_k: buildK,
            apartment: apartment
        };
        if (contact['uid']) {
            commitUpdate.mutate(data);
        }
        else {
            commitCreate.mutate(data);
        }
        onClose();
    };

    const loadData = () => {
        console.log(contact);
        setUid(contact['uid'] ?? null);
        setFirstName(contact['first_name'] ?? '');
        setLastName(contact['last_name'] ?? '');
        setMiddleName(contact['middle_name'] ?? '');
        setTelephone(contact['telephone'] ?? '');
        setStreet(contact['street'] ?? '');
        setBuild(contact['build'] ?? '');
        setBuildK(contact['build_k'] ?? '');
        setApartment(contact['apartment'] ?? '');
    };

    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="telephone"
                                label="Телефон"
                                value={telephone}
                                onChange={(event) => setTelephone(event.target.value)}
                                fullWidth
                                required
                            />
                        </Grid>
                        <Grid item xs={6}>
                            <TextField
                                id="street"
                                label="Улица"
                                value={street}
                                onChange={(event) => setStreet(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={2}>
                            <TextField
                                id="build"
                                label="Дом"
                                value={build}
                                onChange={(event) => setBuild(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={2}>
                            <TextField
                                id="build_k"
                                label="Корпус"
                                value={buildK}
                                onChange={(event) => setBuildK(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={2}>
                            <TextField
                                id="apartment"
                                label="Квартира"
                                value={apartment}
                                onChange={(event) => setApartment(event.target.value)}
                                fullWidth
                            />
                        </Grid>
                    </Grid>
                </DialogContent>
                <DialogActions>
                    <Button onClick={onClose}>Отмена</Button>
                    <Button type="submit" color="primary">Сохранить</Button>
                </DialogActions>

            </form>

        </Dialog>
    );
}
export default ContactDialog;
