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 { MediaResource, MediaWrite } 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 { useMediaService, useSpecificMedia } from '@/service/Media';
import { useOrderedSeasons } from '@/service/Season';
import { useOrderedSeries } from '@/service/Series';
import { useServiceContext } from '@/service/ServiceContext';
import { useOrderedTypes } from '@/service/Type';
import { isNullOrUndefined } from '@/utils/validator';

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

export type MediaEditPopUpProps = {};

export const MediaEditPopUp = ({}: MediaEditPopUpProps) => {
  const { MediaId } = useParams();
  const MediaIdInt = isNullOrUndefined(MediaId)
    ? undefined
    : parseInt(MediaId, 10);
  const { session } = useServiceContext();
  const { dataTypes } = useOrderedTypes(undefined);
  const { dataSeries } = useOrderedSeries(undefined);
  const { dataSeasons } = useOrderedSeasons(undefined);
  const { store } = useMediaService();
  const { dataMedia } = useSpecificMedia(MediaIdInt);
  const [admin, setAdmin] = useState(false);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(MediaIdInt)) {
      return;
    }
    store.remove(
      MediaIdInt,
      MediaResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: MediaIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  const form = useFormidable<MediaWrite>({
    initialValues: dataMedia,
    deltaConfig: { omit: ['covers'] },
  });
  const onSave = async (dataDelta: MediaWrite) => {
    if (isNullOrUndefined(MediaIdInt)) {
      return;
    }
    console.log(`onSave = ${JSON.stringify(dataDelta, null, 2)}`);
    store.update(
      MediaResource.patch({
        restConfig: session.getRestConfig(),
        data: dataDelta,
        params: {
          id: MediaIdInt,
        },
      })
    );
  };
  return (
    <DialogRoot
      //initialFocusRef={initialRef}
      //finalFocusRef={finalRef}
      //closeOnOverlayClick={false}
      onOpenChange={onClose}
      open={true}
      data-testid="Media-edit-pop-up"
    >
      {/* <DialogOverlay /> */}
      <DialogContent>
        <Formidable.From form={form} onSubmitDelta={onSave}>
          <DialogHeader>Edit Media</DialogHeader>
          {/* <DialogCloseButton ref={finalRef} /> */}

          <DialogBody pb={6} gap="0px" paddingLeft="18px">
            {admin && (
              <>
                <FormGroupShow isRequired label="Id">
                  <Text>{dataMedia?.id}</Text>
                </FormGroupShow>
                <FormGroupShow label="Data Id">
                  <Text>{dataMedia?.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 Media"
                  body={`Remove Media [${dataMedia?.id}] ${dataMedia?.name}`}
                  confirmTitle="Remove"
                  onConfirm={onRemove}
                />
              </>
            )}
            {!admin && (
              <>
                <FormInput
                  name="name"
                  isRequired
                  label="Title"
                  ref={initialRef}
                />
                <FormTextarea name="description" label="Description" />
                <FormSelect
                  name="TypeId"
                  options={dataTypes}
                  label="Type"
                />
                <FormSelectMultiple
                  name="Series"
                  options={dataSeries}
                  label="Series(s)"
                />
                <FormSelect name="SeasonId" options={dataSeasons} label="Season" />
                <FormNumber
                  name="Media"
                  label="Media 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>
  );
};
