import React, { useEffect, useState } from 'react'
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Button,
  InputAdornment,
  Box,
  Grid,
  FormControl,
  InputLabel,
  Select,
  OutlinedInput,
  MenuItem
} from '@mui/material'


const IpConfig = ({ open, onClose }) => {

  const [localIp, setLocalIp] = useState("");
  const [formData, setFormData] = useState({
    ipname: "",
    id: '',
  })
  const [ip, setIp] = useState({});

  useEffect(() => {

    window.notesysteme.getIPConfig().then((response) => {
      setIp(response)
    })

    const getLocalIP = async () => {
      const pc = new RTCPeerConnection();
      pc.createDataChannel(""); // Create a data channel
      pc.createOffer().then((offer) => pc.setLocalDescription(offer));

      pc.onicecandidate = (event) => {
        if (event && event.candidate) {
          const ipRegex = /([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})/;
          const match = ipRegex.exec(event.candidate.candidate);
          if (match) setLocalIp(match[1]);
          pc.close();
        }
      };
    };

    getLocalIP();
  }, []);

  useEffect(() => {
    if (ip) {
      setFormData((prevData) => ({
        ...prevData,
        ipname: ip.ipname,
        id: ip.id
      }))
    }

  }, [ip]);

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData({ ...formData, [name]: value })
  }

  const formSubmit = async (e) => {
    e.preventDefault()

    if (ip == undefined) {
      let response = await window.notesysteme.createIPConfig(formData)
      console.log('running the creation: ', response);
      if (response.changes) {
        window.notesysteme.getIPConfig().then((response) => {
          setIp(response)
        })
        onClose()
      }
    } else {
      let response = await window.notesysteme.updateIPConfig(formData)
      console.log('running the update: ', response);
      if (response.changes) {
        window.notesysteme.getIPConfig().then((response) => {
          setIp(response)
        })
        onClose()
      }
    }

  }

  return (
    <Dialog open={open} onClose={onClose}>
      <form action="" onSubmit={formSubmit}>
        <DialogTitle>Configuration de l'adresse IP</DialogTitle>
        <div style={{textAlign:"end"}}>Votre Local IP: {localIp || "Detecting..."}</div>
        <DialogContent>
          <Box sx={{ flexGrow: 1 }}>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={12}>
                <TextField
                  autoFocus
                  margin="dense"
                  name="ipname"
                  required
                  label="IP du PC serveur"
                  type="text"
                  fullWidth
                  variant="outlined"
                  value={formData.ipname}
                  color="warning"
                  onChange={handleChange}
                />
              </Grid>
            </Grid>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose} color="warning">
            Annuler
          </Button>
          <Button type="submit" color="warning">
            Soumettre
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  )
}

export default IpConfig
