import { useRef, useState } from 'react';

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

import { SeriesResource, SeriesWrite } from '@/back-api';
import { FormCovers } from '@/components/form/FormCovers';
import { FormInput } from '@/components/form/FormInput';
import { FormTextarea } from '@/components/form/FormTextarea';
import { ConfirmPopUp } from '@/components/popup/ConfirmPopUp';
import {
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
} from '@/components/ui/dialog';
import { useSeriesService, useSpecificSeries } from '@/service/Series';
import { useServiceContext } from '@/service/ServiceContext';
import { isNullOrUndefined } from '@/utils/validator';

import { useSeasonCountVideo } from '@/service';
import { FormGroupShow } from '../form/FormGroup';
import { Formidable, useFormidable } from '../formidable';

export type SeriesEditPopUpProps = {};

export const SeriesEditPopUp = ({}: SeriesEditPopUpProps) => {
  const { SeriesId } = useParams();
  const SeriesIdInt = isNullOrUndefined(SeriesId)
    ? undefined
    : parseInt(SeriesId, 10);
  const { session } = useServiceContext();
  const { seasonCountVideo } = useSeasonCountVideo(SeriesIdInt);
  const { store } = useSeriesService();
  const { dataSeries } = useSpecificSeries(SeriesIdInt);
  const [admin, setAdmin] = useState(false);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(SeriesIdInt)) {
      return;
    }
    store.remove(
      SeriesIdInt,
      SeriesResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: SeriesIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  const form = useFormidable<SeriesWrite>({
    initialValues: dataSeries,
    deltaConfig: { omit: ['covers'] },
  });
  const onSave = async (dataDelta: SeriesWrite) => {
    if (isNullOrUndefined(SeriesIdInt)) {
      return;
    }
    console.log(`onSave = ${JSON.stringify(dataDelta, null, 2)}`);
    store.update(
      SeriesResource.patch({
        restConfig: session.getRestConfig(),
        data: dataDelta,
        params: {
          id: SeriesIdInt,
        },
      })
    );
  };

  const onUriSelected = (uri: string) => {
    if (isNullOrUndefined(SeriesIdInt)) {
      return;
    }
    console.error("Not implemented");
    // store.update(
    //   SeriesResource.uploadCover({
    //     restConfig: session.getRestConfig(),
    //     data: {
    //       uri,
    //     },
    //     params: {
    //       id: SeriesIdInt,
    //     },
    //   })
    // );
  };
  const onFilesSelected = (files: File[]) => {
    files.forEach((element) => {
      console.log(`Select file: '${element.name}'`);
    });
    if (isNullOrUndefined(SeriesIdInt)) {
      return;
    }
    store.update(
      SeriesResource.uploadCover({
        restConfig: session.getRestConfig(),
        data: {
          file: files[0],
        },
        params: {
          id: SeriesIdInt,
        },
      })
    );
  };
  const onRemoveCover = (index: number) => {
    if (isNullOrUndefined(dataSeries?.covers)) {
      return;
    }
    if (isNullOrUndefined(SeriesIdInt)) {
      return;
    }
    store.update(
      SeriesResource.removeCover({
        restConfig: session.getRestConfig(),
        params: {
          id: SeriesIdInt,
          coverId: dataSeries.covers[index],
        },
      })
    );
  };
  return (
    <DialogRoot
      //initialFocusRef={initialRef}
      //finalFocusRef={finalRef}
      //closeOnOverlayClick={false}
      onOpenChange={onClose}
      open={true}
      data-testid="Series-edit-pop-up"
    >
      {/* <DialogOverlay /> */}
      <DialogContent>
        <Formidable.From form={form} onSubmitDelta={onSave}>
          <DialogHeader>Edit Series</DialogHeader>
          {/* <DialogCloseButton ref={finalRef} /> */}

          <DialogBody pb={6} gap="0px" paddingLeft="18px">
            {admin && (
              <>
                <FormGroupShow isRequired label="Id">
                  <Text>{dataSeries?.id}</Text>
                </FormGroupShow>
                {seasonCountVideo !== 0 && (
                  <Flex paddingLeft="14px">
                    <MdWarning color="red.600" />
                    <Text paddingLeft="6px" color="red.600" fontWeight="bold">
                      Can not remove Series {seasonCountVideo} Media(s)
                      depend on it.
                    </Text>
                  </Flex>
                )}
                <FormGroupShow label="Action(s):">
                  <Button
                    onClick={disclosure.onOpen}
                    marginRight="auto"
                    colorPalette="@danger"
                    disabled={seasonCountVideo !== 0}
                  >
                    <MdDeleteForever /> Remove Media
                  </Button>
                </FormGroupShow>
                <ConfirmPopUp
                  disclosure={disclosure}
                  title="Remove Series"
                  body={`Remove Series [${dataSeries?.id}] ${dataSeries?.name}`}
                  confirmTitle="Remove"
                  onConfirm={onRemove}
                />
              </>
            )}
            {!admin && (
              <>
                <FormInput
                  name="name"
                  isRequired
                  label="Series name"
                  ref={initialRef}
                />
                <FormTextarea name="description" label="Description" />
                <FormInput name="firstName" label="First Name" />
                <FormInput name="surname" label="SurName" />
                <FormInput name="birth" label="Birth date" />
                <FormInput name="death" label="Death date" />
                <FormCovers
                  name="covers"
                  onFilesSelected={onFilesSelected}
                  onUriSelected={onUriSelected}
                  onRemove={onRemoveCover}
                />
              </>
            )}
          </DialogBody>
          <DialogFooter>
            <Button
              onClick={() => setAdmin((value) => !value)}
              marginRight="auto"
              colorPalette={admin ? undefined : '@danger'}
            >
              {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>
  );
};
