import { useRef, useState } from 'react';

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

import { Artist, ArtistResource } 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 { useArtistService, useSpecificArtist } from '@/service/Artist';
import { useServiceContext } from '@/service/ServiceContext';
import { useCountTracksOfAnArtist } from '@/service/Track';
import { isNullOrUndefined } from '@/utils/validator';

export type ArtistEditPopUpProps = {};

export const ArtistEditPopUp = ({ }: ArtistEditPopUpProps) => {
  const { artistId } = useParams();
  const artistIdInt = isNullOrUndefined(artistId)
    ? undefined
    : parseInt(artistId, 10);
  const { session } = useServiceContext();
  const { countTracksOnAnArtist } = useCountTracksOfAnArtist(artistIdInt);
  const { store } = useArtistService();
  const { dataArtist } = useSpecificArtist(artistIdInt);
  const [admin, setAdmin] = useState(false);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(artistIdInt)) {
      return;
    }
    store.remove(
      artistIdInt,
      ArtistResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: artistIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  const form = useFormidable<Artist>({
    initialValues: dataArtist,
  });
  const onSave = async () => {
    if (isNullOrUndefined(artistIdInt)) {
      return;
    }
    const dataThatNeedToBeUpdated = form.getDeltaData({ omit: ['covers'] });
    console.log(`onSave = ${JSON.stringify(dataThatNeedToBeUpdated, null, 2)}`);
    store.update(
      ArtistResource.patch({
        restConfig: session.getRestConfig(),
        data: dataThatNeedToBeUpdated,
        params: {
          id: artistIdInt,
        },
      })
    );
  };

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

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