import * as Yup from 'yup';
import { useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import MenuItem from '@mui/material/MenuItem';

import Select, { SelectChangeEvent } from '@mui/material/Select';
import * as React from 'react';

// form
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
// @mui
import { styled } from '@mui/material/styles';
import { LoadingButton } from '@mui/lab';
import {
  Box,
  Avatar,
  Button,
  ButtonGroup,
  Card,
  FormHelperText,
  Grid,
  Stack,
  Typography,
  TextField,
  Chip,
} from '@mui/material';

import CancelIcon from '@mui/icons-material/Cancel';

// components
import {
  FormProvider,
  RHFTextField,
  RHFRadioGroup,
  RHFUploadAvatar,
  RHFSwitch,
  RHFEditor,
  RHFDatepicker,
  RHFMultiCheckbox,
  RHFCheckbox,
  RHFCustomMultiCheckbox,
} from '../../../components/hook-form';
import axios from '../../../utils/axios';
import { fCurrency } from '../../../utils/formatNumber';
import { Practitioner } from '../../../@types/doctor';

import { Label, Rowing } from '@mui/icons-material';

const LabelStyle = styled(Typography)(({ theme }) => ({
  ...theme.typography.subtitle2,
  color: theme.palette.text.secondary,
  marginBottom: theme.spacing(1),
}));

const HeaderStyle = styled('header')(({ theme }) => ({
  paddingBottom: theme.spacing(5),
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
}));

const Title = styled(Typography)(({ theme }) => ({
  ...theme.typography.h4,
  boxShadow: 'none',
  // paddingBottom: theme.spacing(3),
  fontWeight: 700,
  color: '#005B7F',
}));

interface FormValuesProps extends Partial<Practitioner> {
  taxes: boolean;
  inStock: boolean;
}

type Props = {
  isEdit: boolean;
  currentPractitioner?: Practitioner;
};

const Span = styled(Typography)(({ theme }) => ({
  boxShadow: 'none',
  paddingBottom: theme.spacing(1),
}));

const Text = styled(Typography)(({ theme }) => ({
  boxShadow: 'none',
  paddingBottom: theme.spacing(3),
}));

export default function PractitionerForm({ isEdit, currentPractitioner }: Props) {
  const navigate = useNavigate();
  const [practitioner_group, setPractitionerGroups] = useState([]);

  // const [ errors, setErrors ] = useState<{ [key: string]: string }>({});

  const { enqueueSnackbar } = useSnackbar();

  const NewCorporateSchema = Yup.object().shape({
    name: Yup.string().required('Name is required'),
    // file: Yup.boolean().required('Corporate Status is required'),
  });

  const defaultValues = useMemo(
    () => ({
      id: currentPractitioner?.id,
      name: currentPractitioner?.name || '',
      address: currentPractitioner?.address || '',
      birth_date: currentPractitioner?.birth_date || '',
      gender: currentPractitioner?.gender || '',
      description: currentPractitioner?.description || '',
      birth_place: currentPractitioner?.birth_place || '',
      active: currentPractitioner?.active === 1 ? true : false,
      avatar_url: currentPractitioner?.avatar_url || '',
      doctor_id: currentPractitioner?.doctor_id || '',
      organizations: currentPractitioner?.organizations || [],
      specialities: currentPractitioner?.specialities || [],
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [currentPractitioner]
  );

  console.log('defaultValues', defaultValues);

  function StatusLabel({ value }: { value: boolean }) {
    return (
      <Chip
        label={value ? 'Aktif' : 'Tidak Aktif'}
        size="medium"
        sx={{
          backgroundColor: value ? 'rgba(84, 214, 44, 0.16)' : 'rgba(255, 72, 66, 0.16)',
          color: value ? '#229A16' : '#B72136',
          padding: '1 8 1 8 px',
          borderRadius: '4px',
          fontSize: '12px',
          fontWeight: 'bold',
        }}
      />
    );
  }
  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(NewCorporateSchema),
    defaultValues,
  });

  const {
    reset,
    watch,
    control,
    setValue,
    getValues,
    setError,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  useEffect(() => {
    if (isEdit && currentPractitioner) {
      reset(defaultValues);
    }
    if (!isEdit) {
      reset(defaultValues);
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEdit, currentPractitioner]);

  const handleActivate = (event: React.ChangeEvent<HTMLInputElement>) => {
    setValue('active', event.target.checked);

    console.log('event.target.checked', event.target.checked);

    const formData = new FormData();
    formData.append('active', event.target.checked ? '1' : '0');
    formData.append('_method', 'PUT');
    axios.post('/doctors/' + currentPractitioner?.id ?? '', formData);

    enqueueSnackbar('active Updated Successfully!', { variant: 'success' });
  };

  return (
    <FormProvider methods={methods}>
      <Stack spacing={3}>
        <Box sx={{ width: '100%' }}>
          {/* <Stack spacing={3}> */}
          <Card sx={{ p: 5 }}>
            <HeaderStyle>
              <Grid item xs={6} md={6}>
                <Title>Data Dokter</Title>
              </Grid>
              <Grid item xs={6} md={6}>
                {/* <Typography>Status Rumah Sakit</Typography> */}
                <RHFSwitch name="active" label="" onClick={handleActivate} />
                <StatusLabel value={values.active} />
              </Grid>
            </HeaderStyle>
            <Title variant="h5">Informasi Umum</Title>
            <Avatar
              alt="Remy Sharp"
              src={currentPractitioner?.avatar_url}
              sx={{ width: 120, height: 120, marginBottom: 2 }}
            />

            <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
              <Grid item xs={7}>
                <Span style={{ fontWeight: 'bold' }}>Nama Dokter</Span>
                <Text>{currentPractitioner?.name ? currentPractitioner?.name : '-'}</Text>
                <Span style={{ fontWeight: 'bold' }}>No Telp</Span>
                <Text>{currentPractitioner?.phone ? currentPractitioner?.phone : '-'}</Text>
                <Span style={{ fontWeight: 'bold' }}>Tempat Lahir</Span>
                <Text>
                  {currentPractitioner?.birth_place ? currentPractitioner?.birth_place : '-'}
                </Text>
                <Span style={{ fontWeight: 'bold' }}>Alamat</Span>
                <Text>{currentPractitioner?.address ? currentPractitioner?.address : '-'}</Text>
              </Grid>
              <Grid item xs={5} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
                <Span style={{ fontWeight: 'bold' }}>Jenis Kelamin</Span>
                <Text>{currentPractitioner?.gender ? currentPractitioner?.gender : '-'}</Text>
                <Span style={{ fontWeight: 'bold' }}>Email</Span>
                <Text>{currentPractitioner?.email ? currentPractitioner?.email : '-'}</Text>
                <Span style={{ fontWeight: 'bold' }}>Tanggal Lahir</Span>
                <Text>
                  {currentPractitioner?.birth_date ? currentPractitioner?.birth_date : '-'}
                </Text>
              </Grid>
            </Grid>
          </Card>
          <Card sx={{ p: 5, marginTop: 2 }}>
            <Title variant="h5">Tempat Praktik</Title>
            {currentPractitioner?.organizations?.map((item, index) => (
              <Box key={index} sx={{ mt: 3 }}>
                <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
                  <Grid item xs={7}>
                    <Text>{item.name}</Text>
                  </Grid>
                </Grid>
              </Box>
            ))}
          </Card>
          <Card sx={{ p: 5, marginTop: 2 }}>
            <Title variant="h5">Spesialisasi</Title>
            {currentPractitioner?.specialities?.map((item, index) => (
              <Box key={index} sx={{ mt: 3 }}>
                <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
                  <Grid item xs={7}>
                    <Text>{item.name}</Text>
                  </Grid>
                </Grid>
              </Box>
            ))}
          </Card>
        </Box>
      </Stack>
    </FormProvider>
  );
}
