import { inject, observer } from 'mobx-react';
import { FC, useEffect, useState } from 'react';
import { Block, Elem } from '../../../utils/bem';
import { FF_DEV_2290, isFF } from '../../../utils/feature-flags';
import { Comments as CommentsComponent } from '../../Comments/Comments';
import { AnnotationHistory } from '../../CurrentEntity/AnnotationHistory';
import { PanelBase, PanelProps } from '../PanelBase';
import './DetailsPanel.styl';
import './DetailsPanel.css'; // Tailwind configurations, adjust the path accordingly
import { RegionDetailsMain, RegionDetailsMeta } from './RegionDetails';
import { RegionItem } from './RegionItem';
import { Relations as RelationsComponent } from './Relations';
import { Button, Checkbox, Image } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
// eslint-disable-next-line
// @ts-ignore
import { DraftPanel } from '../../DraftPanel/DraftPanel';
import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';

interface DetailsPanelProps extends PanelProps {
  regions: any;
  selection: any;
}

// My code
const LabelComponentCustom: FC<any> = inject('store')(observer(({ store }) => {
  const [existingLabels, setExistingLabels] = useState([]);

  useEffect(() => {
    store.invokeEvent('onEntityChange', store.annotationStore.selected);
    const currentAnnotations = store.annotationStore.selected.serializeAnnotation();

    setExistingLabels(currentAnnotations.map((annotation: any) => annotation.value[annotation.type][0]));
  }, [store.annotationStore.selected?.results]);

  return (
    <>
      {store?.customParams?.modelType ?
        (
          <Block name="custom-panel">
            <Elem name="section-head">라벨 리스트</Elem>
            <Block name="label-list">
              {store.customParams.labelTagExtract.map((label: any) => {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                if (!store.customParams.exhaustiveModelType?.includes(store.customParams.modelType) || !existingLabels.includes(label.props.item.value)) {
                  return (
                    <Elem key={label.key} name="label-item">
                      {label}
                    </Elem>
                  );
                } })}
            </Block>
          </Block>
        ) : (
          <div className="placeholder">
            <h1 className="placeholder-title">모델 종류를 선택해주세요.</h1>
          </div>
        )
      }
    </>
  );
}));

const ImageComponentCustom: FC<any> = inject('store')(observer(({ store }) => {
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>([]);
  const [numOfCheckedImages, setNumOfCheckedImages] = useState(0);
  const onCheckAll = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? store.customParams.images : []);
  };
  const onCheck = (e: CheckboxChangeEvent) => {
    setCheckedList((prevCheckedList) => {
      if (e.target.checked) {
        return [...prevCheckedList, e.target.value];
      } else {
        return prevCheckedList.filter((img) => img !== e.target.value);
      }
    });
  };

  // const findIndexById = (idToFind: number): number => {
  //   return Object.values(store.customParams?.images).findIndex((image: any) => image.id === idToFind);
  // };

  const onDeleteClick = () => {
    const isCurrentImageToBeDeleted = checkedList.includes(store?.customParams?.images[store?.customParams?.currentImageIndex]);
    const newImages = store.customParams.images.filter((img: any) => !checkedList.includes(img));

    store.setCustomParams('images', newImages);
    store.invokeEvent('deleteImages', checkedList, newImages);

    setCheckedList([]);
    setNumOfCheckedImages(store?.customParams?.images?.filter((img: any) => img.isChecked).length);

    // if the current image is deleted, set the current image index to -1
    if (isCurrentImageToBeDeleted) {
      store.setCustomParams('currentImageIndex', -1);
    }
  };

  useEffect(() => {
    store?.setNewTaskImage(selectedIndex);
  }, [selectedIndex]);

  useEffect(() => {
    if (store?.customParams?.debugLogs) {
      console.log('store?.customParams?.currentImageIndex: ', store?.customParams?.currentImageIndex);
    }

    setNumOfCheckedImages(store?.customParams?.images?.filter((img: any) => img.isChecked).length);

    // reinitialize selectedIndex so that previous image isn't stuck when refreshed
    setSelectedIndex(store?.customParams?.currentImageIndex);
  }, [store?.customParams?.currentImageIndex]);

  return (
    <div className="image-component-custom">
      {store?.customParams?.images?.length > 0 ? (
        <div className="component-container">
          <div className="top-bar">
            <div style={{ display: 'flex', gap: '16px' }}>
              <Checkbox
                checked={store?.customParams?.images?.length !== 0 && store?.customParams?.images?.length === checkedList?.length}
                onChange={(e) => onCheckAll(e)}
                value={checkedList}
              />
              <h1 className="image-name">
                {`(${numOfCheckedImages}/${store?.customParams?.images?.length})`}
              </h1>
            </div>
            <Button
              style={{ padding: '0 10px', marginLeft: 10 }}
              onClick={() => {
                if (store?.customParams?.debugLogs) {
                  console.log('checked: ', checkedList);
                }
                onDeleteClick();
              }}
            >
              선택삭제
            </Button>
          </div>
          <div className="image-list">
            {store?.customParams?.images?.map((img: any, index: number) => {
              const isTaskImage = img.id === store?.task?.id;

              return (
                <div
                  key={img?.id}
                  className={`image-block ${isTaskImage ? 'is-task-image' : `hover-bg ${index % 2 === 0 ? 'even-bg' : 'odd-bg'}`}`}
                >
                  <Checkbox
                    value={img}
                    onChange={(e: CheckboxChangeEvent) => onCheck(e)}
                    checked={checkedList.indexOf(img) > -1}
                  />
                  {img?.isChecked ? (
                    <CheckCircleFilled
                      style={{ fontSize: 20, color: '#52c41a', backgroundColor: 'white', borderRadius: '100%' }}
                    />
                  ) : (
                    <CloseCircleFilled
                      style={{ fontSize: 20, color: 'red', backgroundColor: 'white', borderRadius: '100%' }}
                    />
                  )}
                  <div
                    onClick={() => setSelectedIndex(index)}
                    className="image-area"
                  >
                    <h2 className="image-id">
                      {index + 1}
                    </h2>
                    <div
                      className="image-preview"
                      onClick={(e) => {
                        e.stopPropagation();
                      }}
                    >
                      <Image
                        width={160}
                        height={90}
                        src={img?.data?.image}
                        style={{
                          backgroundColor: '#f5f5f5',
                          objectFit: 'contain',
                          objectPosition: 'center',
                          flexShrink: '0',
                        }}
                      />
                    </div>
                    <h1 className="image-name">
                      {img?.data?.title}
                    </h1>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ) : (
        <div className="placeholder">
          <h1 className="placeholder-title">학습 이미지를 추가해주세요.</h1>
        </div>
      )}
    </div>
  );
}));
// End of my code

const DetailsPanelComponent: FC<DetailsPanelProps> = ({ currentEntity, regions, ...props }) => {
  const selectedRegions = regions.selection;

  return (
    <PanelBase {...props} currentEntity={currentEntity} name="details" title="Details">
      <Content selection={selectedRegions} currentEntity={currentEntity} />
    </PanelBase>
  );
};

const DetailsComponent: FC<DetailsPanelProps> = ({ currentEntity, regions }) => {
  const selectedRegions = regions.selection;

  return (
    <Block name="details-tab">
      <Content selection={selectedRegions} currentEntity={currentEntity} />
    </Block>
  );
};


const Content: FC<any> = observer(({
  selection,
  currentEntity,
}) => {
  return (
    <>
      {(selection.size) ? (
        <RegionsPanel regions={selection}/>
      ) : (
        <GeneralPanel currentEntity={currentEntity}/>
      )}
    </>
  );
});


const CommentsTab: FC<any> = inject('store')(observer(({ store }) => {
  return (
    <>
      {store.hasInterface('annotations:comments') && store.commentStore.isCommentable && (
        <Block name="comments-panel">
          <Elem name="section-tab">
            <Elem name="section-content">
              <CommentsComponent commentStore={store.commentStore} cacheKey={`task.${store.task.id}`} />
            </Elem>
          </Elem>
        </Block>
      )}
    </>
  );
}));

const RelationsTab: FC<any> = inject('store')(observer(({ currentEntity }) => {
  const { relationStore } = currentEntity;

  return (
    <>
      <Block name="relations">
        <Elem name="section-tab">
          <Elem name="section-head">Relations ({relationStore.size})</Elem>
          <Elem name="section-content">
            <RelationsComponent relationStore={relationStore} />
          </Elem>
        </Elem>
      </Block>
    </>
  );
}));

const HistoryTab: FC<any> = inject('store')(observer(({ store, currentEntity }) => {
  const showAnnotationHistory = store.hasInterface('annotations:history');
  const showDraftInHistory = isFF(FF_DEV_2290);

  return (
    <>
      <Block name="history">
        {!showDraftInHistory ? (
          <DraftPanel item={currentEntity} />
        ) : (
          <Elem name="section-tab">
            <Elem name="section-head">
              Annotation History
              <span>#{currentEntity.pk ?? currentEntity.id}</span>
            </Elem>
            <Elem name="section-content">
              <AnnotationHistory inline showDraft={showDraftInHistory} enabled={showAnnotationHistory} />
            </Elem>
          </Elem>
        )}
      </Block>
    </>
  );
}));


const InfoTab: FC<any> = inject('store')(
  observer(({ selection }) => {
    return (
      <>
        <Block name="info">
          <Elem name="section-tab">
            <Elem name="section-head">Selection Details</Elem>
            <RegionsPanel regions={selection}/>
          </Elem>
        </Block>
      </>
    );
  }),
);

const GeneralPanel: FC<any> = inject('store')(observer(({ store, currentEntity }) => {
  const { relationStore } = currentEntity;
  const showAnnotationHistory = store.hasInterface('annotations:history');
  const showDraftInHistory = isFF(FF_DEV_2290);

  return (
    <>
      {!showDraftInHistory ? (
        <DraftPanel item={currentEntity} />
      ) : (
        <Elem name="section">
          <Elem name="section-head">
              Annotation History
            <span>#{currentEntity.pk ?? currentEntity.id}</span>
          </Elem>
          <Elem name="section-content">
            <AnnotationHistory
              inline
              showDraft={showDraftInHistory}
              enabled={showAnnotationHistory}
            />
          </Elem>
        </Elem>
      )}
      <Elem name="section">
        <Elem name="section-head">
          Relations ({relationStore.size})
        </Elem>
        <Elem name="section-content">
          <RelationsComponent
            relationStore={relationStore}
          />
        </Elem>
      </Elem>
      {store.hasInterface('annotations:comments') && store.commentStore.isCommentable && (
        <Elem name="section">
          <Elem name="section-head">
            Comments
          </Elem>
          <Elem name="section-content">
            <CommentsComponent
              commentStore={store.commentStore}
              cacheKey={`task.${store.task.id}`}
            />
          </Elem>
        </Elem>
      )}
    </>
  );
}));

GeneralPanel.displayName = 'GeneralPanel';

const RegionsPanel: FC<{regions: any}> = observer(({
  regions,
}) => {
  return (
    <div>
      {regions.list.map((reg: any) => {
        return (
          <SelectedRegion key={reg.id} region={reg}/>
        );
      })}
    </div>
  );
});

const SelectedRegion: FC<{region: any}> = observer(({
  region,
}) => {
  return (
    <RegionItem
      region={region}
      mainDetails={RegionDetailsMain}
      metaDetails={RegionDetailsMeta}
    />
  );
});

export const Images = ImageComponentCustom;
export const Labels = observer(LabelComponentCustom);
export const Comments = observer(CommentsTab);
export const History = observer(HistoryTab);
export const Relations = observer(RelationsTab);
export const Info = observer(InfoTab);
export const Details = observer(DetailsComponent);
export const DetailsPanel = observer(DetailsPanelComponent);
