import { useRef, useState } from 'react';

import {
  Button,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Text,
  useDisclosure,
} from '@chakra-ui/react';
import { MdAdminPanelSettings, MdDeleteForever, MdEdit } from 'react-icons/md';
import { useNavigate, useParams } from 'react-router-dom';

import { Track, TrackResource } from '@/back-api';
import { FormGroup } from '@/components/form/FormGroup';
import { FormInput } from '@/components/form/FormInput';
import { FormNumber } from '@/components/form/FormNumber';
import { FormSelect } from '@/components/form/FormSelect';
import { FormSelectMultiple } from '@/components/form/FormSelectMultiple';
import { FormTextarea } from '@/components/form/FormTextarea';
import { useFormidable } from '@/components/form/Formidable';
import { ConfirmPopUp } from '@/components/popup/ConfirmPopUp';
import { useOrderedAlbums } from '@/service/Album';
import { useOrderedArtists } from '@/service/Artist';
import { useOrderedGenders } from '@/service/Gender';
import { useServiceContext } from '@/service/ServiceContext';
import { useSpecificTrack, useTrackService } from '@/service/Track';
import { isNullOrUndefined } from '@/utils/validator';

export type TrackEditPopUpProps = {};

export const TrackEditPopUp = ({}: TrackEditPopUpProps) => {
  const { trackId } = useParams();
  const trackIdInt = isNullOrUndefined(trackId)
    ? undefined
    : parseInt(trackId, 10);
  const { session } = useServiceContext();
  const { dataGenders } = useOrderedGenders(undefined);
  const { dataArtist } = useOrderedArtists(undefined);
  const { dataAlbums } = useOrderedAlbums(undefined);
  const { store } = useTrackService();
  const { dataTrack } = useSpecificTrack(trackIdInt);
  const [admin, setAdmin] = useState(false);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(trackIdInt)) {
      return;
    }
    store.remove(
      trackIdInt,
      TrackResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: trackIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef(null);
  const finalRef = useRef(null);
  const form = useFormidable<Track>({
    //onSubmit,
    //onValuesChange,
    initialValues: dataTrack,
    //onValid: () => console.log('onValid'),
    //onInvalid: () => console.log('onInvalid'),
  });
  const onSave = async () => {
    if (isNullOrUndefined(trackIdInt)) {
      return;
    }
    const dataThatNeedToBeUpdated = form.getDeltaData({ omit: ['covers'] });
    console.log(`onSave = ${JSON.stringify(dataThatNeedToBeUpdated, null, 2)}`);
    store.update(
      TrackResource.patch({
        restConfig: session.getRestConfig(),
        data: dataThatNeedToBeUpdated,
        params: {
          id: trackIdInt,
        },
      })
    );
  };
  return (
    <Modal
      initialFocusRef={initialRef}
      finalFocusRef={finalRef}
      closeOnOverlayClick={false}
      onClose={onClose}
      isOpen={true}
    >
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>Edit Track</ModalHeader>
        <ModalCloseButton ref={finalRef} />

        <ModalBody pb={6} gap="0px" paddingLeft="18px">
          {admin && (
            <>
              <FormGroup isRequired label="Id">
                <Text>{dataTrack?.id}</Text>
              </FormGroup>
              <FormGroup label="Data Id">
                <Text>{dataTrack?.dataId}</Text>
              </FormGroup>
              <FormGroup label="Action(s):">
                <Button
                  onClick={disclosure.onOpen}
                  marginRight="auto"
                  variant="@danger"
                >
                  <MdDeleteForever /> Remove Media
                </Button>
              </FormGroup>
              <ConfirmPopUp
                disclosure={disclosure}
                title="Remove track"
                body={`Remove Media [${dataTrack?.id}] ${dataTrack?.name}`}
                confirmTitle="Remove"
                onConfirm={onRemove}
              />
            </>
          )}
          {!admin && (
            <>
              <FormInput
                form={form}
                variableName="name"
                isRequired
                label="Title"
                ref={initialRef}
              />
              <FormTextarea
                form={form}
                variableName="description"
                label="Description"
              />
              <FormSelect
                form={form}
                variableName="genderId"
                options={dataGenders}
                label="Gender"
              />
              <FormSelectMultiple
                form={form}
                variableName="artists"
                options={dataArtist}
                label="Artist(s)"
              />
              <FormSelect
                form={form}
                variableName="albumId"
                options={dataAlbums}
                label="Album"
              />
              <FormNumber
                form={form}
                variableName="track"
                label="Track n°"
                step={1}
                defaultValue={0}
                min={0}
                max={1000}
              />
            </>
          )}
        </ModalBody>
        <ModalFooter>
          <Button
            onClick={() => setAdmin((value) => !value)}
            marginRight="auto"
          >
            {admin ? (
              <>
                <MdEdit />
                Edit
              </>
            ) : (
              <>
                <MdAdminPanelSettings />
                Admin
              </>
            )}
          </Button>
          {!admin && form.isFormModified && (
            <Button colorScheme="blue" mr={3} onClick={onSave}>
              Save
            </Button>
          )}
          <Button onClick={onClose}>Cancel</Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};
