import { useRef, useState } from 'react';

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

import { Gender, GenderResource } from '@/back-api';
import { FormCovers } from '@/components/form/FormCovers';
import { FormGroup } from '@/components/form/FormGroup';
import { FormInput } from '@/components/form/FormInput';
import { FormTextarea } from '@/components/form/FormTextarea';
import { useFormidable } from '@/components/form/Formidable';
import { ConfirmPopUp } from '@/components/popup/ConfirmPopUp';
import { useGenderService, useSpecificGender } from '@/service/Gender';
import { useServiceContext } from '@/service/ServiceContext';
import { useCountTracksOfAGender } from '@/service/Track';
import { isNullOrUndefined } from '@/utils/validator';

export type GenderEditPopUpProps = {};

export const GenderEditPopUp = ({ }: GenderEditPopUpProps) => {
  const { genderId } = useParams();
  const genderIdInt = isNullOrUndefined(genderId)
    ? undefined
    : parseInt(genderId, 10);
  const { session } = useServiceContext();
  const { countTracksOnAGender } = useCountTracksOfAGender(genderIdInt);
  const { store } = useGenderService();
  const { dataGender } = useSpecificGender(genderIdInt);
  const [admin, setAdmin] = useState(false);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(genderIdInt)) {
      return;
    }
    store.remove(
      genderIdInt,
      GenderResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: genderIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef(null);
  const finalRef = useRef(null);
  const form = useFormidable<Gender>({
    initialValues: dataGender,
  });
  const onSave = async () => {
    if (isNullOrUndefined(genderIdInt)) {
      return;
    }
    const dataThatNeedToBeUpdated = form.getDeltaData({ omit: ['covers'] });
    console.log(`onSave = ${JSON.stringify(dataThatNeedToBeUpdated, null, 2)}`);
    store.update(
      GenderResource.patch({
        restConfig: session.getRestConfig(),
        data: dataThatNeedToBeUpdated,
        params: {
          id: genderIdInt,
        },
      })
    );
  };
  const onUriSelected = (uri: string) => {
    if (isNullOrUndefined(genderIdInt)) {
      return;
    }
    store.update(
      GenderResource.uploadCover({
        restConfig: session.getRestConfig(),
        data: {
          uri: uri,
        },
        params: {
          id: genderIdInt,
        },
      })
    );
  };
  const onFilesSelected = (files: File[]) => {
    files.forEach((element) => {
      console.log(`Select file: '${element.name}'`);
    });
    if (isNullOrUndefined(genderIdInt)) {
      return;
    }
    store.update(
      GenderResource.uploadCover({
        restConfig: session.getRestConfig(),
        data: {
          file: files[0],
        },
        params: {
          id: genderIdInt,
        },
      })
    );
  };
  const onRemoveCover = (index: number) => {
    if (isNullOrUndefined(dataGender?.covers)) {
      return;
    }
    if (isNullOrUndefined(genderIdInt)) {
      return;
    }
    store.update(
      GenderResource.removeCover({
        restConfig: session.getRestConfig(),
        params: {
          id: genderIdInt,
          coverId: dataGender.covers[index],
        },
      })
    );
  };
  return (
    <Modal
      initialFocusRef={initialRef}
      finalFocusRef={finalRef}
      closeOnOverlayClick={false}
      onClose={onClose}
      isOpen={true}
    >
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>Edit Gender</ModalHeader>
        <ModalCloseButton ref={finalRef} />

        <ModalBody pb={6} gap="0px" paddingLeft="18px">
          {admin && (
            <>
              <FormGroup isRequired label="Id">
                <Text>{dataGender?.id}</Text>
              </FormGroup>
              {countTracksOnAGender !== 0 && (
                <Flex paddingLeft="14px">
                  <MdWarning color="red.600" />
                  <Text paddingLeft="6px" color="red.600" fontWeight="bold">
                    Can not remove gender {countTracksOnAGender} track(s) depend
                    on it.
                  </Text>
                </Flex>
              )}
              <FormGroup label="Action(s):">
                <Button
                  onClick={disclosure.onOpen}
                  marginRight="auto"
                  variant="@danger"
                  isDisabled={countTracksOnAGender !== 0}
                >
                  <MdDeleteForever /> Remove gender
                </Button>
              </FormGroup>
              <ConfirmPopUp
                disclosure={disclosure}
                title="Remove gender"
                body={`Remove gender [${dataGender?.id}] ${dataGender?.name}`}
                confirmTitle="Remove"
                onConfirm={onRemove}
              />
            </>
          )}
          {!admin && (
            <>
              <FormInput
                form={form}
                variableName="name"
                isRequired
                label="Gender name"
                ref={initialRef}
              />
              <FormTextarea
                form={form}
                variableName="description"
                label="Description"
              />
              <FormCovers
                form={form}
                variableName="covers"
                onFilesSelected={onFilesSelected}
                onUriSelected={onUriSelected}
                onRemove={onRemoveCover}
              />
            </>
          )}
        </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>
  );
};
