import { useRef, useState } from 'react';

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

import { SeasonResource, SeasonWrite } from '@/back-api';
import { FormCovers } from '@/components/form/FormCovers';
import { FormGroupShow } from '@/components/form/FormGroup';
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 { useSeasonCountVideo, useSeasonService, useSpecificSeason } from '@/service/Season';
import { useServiceContext } from '@/service/ServiceContext';
import { isNullOrUndefined } from '@/utils/validator';

import { Formidable, useFormidable } from '../formidable';
import { Button } from '../ui/button';

export type SeasonEditPopUpProps = {};

export const SeasonEditPopUp = ({}: SeasonEditPopUpProps) => {
  const { SeasonId } = useParams();
  const SeasonIdInt = isNullOrUndefined(SeasonId)
    ? undefined
    : parseInt(SeasonId, 10);
  const { session } = useServiceContext();
  const { seasonCountVideo } = useSeasonCountVideo(SeasonIdInt);
  const { store } = useSeasonService();
  const { dataSeason } = useSpecificSeason(SeasonIdInt);
  const [admin, setAdmin] = useState(false);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(SeasonIdInt)) {
      return;
    }
    store.remove(
      SeasonIdInt,
      SeasonResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: SeasonIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  const form = useFormidable<SeasonWrite>({
    initialValues: dataSeason,
    deltaConfig: { omit: ['covers'] },
  });
  const onSave = async (deltaData: SeasonWrite) => {
    if (isNullOrUndefined(SeasonIdInt)) {
      return;
    }
    console.log(`onSave = ${JSON.stringify(deltaData, null, 2)}`);
    store.update(
      SeasonResource.patch({
        restConfig: session.getRestConfig(),
        data: deltaData,
        params: {
          id: SeasonIdInt,
        },
      })
    );
  };

  const onUriSelected = (uri: string) => {
    if (isNullOrUndefined(SeasonIdInt)) {
      return;
    }
    console.error("not implemented");
    // store.update(
    //   SeasonResource.uploadCover({
    //     restConfig: session.getRestConfig(),
    //     data: {
    //       uri,
    //     },
    //     params: {
    //       id: SeasonIdInt,
    //     },
    //   })
    // );
  };

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

          <DialogBody pb={6} gap="0px" paddingLeft="18px">
            {admin && (
              <>
                <FormGroupShow isRequired label="Id">
                  <Text>{dataSeason?.id}</Text>
                </FormGroupShow>
                {seasonCountVideo !== 0 && (
                  <Flex paddingLeft="14px">
                    <MdWarning color="red.600" />
                    <Text paddingLeft="6px" color="red.600" fontWeight="bold">
                      Can not remove Season {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 Season"
                  body={`Remove Season [${dataSeason?.id}] ${dataSeason?.name}`}
                  confirmTitle="Remove"
                  onConfirm={onRemove}
                />
              </>
            )}
            {!admin && (
              <>
                <FormInput
                  name="name"
                  isRequired
                  label="Title"
                  ref={initialRef}
                />
                <FormTextarea name="description" label="Description" />
                <FormInput name="publication" label="Publication" />
                <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>
  );
};
