// mui
import { Button, IconButton, Card, Stack, Typography, TextField, InputLabel } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { CardMembership, Visibility as VisibilityIcon } from '@mui/icons-material';
// components
import Iconify from '../../../components/Iconify';
import axios from '../../../utils/axios';
import { useContext, useEffect, useState } from 'react';
import { UserCurrentCorporateContext } from '../../../contexts/UserCurrentCorporate';
import { useParams } from 'react-router-dom';
import { Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import { enqueueSnackbar } from 'notistack';
import { fDate } from '../../../utils/formatTime';

export default function CardPersonalInformation({ data }) {
  /* const [data, setData] = useState(); */
  const [openDialog, setOpenDialog] = useState(false);
  const [editedData, setEditedData] = useState(null);
  const { id } = useParams();
  const [weight, setWeight] = useState(data?.last_weight_kg || '');
  const [height, setHeight] = useState(data?.last_height_cm || '');
  const [email, setEmail] = useState(data?.email || '');
  const [phone, setPhone] = useState(data?.phone || '');
  const [address, setAddress] = useState(data?.main_address_id || '');

  //Check Required
  const [nameField, setNameField] = useState('');
  const [weightField, setWeightField] = useState('');
  const [heightField, setHeightField] = useState('');
  const [emailField, setEmailField] = useState('');
  const [emailFieldCheck, setEmailFieldCheck] = useState(false);
  const [phoneField, setPhoneField] = useState('');

  const [nameFieldError, setNameFieldError] = useState('');
  const [weightFieldError, setWeightFieldError] = useState('');
  const [heightFieldError, setHeightFieldError] = useState('');
  const [emailFieldError, setEmailFieldError] = useState('');
  const [phoneFieldError, setPhoneFieldError] = useState('');

  useEffect(() => {
    // Periksa apakah data sudah terdefinisi
    if (data) {
      // Atur state sesuai dengan data yang diterima
      setNameField(data?.name || '');
      setWeightField((data?.last_weight_kg || '').toString());
      setHeightField((data?.last_height_cm || '').toString());
      setEmailField(data?.email || '');
      setEmailFieldCheck(isValidEmail(data?.email));
      setPhoneField(data?.phone || '');
    }
  }, [data]);

  const isValidEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const isRequiredFieldsFilled = () => {
    return nameField.trim() !== '' && weightField.trim() !== '' && heightField.trim() !== '' &&  emailField.trim() !== '' && emailFieldCheck && phoneField.trim() !== '';
  };


  const handleEditData = () => {
    setWeight(data?.last_weight_kg || '');
    setHeight(data?.last_height_cm || '');
    setEmail(data?.email || '');
    setPhone(data?.phone || '');
    setAddress(data?.main_address_id || '');
    setEditedData(data);
    setOpenDialog(true);
    if (data) {
      // Atur state sesuai dengan data yang diterima
      setNameField(data?.name || '');
      setWeightField((data?.last_weight_kg || '').toString());
      setHeightField((data?.last_height_cm || '').toString());
      setEmailField(data?.email || '');
      setPhoneField(data?.phone || '');

      setNameFieldError('');
      setWeightFieldError('');
      setHeightFieldError('');
      setEmailFieldError('');
      setPhoneFieldError('');
    }
  };

  const handleCloseDialog = () => {
    // Close the dialog
    /* setOpenDialog(false); */
    // Reset the edited data
    setEditedData(null);
    setOpenDialog(false);
  };

  const handleSaveData = () => {
    const updatedData = {
      ...editedData,
      last_weight_kg: weight,
      last_height_cm: height,
      email: email,
      phone: phone,
      main_address_id: address,
    };

    // Update the data in the database using the updatedData object
    axios
      .put('/data/' + id, updatedData)
      .then((response) => {
        // Handle the successful update
        enqueueSnackbar('Data updated successfully', { variant: 'success' });
        setOpenDialog(false);
        window.location.reload();
      })
      .catch((error) => {
        // Handle the error
        enqueueSnackbar('Failed to update data', { variant: 'error' });
      });
  };

  return (
    <Card sx={{ borderRadius: '6px', paddingY: 2 }}>
      {/* Stack 1 */}
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{ paddingY: 1, paddingX: 3 }}
      >
        <Typography variant="subtitle2">Personal Information</Typography>
        {/*<Button startIcon={<Iconify icon="heroicons:pencil-solid" />} onClick={handleEditData}>
          Edit Data
        </Button>*/}
      </Stack>
      {/* Stack 2 */}
      <Stack maxHeight="584px" paddingX={2} sx={{ overflowY: 'auto' }}>
        {/* Stack 2.1 */}
        <Stack marginTop={2} spacing={1}>
            {/*<Typography variant="subtitle2">Informasi Dasar</Typography>*/}
            <Stack direction="row" spacing={2} sx={{ flex: '100%' }}>
              <Stack direction="row" spacing={2} sx={{ width: '40%' }}>
                <img
                  width={52}
                  height={52}
                  src="/images/user-profile.png"
                  alt="user-profile"
                  style={{ borderRadius: '50%' }}
                />
                <Stack>
                  <Typography variant="caption">Full Name</Typography>
                  <Typography variant="body2"> {data?.name} </Typography>
                </Stack>
              </Stack>
              <Stack sx={{ width: '30%' }}>
                <Typography variant="caption">Weight</Typography>
                <Typography variant="body2">{data?.last_weight_kg} kg</Typography>
              </Stack>
              <Stack sx={{ width: '30%' }}>
                <Typography variant="caption">Height</Typography>
                <Typography variant="body2">{data?.last_height_cm} cm</Typography>
              </Stack>
            </Stack>
        </Stack>
      </Stack>
      {/* Stack 3 */}
      <Stack maxHeight="584px" paddingX={2} sx={{ overflowY: 'auto' }}>
        {/* Stack 3.1 */}
        <Stack marginTop={2} spacing={1}>
          {/*<Typography variant="subtitle2">Informasi Dasar</Typography>*/}
          <Stack direction="row" spacing={2} sx={{ flex: '100%' }}>
            <Stack sx={{ width: '40%' }}>
              <Typography variant="caption">Place of Birth</Typography>
              <Typography variant="body2"> {data?.birth_place} </Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
              <Typography variant="caption">Date of Birth</Typography>
              <Typography variant="body2">
                {' '}
                {data?.birth_date ? fDate(data?.birth_date) : ''}
              </Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
              <Typography variant="caption">Gender</Typography>
              <Typography variant="body2">{data?.gender ? data.gender.charAt(0).toUpperCase() + data.gender.slice(1) : ''}</Typography>
            </Stack>
          </Stack>
        </Stack>
        {/* Stack 3.2 */}
        <Stack marginTop={2} spacing={1}>
          {/*<Typography variant="subtitle2">Informasi Kontak</Typography>*/}
          <Stack direction="row" spacing={2} sx={{ flex: '100%' }}>
            <Stack sx={{ width: '40%' }}>
              <Typography variant="caption">Phone Number</Typography>
              <Typography variant="body2">{data?.phone}</Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
              <Typography variant="caption">Email</Typography>
              <Typography variant="body2">{data?.email}</Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
            </Stack>
          </Stack>
          <Stack>
            <Typography variant="caption">Address</Typography>
            <Typography variant="body2">{data?.main_address_id}</Typography>
          </Stack>
        </Stack>
        {/* Stack 3.3 */}
        <Stack marginTop={2} spacing={1}>
          {/*<Typography variant="subtitle2">Identitas Diri</Typography>*/}
          <Stack
            direction="row"
            spacing={2}
            sx={{ flex: '100%' }}
          >
            <Stack sx={{ width: '40%' }}>
              <Typography variant="caption">ID Member</Typography>
              <Typography variant="body2">{data?.nik}</Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
              <Typography variant="caption">Agama</Typography>
              <Typography variant="body2">{data?.religion}</Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
              {/*<Button variant="contained" startIcon={<VisibilityIcon />} disabled>
                Lihat Foto
              </Button>*/}
            </Stack>
          </Stack>
        </Stack>
        {/* Stack 3.4 */}
        <Stack marginTop={2} spacing={1}>
          {/*<Typography variant="subtitle2">Informasi Lainnya</Typography>*/}
          <Stack direction="row" justifyContent="space-between" spacing={2} sx={{ flex: '100%' }}>
            <Stack sx={{ width: '40%' }}>
              <Typography variant="caption">Marital Status</Typography>
              <Typography variant="body2">{data?.marital_status}</Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
              <Typography variant="caption">Education</Typography>
              <Typography variant="body2">{data?.last_education}</Typography>
            </Stack>
            <Stack sx={{ width: '30%' }}>
              <Typography variant="caption">Occupation</Typography>
              <Typography variant="body2">{data?.current_employment}</Typography>
            </Stack>
          </Stack>
        </Stack>
      </Stack>

      {/* Dialog */}
      <Dialog open={openDialog} onClose={handleCloseDialog} fullWidth={true}>
        <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between">
              <Stack direction="row">
                <Iconify width={25} height={25} sx={{ marginRight: '10px' }} />
                <Typography variant="h6">Edit Data</Typography>
              </Stack>
            <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialog}>
              <CloseIcon />
            </IconButton>
          </Stack>
        </DialogTitle>
        <DialogContent>
          <Stack spacing={2}>
            <TextField
              label="Full Name"
              required
              value={editedData ? editedData.name : ''}
              onChange={(e) =>{
               setEditedData({ ...editedData, name: e.target.value });
               setNameField(e.target.value);
               setNameFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
             }}
              fullWidth
              sx={{ marginTop: '16px' }}
              inputProps={{ maxLength: 50 }}
              error={!!nameFieldError}
              helperText={nameFieldError}
            />
            <TextField
              label="Weight (kg)"
              required
              value={weight}
              onChange={(e) => {
                let input = e.target.value;
                // Hanya izinkan angka
                input = input.replace(/[^0-9]/g, '');
                // Batasi panjang input menjadi 3 digit
                const maxLength = 3;
                const sanitizedInput = input.slice(0, maxLength);
                setWeight(sanitizedInput);
                setWeightField(sanitizedInput);
                setWeightFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
              }}
              fullWidth
              sx={{ marginTop: '16px' }}
              inputProps={{
                inputMode: 'numeric',
                pattern: '[0-9]*', // Memungkinkan hanya karakter angka
              }}
              error={!!weightFieldError}
              helperText={weightFieldError}
            />
            <TextField
              label="Height (cm)"
              required
              value={height}
              onChange={(e) => {
                let input = e.target.value;
                // Hanya izinkan angka
                input = input.replace(/[^0-9]/g, '');
                // Batasi panjang input menjadi 3 digit
                const maxLength = 3;
                const sanitizedInput = input.slice(0, maxLength);
                setHeight(sanitizedInput);
                setHeightField(sanitizedInput);
                setHeightFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
              }}
              fullWidth
              sx={{ marginTop: '16px' }}
              inputProps={{
                inputMode: 'numeric',
                pattern: '[0-9]*', // Memungkinkan hanya karakter angka
              }}
              error={!!heightFieldError}
              helperText={heightFieldError}

            />
            <TextField
              label="Email Address"
              required
              value={email}
              onChange={(e) => {
                setEmail(e.target.value)
                setEmailField(e.target.value);
                setEmailFieldError(
                  e.target.value.trim() === '' ? 'This field is required' : !isValidEmail(e.target.value) ? 'Invalid email address' : ''
                );
                setEmailFieldCheck(isValidEmail(e.target.value));
              }}
              fullWidth
              sx={{ marginTop: '16px' }}
              error={!!emailFieldError}
              helperText={emailFieldError}
            />
            <TextField
              label="Phone No."
              required
              value={phone}
              onChange={(e) => {
                let input = e.target.value;
                // Hanya izinkan angka dan karakter '+'
                input = input.replace(/[^0-9+]/g, '');
                // Batasi panjang input menjadi 13 digit
                const maxLength = 15;
                const sanitizedInput = input.slice(0, maxLength);
                setPhone(sanitizedInput);
                setPhoneField(sanitizedInput);
                setPhoneFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
              }}
              fullWidth
              sx={{ marginTop: '16px' }}
              inputProps={{
                inputMode: 'tel',
                pattern: '^\\+?[0-9]*$', // Memungkinkan karakter '+' di awal, diikuti oleh angka
              }}
              error={!!phoneFieldError}
              helperText={phoneFieldError}
            />
            {/*  <TextField
              label="Address"
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              fullWidth
              sx={{ marginTop: '16px' }}
            /> */}

            {/* Add more fields as needed */}
          </Stack>
        </DialogContent>

        <DialogActions>
          <Button onClick={handleCloseDialog}>Cancel</Button>
          <Button onClick={handleSaveData} variant="contained" color="primary" disabled={!isRequiredFieldsFilled()}>
            Save
          </Button>
        </DialogActions>
      </Dialog>
    </Card>
  );
}
