// mui
import { FormHelperText, FormControl, Button, Card, Stack, Typography, Grid, Switch, TextField, IconButton, Select, MenuItem, InputLabel } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { DatePicker, LocalizationProvider, MobileDatePicker } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
// components
import Iconify from '../../../components/Iconify';
import { fDate, fPostFormat } from '../../../utils/formatTime';
import { Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import { useContext, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import axios from '../../../utils/axios';
import { enqueueSnackbar } from 'notistack';

export default function CardFamilyInformation({ data }) {

  const [openDialog, setOpenDialog] = useState(false);
  const [editIndex, setEditIndex] = useState(null);
  const [editedFamilyData, setEditedFamilyData] = useState({});
  const { id } = useParams();

  //Check Required
  //State Field
  const [nameField, setNameField] = useState('');
  const [relationshipField, setRelationshipField] = useState('');
  const [birthDateField, setBirthDateField] = useState('');
  const [birthDateFieldCheck, setBirthDateFieldCheck] = useState(1);
  const [emailField, setEmailField] = useState('');
  const [emailFieldCheck, setEmailFieldCheck] = useState(false);
  const [phoneField, setPhoneField] = useState('');
  //State Field Error
  const [nameFieldError, setNameFieldError] = useState('');
  const [relationshipFieldError, setRelationshipFieldError] = useState('');
  const [birthDateFieldError, setBirthDateFieldError] = useState('');
  const [emailFieldError, setEmailFieldError] = useState('');
  const [phoneFieldError, setPhoneFieldError] = useState('');

  const handleEditData = (index) => {
    setEditIndex(index);
    setEditedFamilyData(data?.family[index] || {});
    setOpenDialog(true);

    setNameField(data?.family[index].name);
    setRelationshipField(data?.family[index].relation_with_principal);
    setBirthDateField(data?.family[index].birth_date);
    setEmailField(data?.family[index].email);
    setEmailFieldCheck(isValidEmail(data?.family[index].email));
    setPhoneField(data?.family[index].phone);
    
    setNameFieldError('');
    setRelationshipFieldError('');
    setBirthDateFieldError('');
    setEmailFieldError('');
    setPhoneFieldError('');
  };

  const handleCloseDialog = () => {
     setOpenDialog(false);
  };

  const handleSaveData = () => {
    if (editIndex !== null) {
      try {

        // Salin data keluarga saat ini
        const updatedFamily = [...data?.family];

        // Perbarui data keluarga dengan data yang diedit
        updatedFamily[editIndex] = editedFamilyData;

        // Perbarui data utama dengan data keluarga yang telah diperbarui
        const updatedData = { ...data, family: updatedFamily[editIndex]};

        updatedData.family.birth_date = fPostFormat(updatedData.family.birth_date, 'yyyy-MM-dd') ;

        const familyArray = [updatedData.family];

        axios
        .post('/update-family', familyArray)
        .then((response) => {
          enqueueSnackbar('Data updated successfully', { variant: 'success' });
          setOpenDialog(false);
          window.location.reload();
        })
        .catch((error) => {
          enqueueSnackbar('Failed to update data', { variant: 'error' });
        });

      } catch (error) {
        console.error('Terjadi kesalahan saat menyimpan data:', error);
      }
    }
  };

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

  const isRequiredFieldsFilled = () => {
    return nameField.trim() !== '' && relationshipField.trim() !== '' && birthDateField !== '' && birthDateFieldCheck !== 0 && emailField.trim() !== '' && emailFieldCheck && phoneField.trim() !== '';
  };
  
  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">Beneficiary / Family</Typography>
        {/*<Button startIcon={<Iconify icon="ic:round-add" />} disabled>Add Member</Button>*/}
      </Stack>
      {/* Stack 2 */}
      <Grid container maxHeight="584px" spacing={2} paddingX={2} sx={{ overflowY: 'auto' }}>
      {data?.family.map((familyMember, index) => (
        <Grid item xs={12} sm={6} md={6} key={index}>
          <Card sx={{ paddingX: 1.5, paddingY: 1, marginBottom: 2 }}>
            {/* Stack 1 */}
            <Stack
              direction="row"
              alignItems="left"
              justifyContent="space-between"
              spacing={2}
              sx={{ flex: '100%' }}
            >
              {/* Row 1 */}
              <Stack direction="row" spacing={1}>
                <img
                  width={34}
                  height={34}
                  src="/images/husband-user-profile.png"
                  alt="user-profile"
                  style={{ borderRadius: '50%' }}
                />
                <Stack>
                <Typography variant="body2" sx={{ fontWeight: 500 }}>
                  {familyMember?.name}
                </Typography>
                <Typography variant="body2" color="#757575">
                  {familyMember.relation_with_principal === 'H'
                    ? 'Husband'
                    : familyMember.relation_with_principal === 'W'
                    ? 'Wife'
                    : familyMember.relation_with_principal === 'S'
                    ? 'Son'
                    : familyMember.relation_with_principal === 'D'
                    ? 'Daughter'
                    : ''}
                </Typography>
                </Stack>
              </Stack>
              {/* Row 2 */}
              <Stack sx={{display:'none'}} alignItems="center">
                <Typography variant="caption">Suspend</Typography>
                <Switch aria-label="switch demo" disabled />
              </Stack>
            </Stack>
            <Stack
              direction="row"
              alignItems="left"
              spacing={10}
              sx={{ flex: '100%' }}
            >
              <Typography sx={{width: '20%'}} variant="body2" color="#757575">
                Date of Birth
              </Typography>
              <Typography variant="body2" sx={{ fontWeight: 500 }}>
                {familyMember?.birth_date != '0000-00-00' ? fDate(familyMember?.birth_date) : '-'}
              </Typography>
            </Stack>
            <Stack
              direction="row"
              alignItems="left"
              spacing={10}
              sx={{ flex: '100%' }}
            >
              <Typography sx={{width: '20%'}} variant="body2" color="#757575">
                Email
              </Typography>
              <Typography variant="body2" sx={{ fontWeight: 500 }}>
                {familyMember?.email}
              </Typography>
            </Stack>
            <Stack
              direction="row"
              alignItems="left"
              spacing={10}
              sx={{ flex: '100%' }}
            >
              <Typography sx={{width: '20%'}} variant="body2" color="#757575">
                Phone Number
              </Typography>
              <Typography variant="body2" sx={{ fontWeight: 500 }}>
                {familyMember?.phone}
              </Typography>
            </Stack>
            <Stack
              direction="row"
              alignItems="left"
              spacing={10}
              sx={{ flex: '100%' }}
            >
              <Typography sx={{width: '20%'}} variant="body2" color="#757575">
                Status
              </Typography>
              <Typography variant="body2" sx={{ fontWeight: 500 }}>
                {
                  familyMember?.phone === '1'
                  ? 'Active'
                  : 'Inactive'
                }
              </Typography>
            </Stack>
            {/* Stack 2 */}
            <Stack sx={{display:'none'}} direction="row" alignItems="center" justifyContent="space-between" marginTop={1.25}>
              <Button color="error" startIcon={<Iconify icon="ic:round-close" />} disabled>
                Remove
              </Button>
              <Button variant="contained" startIcon={<Iconify icon="heroicons:pencil-solid" />} onClick={ () => handleEditData(index)}>
                Edit Data
              </Button>
            </Stack>
          </Card>
        </Grid>
      ))}
      </Grid>
      {/* 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="Name"
              required
              value={editedFamilyData?.name || ''}
              onChange={(e) => {
                setEditedFamilyData({ ...editedFamilyData, name: e.target.value })
                setNameField(e.target.value);
                setNameFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
              }}
              fullWidth
              sx={{ marginTop: '16px' }}
              error={!!nameFieldError}
              helperText={nameFieldError}
            />
            <FormControl>
              <InputLabel htmlFor="relationship" required>
                Relationship
              </InputLabel>
              <Select
                id="relationship"
                value={editedFamilyData?.relation_with_principal || ''}
                onChange={(e) => {
                  setEditedFamilyData({ ...editedFamilyData, relation_with_principal: e.target.value })
                  setRelationshipField(e.target.value);
                  setRelationshipFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
                }}
                fullWidth
                label="Relationship"
                error={!!relationshipFieldError}
              >
                <MenuItem value="H">Husband</MenuItem>
                <MenuItem value="W">Wife</MenuItem>
                <MenuItem value="S">Son</MenuItem>
                <MenuItem value="D">Daughter</MenuItem>
              </Select>
              <FormHelperText style={{ color: 'red' }}>{relationshipFieldError}</FormHelperText>
            </FormControl>
            <FormControl>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
                <DatePicker
                  label="Date of Birth"
                  value={editedFamilyData?.birth_date || ''}
                  onChange={(newValue) => {
                      setEditedFamilyData({ ...editedFamilyData, birth_date: newValue });
                      setBirthDateField(newValue);
                      setBirthDateFieldError(newValue === '' || newValue === null ? 'This field is required' : '');
                      if(newValue !== null)
                      {
                        newValue = newValue.toString();
                        setBirthDateFieldCheck(newValue === 'Invalid Date' ? 0 : 1);
                      }
                  }}
                  inputFormat="dd-MM-yyyy"
                  renderInput={(params) => <TextField {...params} required/>}
                />
              </LocalizationProvider>
              <FormHelperText style={{ color: 'red' }}>{birthDateFieldError}</FormHelperText>
            </FormControl>
            <TextField
              label="Email Address"
              required
              value={editedFamilyData?.email || ''}
              onChange={(e) => {
                setEditedFamilyData({ ...editedFamilyData, email: 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."
              value={editedFamilyData?.phone || ''}
              onChange={(e) => {
                let input = e.target.value;
                // Hanya izinkan angka dan karakter '+'
                input = input.replace(/[^0-9+]/g, '');
                // Batasi panjang input menjadi 15 digit
                const maxLength = 15;
                const sanitizedInput = input.slice(0, maxLength);
                setEditedFamilyData({ ...editedFamilyData, phone: 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}
            />

          </Stack>
        </DialogContent>

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