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

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

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<Partial<ArtistUpdate>>({
    initialValues: dataArtist,
    deltaConfig: { omit: ['covers'] },
  });
  const onSave = async (dataDelta: Partial<ArtistUpdate>) => {
    if (isNullOrUndefined(artistIdInt)) {
      return;
    }
    console.log(`onSave = ${JSON.stringify(dataDelta, null, 2)}`);
    store.update(
      ArtistResource.patch({
        restConfig: session.getRestConfig(),
        data: dataDelta,
        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>
        <Formidable.From form={form} onSubmitDelta={onSave}>
          <DialogHeader>Edit Artist</DialogHeader>
          {/* <DialogCloseButton ref={finalRef} /> */}

          <DialogBody pb={6} gap="0px" paddingLeft="18px">
            {admin && (
              <>
                <FormGroupShow isRequired label="Id">
                  <Text>{dataArtist?.id}</Text>
                </FormGroupShow>
                {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>
                )}
                <FormGroupShow label="Action(s):">
                  <Button
                    onClick={disclosure.onOpen}
                    marginRight="auto"
                    colorPalette="@danger"
                    disabled={countTracksOnAnArtist !== 0}
                  >
                    <MdDeleteForever /> Remove Media
                  </Button>
                </FormGroupShow>
                <ConfirmPopUp
                  disclosure={disclosure}
                  title="Remove artist"
                  body={`Remove Artist [${dataArtist?.id}] ${dataArtist?.name}`}
                  confirmTitle="Remove"
                  onConfirm={onRemove}
                />
              </>
            )}
            {!admin && (
              <>
                <FormInput
                  name="name"
                  isRequired
                  label="Artist 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>
  );
};
