import { useEffect, useRef, useState } from 'react';

import {
  Button,
  FormControl,
  FormLabel,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  NumberInput,
  Textarea,
} from '@chakra-ui/react';
import { Formiz, useForm, useFormFields } from '@formiz/core';
import { useNavigate, useParams } from 'react-router-dom';

import { Album, Track } from '@/back-api';
import { FormGroup } from '@/components/form/FormGroup';
import { SelectMultiple } from '@/components/form/SelectMultiple';
import { SelectSingle } from '@/components/form/SelectSingle';
import { useOrderedAlbums } from '@/service/Album';
import { useOrderedArtists } from '@/service/Artist';
import { useOrderedGenders } from '@/service/Gender';
import { useSpecificTrack } from '@/service/Track';
import { isNullOrUndefined } from '@/utils/validator';

export type TrackEditPopUpProps = {};

const getDifferences = (obj1: any, obj2: any): { [key: string]: boolean } => {
  const result: { [key: string]: boolean } = {};
  for (const key in obj1) {
    if (obj1.hasOwnProperty(key)) {
      result[key] = obj1[key] !== obj2[key];
    }
  }
  return result;
};

const hasAnyTrue = (obj: { [key: string]: boolean }): boolean => {
  for (const key in obj) {
    if (obj.hasOwnProperty(key) && obj[key] === true) {
      return true;
    }
  }
  return false;
};

export const TrackEditPopUp = ({}: TrackEditPopUpProps) => {
  const { trackId } = useParams();
  const { dataGenders } = useOrderedGenders(undefined);
  const { dataArtist } = useOrderedArtists(undefined);
  const { dataAlbums } = useOrderedAlbums(undefined);
  const { dataTrack } = useSpecificTrack(
    isNullOrUndefined(trackId) ? undefined : parseInt(trackId, 10)
  );
  const navigate = useNavigate();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onSubmit = (values) => {
    console.log(`onSubmit = ${values}`);
  };
  const onValuesChange = (values, form) => {
    console.log(`onValuesChange = ${values}`);
  };
  const initialRef = useRef(null);
  const finalRef = useRef(null);
  const form = useForm<Track>({
    onSubmit,
    onValuesChange,
    initialValues: { ...dataTrack },
    onValid: () => console.log('onValid'),
    onInvalid: () => console.log('onInvalid'),
  });
  const formValues = useFormFields({
    connect: form,
    selector: (field) => field.value,
  });
  /*
  const formValues = useFormFields({
    connect: form,
    fields: ['genderId'] as const,
    selector: 'value',
  });
  */
  console.log(`dataTrack : ${JSON.stringify(dataTrack, null, 2)}`);
  console.log(`Redraw : ${JSON.stringify(formValues, null, 2)}`);
  const [newData, setNewData] = useState<Track>();
  const [changeData, setChangeData] = useState<{ [key: string]: boolean }>();
  const [changeOneData, setChangeOneData] = useState<boolean>(true);
  // initialize value when ready
  useEffect(() => {
    setNewData(dataTrack);
  }, [dataTrack, setNewData, setChangeData]);

  useEffect(() => {
    if (!newData) {
      return;
    }
    const ret = getDifferences(dataTrack, newData);
    setChangeData(ret);
    ///////////////////////setChangeOneData(hasAnyTrue(ret));
    console.log(
      `ChangeData=${JSON.stringify(ret, null, 2)} ChangeOneData=${hasAnyTrue(ret)}`
    );
  }, [dataTrack, newData, setChangeData, setChangeOneData]);

  // const onChangeValue = (key: string, data) => {
  //   console.log(`[${key}] data: ${data}`);
  //   setNewData((previous) => {
  //     if (previous === undefined) {
  //       return previous;
  //     }
  //     if (previous[key] === data) {
  //       return previous;
  //     }
  //     const tmp = { ...previous };
  //     tmp[key] = data;
  //     console.log(`data = ${JSON.stringify(tmp, null, 2)}`);
  //     return tmp;
  //   });
  // };

  return (
    <Formiz connect={form} autoForm>
      <form noValidate onSubmit={form.submit}>
        <Modal
          initialFocusRef={initialRef}
          finalFocusRef={finalRef}
          closeOnOverlayClick={false}
          onClose={onClose}
          isOpen={true}
        >
          <ModalOverlay />
          <ModalContent>
            <ModalHeader>Edit Track</ModalHeader>
            <ModalCloseButton ref={finalRef} />

            <ModalBody pb={6}>
              <FormGroup isRequired>
                <FormLabel>Title</FormLabel>
                <Input
                  ref={initialRef}
                  value={formValues.name}
                  onChange={(e) => form.setValues({ name: e.target.value })}
                />
              </FormGroup>

              <FormGroup>
                <label>Description</label>
                <Textarea
                  value={formValues.description}
                  onChange={(e) =>
                    form.setValues({ description: e.target.value })
                  }
                />
              </FormGroup>
              <FormGroup>
                <label>Gender</label>
                <SelectSingle
                  value={formValues.genderId}
                  options={dataGenders}
                  onChange={(value) => {
                    form.setValues({ genderId: value });
                    console.log(`event change value: ${value}`);
                    console.log(
                      `values: ${JSON.stringify(formValues, null, 2)}`
                    );
                  }}
                  keyValue="name"
                />
              </FormGroup>
              <FormGroup>
                <label>Artist(s)</label>
                <SelectMultiple
                  values={formValues.artists}
                  options={dataArtist}
                  onChange={(value) => form.setValues({ artists: value })}
                  keyValue="name"
                />
              </FormGroup>
              <FormGroup>
                <label>Album</label>
                <SelectSingle
                  value={formValues.albumId}
                  options={dataAlbums}
                  onChange={(value) => form.setValues({ albumId: value })}
                  keyValue="name"
                />
              </FormGroup>
              <FormControl>
                <FormLabel>track n°</FormLabel>
                <NumberInput
                  value={formValues.track}
                  onChange={(value) => form.setValues({ track: value })}
                />
              </FormControl>
            </ModalBody>
            <ModalFooter>
              {changeOneData && (
                <Button colorScheme="blue" mr={3} type="submit">
                  Save
                </Button>
              )}
              <Button onClick={onClose}>Cancel</Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
      </form>
    </Formiz>
  );
};
