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, Controller } 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,
  Autocomplete,
} from '@mui/material';

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

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

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

const LabelStyle = styled(Typography)(({ theme }) => ({
  ...theme.typography.h6,
  marginBottom: theme.spacing(2),
  marginTop: theme.spacing(2),
}));

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,
}));

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 || '',
      email: currentPractitioner?.email || '',
      phone: currentPractitioner?.phone || '',
      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('currentPractitioner', 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 onSubmit = async (data: FormValuesProps) => {
    try {
      const formData = new FormData();
      formData.append('name', data.name);
      formData.append('gender', data.gender);
      formData.append('address', data.address);
      formData.append('birth_place', data.birth_place);
      formData.append('birth_date', data.birth_date);
      formData.append('email', data.email);
      formData.append('phone', data.phone);
      // formData.append('active', data.active ? '1' : '0');
      forms.forEach((form, index) => {
        formData.append(`practices[${index}][organization_id]`, form.organizationId);
        form.specialities.forEach((speciality, i) => {
          formData.append(`practices[${index}][specialities][${i}][speciality_id]`, speciality);
        });
      });

      if (!isEdit) {
        console.log('formData', formData);
        const response = await axios.post('/doctors', formData);
      } else {
        formData.append('_method', 'PUT');
        const response = await axios.post('/doctors/' + currentPractitioner?.id ?? '', formData);
      }
      reset();
      enqueueSnackbar(!isEdit ? 'Doctors Created Successfully!' : 'Doctors Udpated Successfully!', {
        variant: 'success',
      });
      navigate('/master/doctors');
    } catch (error: any) {
      if (error && error.response.status === 422) {
        console.log('error', error.response.data.errors);
        for (const [key, value] of Object.entries(error.response.data.errors)) {
          setError(key, { message: value[0] });
          enqueueSnackbar(value[0] ?? 'Failed Processing Request', { variant: 'error' });
        }
      } else {
        enqueueSnackbar(error.message ?? 'Failed Processing Request', { variant: 'error' });
      }
    }

    const ascent = document?.querySelector('ascent');
    if (ascent != null) {
      ascent.innerHTML = '';
    }
  };

  const [organizations, setOrganizations] = useState<any>([]);
  const [specialities, setSpecialities] = useState<any>([]);

  useEffect(() => {
    axios.get(`/search-organizations`).then((response) => {
      console.log(response);
      
      setOrganizations(
        response.data.map((item: any) => ({ ...item, name: item.name, value: item.id }))
      );
    });

    axios.get(`/search-specialities`).then((response) => {
      setSpecialities(
        response.data.map((item: any) => ({ ...item, name: item.name, value: item.id }))
      );
    });
  }, []);

  // const specialities = [
  //   { name: 'Dentistry', id: 1 },
  //   { name: 'Dermatology', id: 2 },
  //   { name: 'General Medicine', id: 3 },
  //   { name: 'Pediatrics', id: 4 },
  //   { name: 'Surgery', id: 5 },
  // ];

  const practices = currentPractitioner?.practices || [];
  // const practices = [
  //   {
  //     organization_id: 187,
  //     specialities: [
  //       {
  //         speciality_id: 7,
  //       },
  //       {
  //         speciality_id: 6,
  //       },
  //     ],
  //   },
  //   {
  //     organization_id: 181,
  //     specialities: [
  //       {
  //         speciality_id: 2,
  //       },
  //     ],
  //   },
  // ];

  const [forms, setForms] = useState<any>([]);

  useEffect(() => {
    if (practices.length > 0) {
      const newForms = practices.map((practice: any) => {
        return {
          organizationId: practice.organization_id,
          specialities: practice.specialities.map((s) => s.speciality_id),
        };
      });
      setForms(newForms);
    } else {
      setForms([
        {
          organizationId: '',
          specialities: [],
        },
      ]);
    }
  }, [practices && practices.length]);
  // }, []);

  console.log('forms', forms);

  const findValueOrganization = (organizationId) => {
    if (organizationId === '' || organizationId === null) {
      return { name: '', value: '' };
    } else {
      const organization = organizations.find((o) => o.id === organizationId);
      return { name: organization?.name, value: organizationId };
    }
  };

  // console.log('findValueOrganization', findValueOrganization(187));

  // const findValueSpeciality = (specialityIds: number[]) => {
  //   if (specialityIds.length === 0) {
  //     return [];
  //   } else {
  //     const data = specialities.filter((s) => specialityIds.includes(s.id));
  //     return data.map((d) => ({ name: d.name, value: d.id }));
  //   }
  // };

  const findValueSpeciality = (values: any) => {
    return specialities.filter((s) => values.includes(s.value));
  };

  // const [forms, setForms] = useState([
  //   {
  //     organizationId: '',
  //     specialities: [],
  //   },
  // ]);

  const addForm = () => {
    setForms([
      ...forms,
      {
        organizationId: '',
        specialities: [],
      },
    ]);
  };
  console.log('forms', forms);

  const gender = [
    {
      value: 'male',
      label: 'Laki-Laki',
    },
    {
      value: 'female',
      label: 'Perempuan',
    },
  ];

  console.log('forms', forms);
  // const handleSpecialitiesChange = (index: number, value: any) => {
  //   const newForms = [...forms];
  //   newForms[index].specialities = value.map((v: any) => ({ speciality_id: v.id }));
  //   setForms(newForms);
  // };
  // const handleSpecialitiesChange = (index: number, value: any) => {
  //   const updatedForms = [...forms];
  //   updatedForms[index].specialities = value.map((v: any) => v.speciality_id);
  //   setForms(updatedForms);
  // };

  const handleOrganizationIdChange = (index, value) => {
    const updatedForms = [...forms];
    updatedForms[index].organizationId = value.id;
    setForms(updatedForms);
  };

  const handleSpecialitiesChange = (index: number, value: any) => {
    setForms((forms) => {
      forms[index].specialities = value.map((v: any) => v.value);
      return [...forms];
    });
  };

  // const availableOrganizations = organizations.filter(
  //   (org) =>
  //     !forms.some((f) => f.organization && f.organization.id === org.id) ||
  //     forms.findIndex((f) => f.organization && f.organization.id === org.id) === editIndex
  // );
  const availableOrganizations =
    practices.length > 0
      ? organizations.filter(
          (org) => !practices.some((practice) => practice.organization_id === org.id)
        )
      : organizations.filter((org) => !forms.some((f) => f.organizationId === org.id));

  // const availableOrganizations = organizations.filter(
  //   (org) => !practices.some((p) => p.organization_id === org.id)
  // );

  const handleDeleteForm = (index) => {
    const updatedForms = [...forms];
    updatedForms.splice(index, 1);
    setForms(updatedForms);
  };

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <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}>
                <RHFSwitch name="active" label="" />
                <StatusLabel value={values.active} />
              </Grid>
            </HeaderStyle> */}
            <Title variant="h5">Informasi Umum</Title>
            <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }} sx={{ mt: 2 }}>
              <Grid item xs={12}>
                <LabelStyle>Nama Dokter</LabelStyle>
                <RHFTextField name="name" placeholder="Tuliskan Nama Dokter" />
              </Grid>

              <Grid item xs={6}>
                <LabelStyle>Jenis Kelamin</LabelStyle>
                <RHFSelect name="gender" label="Pilih Jenis Kelamin">
                  <option value="" />
                  {gender.map((option, index) => (
                    <option key={index} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </RHFSelect>
              </Grid>
              <Grid item xs={6}>
                <LabelStyle>Alamat</LabelStyle>
                <RHFTextField name="address" placeholder="Tuliskan Alamat" />
              </Grid>

              <Grid item xs={6}>
                <LabelStyle>Tempat Lahir</LabelStyle>
                <RHFTextField name="birth_place" placeholder="Tuliskan Tempat Lahir" />
              </Grid>
              <Grid item xs={6}>
                <LabelStyle>Tanggal Lahir</LabelStyle>
                <RHFDatepicker name="birth_date" placeholder="Silahkan Pilih Tanggal Lahir" />
              </Grid>
              <Grid item xs={6}>
                <LabelStyle>Email</LabelStyle>
                <RHFTextField name="email" placeholder="Tuliskan Email" type="email" />
              </Grid>
              <Grid item xs={6}>
                <LabelStyle>No. Telp</LabelStyle>
                <RHFTextField name="phone" placeholder="Tuliskan Nomor Telepon" />
              </Grid>
            </Grid>
          </Card>
          <Card sx={{ p: 5, marginTop: 2 }}>
            <Stack spacing={3} direction="row" justifyContent="space-between">
              <Title variant="h5">Tempat Praktik</Title>
              <Button
                variant="contained"
                color="primary"
                size="small"
                sx={{ boxShadow: 'none' }}
                onClick={addForm}
                startIcon={<AddIcon />}
              >
                Tambah Tempat Praktik
              </Button>
            </Stack>

            {forms.map((form, index) => (
              <div key={index}>
                <Box sx={{ mt: 3 }}>
                  <Stack spacing={3} direction="row" justifyContent="space-between">
                    <LabelStyle></LabelStyle>
                    {index !== 0 && (
                      <Button
                        sx={{ color: 'red', m: 1 }}
                        aria-label="close"
                        onClick={() => handleDeleteForm(index)}
                      >
                        Delete
                      </Button>
                      // <Button onClick={() => handleDeleteForm(index)}>Delete</Button>
                    )}
                  </Stack>
                  {/* <h1>{form.organizationId}</h1> */}
                  <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
                    <Grid item xs={6}>
                      <Autocomplete
                        options={availableOrganizations}
                        value={findValueOrganization(form.organizationId) ?? ''}
                        getOptionLabel={(option) => option.name}
                        isOptionEqualToValue={(option, value) => {
                            console.log(value, option, 'test')
                            return option.value === value.value
                          }
                        }
                        onChange={(event, value) => handleOrganizationIdChange(index, value)}
                        renderInput={(params) => (
                          <TextField {...params} label="Rumah Sakit" variant="outlined" />
                        )}
                      />
                      {/* <Autocomplete
                        options={organizations}
                        value={findValueOrganization(form.organizationId)}
                        getOptionLabel={(option) =>
                          option.name ?? findValueOrganization(form.organizationId).name ?? ''
                        }
                        onChange={(event, value) => handleOrganizationIdChange(index, value)}
                        renderInput={(params) => (
                          <TextField {...params} label="Rumah Sakit" variant="outlined" />
                        )}
                      /> */}
                    </Grid>
                    <Grid item xs={6}>
                      {form.specialities && (
                        // <Autocomplete
                        //   multiple
                        //   // options={specialities}
                        //   options={specialities}
                        //   value={findValueSpeciality(form.specialities) ?? ''}
                        //   getOptionLabel={(option) => option.name}
                        //   isOptionEqualToValue={(option, value) => option.value === value.value}
                        //   onChange={(event, value) => handleSpecialitiesChange(index, value)}
                        //   renderInput={(params) => (
                        //     <TextField {...params} label="Spesialis" variant="outlined" />
                        //   )}
                        // />

                        <Autocomplete
                          multiple
                          options={specialities}
                          value={findValueSpeciality(form.specialities)}
                          getOptionLabel={(option) => option.name}
                          onChange={(event, value) => handleSpecialitiesChange(index, value)}
                          renderInput={(params) => (
                            <TextField {...params} label="Spesialis" variant="outlined" />
                          )}
                        />
                      )}
                    </Grid>
                  </Grid>
                </Box>
              </div>
            ))}
          </Card>
          <Box sx={{ width: '100%', mt: 5 }}>
            <Stack
              alignItems="center"
              justifyContent="end"
              direction={{ xs: 'column', md: 'row' }}
              sx={{ width: 1, textAlign: { xs: 'center', md: 'left' } }}
            >
              <Grid item xs={12} md={4}>
                <LoadingButton
                  sx={{ boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)' }}
                  type="submit"
                  variant="contained"
                  size="large"
                  // fullWidth={true}
                  loading={isSubmitting}
                >
                  {!isEdit ? 'Simpan' : 'Simpan Perubahan'}
                </LoadingButton>
              </Grid>
            </Stack>
          </Box>
        </Box>
      </Stack>
    </FormProvider>
  );
}
