import { useRef, useState } from 'react';

import { Button, Text, useDisclosure } from '@chakra-ui/react';
import { MdAdminPanelSettings, MdDeleteForever, MdEdit } from 'react-icons/md';
import { useNavigate, useParams } from 'react-router-dom';

import { TrackResource, TrackWrite } from '@/back-api';
import { FormGroupShow } 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 { ConfirmPopUp } from '@/components/popup/ConfirmPopUp';
import {
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
} from '@/components/ui/dialog';
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';

import { Formidable, useFormidable } from '../formidable';

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<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  const form = useFormidable<TrackWrite>({
    initialValues: dataTrack,
    deltaConfig: { omit: ['covers'] },
  });
  const onSave = async (dataDelta: TrackWrite) => {
    if (isNullOrUndefined(trackIdInt)) {
      return;
    }
    console.log(`onSave = ${JSON.stringify(dataDelta, null, 2)}`);
    store.update(
      TrackResource.patch({
        restConfig: session.getRestConfig(),
        data: dataDelta,
        params: {
          id: trackIdInt,
        },
      })
    );
  };
  return (
    <DialogRoot
      //initialFocusRef={initialRef}
      //finalFocusRef={finalRef}
      //closeOnOverlayClick={false}
      onOpenChange={onClose}
      open={true}
      data-testid="track-edit-pop-up"
    >
      {/* <DialogOverlay /> */}
      <DialogContent>
        <Formidable.From form={form} onSubmitDelta={onSave}>
          <DialogHeader>Edit Track</DialogHeader>
          {/* <DialogCloseButton ref={finalRef} /> */}

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