import { useRef } from 'react';

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

import { SeriesResource, SeriesUpdate, ZodSeriesUpdate } 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 { useSeasonCountVideo } from '@/service';
import { useSeriesService, useSpecificSeries } from '@/service/Series';
import { useServiceContext } from '@/service/ServiceContext';
import { isNullOrUndefined } from '@/utils/validator';

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

export type SeriesEditPopUpProps = {};

export const SeriesEditPopUp = ({}: SeriesEditPopUpProps) => {
  const { seriesId } = useParams();
  const seriesIdInt = isNullOrUndefined(seriesId)
    ? undefined
    : parseInt(seriesId, 10);
  const { session } = useServiceContext();
  const { seasonCountVideo } = useSeasonCountVideo(seriesIdInt);
  const { store } = useSeriesService();
  const { dataSeries } = useSpecificSeries(seriesIdInt);
  const navigate = useNavigate();
  const disclosure = useDisclosure();
  const onClose = () => {
    navigate('../../', { relative: 'path' });
  };
  const onRemove = () => {
    if (isNullOrUndefined(seriesIdInt)) {
      return;
    }
    store.remove(
      seriesIdInt,
      SeriesResource.remove({
        restConfig: session.getRestConfig(),
        params: {
          id: seriesIdInt,
        },
      })
    );
    onClose();
  };
  const initialRef = useRef<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  const form = useFormidable<SeriesUpdate>({
    initialValues: dataSeries,
    deltaConfig: { omit: ['covers'] },
  });
  const onSave = async (data: SeriesUpdate) => {
    if (isNullOrUndefined(seriesIdInt)) {
      return;
    }
    console.log(`onSave = ${JSON.stringify(data, null, 2)}`);
    store.update(
      SeriesResource.patch({
        restConfig: session.getRestConfig(),
        data: ZodSeriesUpdate.parse(data),
        params: {
          id: seriesIdInt,
        },
      })
    );
  };

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

          <DialogBody pb={6} gap="0px" paddingLeft="18px">
            <Tabs.Root defaultValue="edit" variant="outline">
              <Tabs.List>
                <Tabs.Trigger value="edit">
                  <MdEdit />
                  Edit
                </Tabs.Trigger>
                <Tabs.Trigger value="admin" colorPalette="@danger">
                  <MdAdminPanelSettings />
                  Admin
                </Tabs.Trigger>
              </Tabs.List>
              {/* ---------------------- Other Tabs --------------------------- */}
              <Tabs.Content value="edit">
                <FormInput
                  name="name"
                  isRequired
                  label="Series name"
                  ref={initialRef}
                />
                <FormTextarea name="description" label="Description" />
                <FormCovers
                  name="covers"
                  label="Covers"
                  onFilesSelected={onFilesSelected}
                  onUriSelected={onUriSelected}
                  onRemove={onRemoveCover}
                />
              </Tabs.Content>
              {/* ---------------------- Other Tabs --------------------------- */}
              <Tabs.Content value="admin">
                <FormGroupShow isRequired label="Id">
                  <Text>{dataSeries?.id}</Text>
                </FormGroupShow>
                {seasonCountVideo !== 0 && (
                  <Flex paddingLeft="14px">
                    <MdWarning color="red.600" />
                    <Text paddingLeft="6px" color="red.600" fontWeight="bold">
                      Can not remove Series {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 Series (not check)
                  </Button>
                </FormGroupShow>
                <ConfirmPopUp
                  disclosure={disclosure}
                  title="Remove Series"
                  body={`Remove Series [${dataSeries?.id}] ${dataSeries?.name}`}
                  confirmTitle="Remove"
                  onConfirm={onRemove}
                />
              </Tabs.Content>
            </Tabs.Root>
          </DialogBody>
          <DialogFooter>
            <Button onClick={onClose} marginRight="auto">
              Cancel
            </Button>
            {form.isFormModified && (
              <Button colorPalette="blue" type="submit">
                Save
              </Button>
            )}
          </DialogFooter>
        </Formidable.From>
      </DialogContent>
    </DialogRoot>
  );
};
