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 { TypeResource, TypeWrite } 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 { useServiceContext, useSpecificType, useTypeCountVideo, useTypeService } from '@/service';
import { isNullOrUndefined } from '@/utils/validator';

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

export type TypeEditPopUpProps = {};

export const TypeEditPopUp = ({}: TypeEditPopUpProps) => {
  const { TypeId } = useParams();
  const TypeIdInt = isNullOrUndefined(TypeId)
    ? undefined
    : parseInt(TypeId, 10);
  const { session } = useServiceContext();
  const { countVideoWithType } = useTypeCountVideo(TypeIdInt);
  const { store } = useTypeService();
  const { dataType } = useSpecificType(TypeIdInt);
  const [admin, setAdmin] = useState(false);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(TypeIdInt)) {
      return;
    }
    store.remove(
      TypeIdInt,
      TypeResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: TypeIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  const form = useFormidable<TypeWrite>({
    initialValues: dataType,
    deltaConfig: { omit: ['covers'] },
  });
  const onSave = async (dataDelta: TypeWrite) => {
    if (isNullOrUndefined(TypeIdInt)) {
      return;
    }
    console.log(`onSave = ${JSON.stringify(dataDelta, null, 2)}`);
    store.update(
      TypeResource.patch({
        restConfig: session.getRestConfig(),
        data: dataDelta,
        params: {
          id: TypeIdInt,
        },
      })
    );
  };
  const onUriSelected = (uri: string) => {
    if (isNullOrUndefined(TypeIdInt)) {
      return;
    }
    console.error("Not implemented");
    // store.update(
    //   TypeResource.uploadCover({
    //     restConfig: session.getRestConfig(),
    //     data: {
    //       uri,
    //     },
    //     params: {
    //       id: TypeIdInt,
    //     },
    //   })
    // );
  };
  const onFilesSelected = (files: File[]) => {
    files.forEach((element) => {
      console.log(`Select file: '${element.name}'`);
    });
    if (isNullOrUndefined(TypeIdInt)) {
      return;
    }
    store.update(
      TypeResource.uploadCover({
        restConfig: session.getRestConfig(),
        data: {
          file: files[0],
        },
        params: {
          id: TypeIdInt,
        },
      })
    );
  };
  const onRemoveCover = (index: number) => {
    if (isNullOrUndefined(dataType?.covers)) {
      return;
    }
    if (isNullOrUndefined(TypeIdInt)) {
      return;
    }
    store.update(
      TypeResource.removeCover({
        restConfig: session.getRestConfig(),
        params: {
          id: TypeIdInt,
          coverId: dataType.covers[index],
        },
      })
    );
  };
  return (
    <DialogRoot
      //initialFocusRef={initialRef}
      //finalFocusRef={finalRef}
      //closeOnOverlayClick={false}
      onOpenChange={onClose}
      open={true}
      data-testid="Type-edit-pop-up"
    >
      {/* <DialogOverlay /> */}
      <DialogContent>
        <Formidable.From form={form} onSubmitDelta={onSave}>
          <DialogHeader>Edit Type</DialogHeader>
          {/* <DialogCloseButton ref={finalRef} /> */}

          <DialogBody pb={6} gap="0px" paddingLeft="18px">
            {admin && (
              <>
                <FormGroupShow isRequired label="Id">
                  <Text>{dataType?.id}</Text>
                </FormGroupShow>
                {countVideoWithType !== 0 && (
                  <Flex paddingLeft="14px">
                    <MdWarning color="red.600" />
                    <Text paddingLeft="6px" color="red.600" fontWeight="bold">
                      Can not remove Type {countVideoWithType} Media(s)
                      depend on it.
                    </Text>
                  </Flex>
                )}
                <FormGroupShow label="Action(s):">
                  <Button
                    onClick={disclosure.onOpen}
                    marginRight="auto"
                    colorPalette="@danger"
                    disabled={countVideoWithType !== 0}
                  >
                    <MdDeleteForever /> Remove Type
                  </Button>
                </FormGroupShow>
                <ConfirmPopUp
                  disclosure={disclosure}
                  title="Remove Type"
                  body={`Remove Type [${dataType?.id}] ${dataType?.name}`}
                  confirmTitle="Remove"
                  onConfirm={onRemove}
                />
              </>
            )}
            {!admin && (
              <>
                <FormInput
                  name="name"
                  isRequired
                  label="Type name"
                  ref={initialRef}
                />
                <FormTextarea name="description" label="Description" />
                <FormCovers
                  name="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} type="submit">
                Save
              </Button>
            )}
            <Button onClick={onClose}>Cancel</Button>
          </DialogFooter>
        </Formidable.From>
      </DialogContent>
    </DialogRoot>
  );
};
