import { SidePanel } from '@wix/design-system';
import React, {
  CSSProperties,
  useMemo,
  useEffect,
  useState,
  useCallback,
} from 'react';
import { observer } from 'mobx-react-lite';
import { ScrollableContent } from '../ScrollableContent';
import { ArchivedItemsList } from './ArchivedItemsList';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import type { DeleteFieldModalState, FieldArchive } from '@wix/bex-core';
import type { ArchivedItem } from './types';

export interface ArchivedItemsPanelProps {
  items: ArchivedItem[];
  onBackButtonClick: () => void;
  onCloseButtonClick: () => void;
  archive: FieldArchive;
  /** The shared delete-field modal, opened when an archived field is deleted. */
  deleteFieldModal: DeleteFieldModalState;
  dataHook?: string;
}

function _ArchivedItemsPanel({
  items,
  onBackButtonClick,
  onCloseButtonClick,
  archive,
  deleteFieldModal,
  dataHook = 'custom-columns',
}: ArchivedItemsPanelProps) {
  const { translate: t } = useWixPatternsContainer();
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    setTimeout(() => setIsVisible(true), 10);
  }, []);

  const closeIfEmpty = () => {
    if (archive.items.length === 0) {
      handleBack();
    }
  };

  const handleRestore = async (item: ArchivedItem) => {
    await archive.restoreField(item.id, 'Archived items panel');
    closeIfEmpty();
  };

  const handleDelete = useCallback(
    (item: ArchivedItem) => {
      deleteFieldModal.modal.open({
        id: item.id,
        origin: 'Archived items panel',
        fieldName: archive.fieldName(item.id),
      });
    },
    [archive, deleteFieldModal],
  );

  const slideStyle = useMemo<CSSProperties>(
    () => ({
      position: 'absolute',
      top: 0,
      right: isVisible ? 0 : '-600px',
      bottom: 0,
      width: '100%',
      maxWidth: '600px',
      backgroundColor: 'white',
      transition: 'right 0.3s ease-out',
      display: 'flex',
      flexDirection: 'column',
      zIndex: 1,
    }),
    [isVisible],
  );

  const handleBack = useCallback(() => {
    // Trigger slide-out animation
    setIsVisible(false);
    // Wait for animation to complete before calling onBackButtonClick
    setTimeout(() => {
      onBackButtonClick();
    }, 300); // Match the transition duration
  }, [onBackButtonClick]);

  const handleClose = useCallback(() => {
    // Trigger slide-out animation
    setIsVisible(false);
    // Close both panels immediately so they animate together
    onCloseButtonClick();
  }, [onCloseButtonClick]);

  const tooltipKey = useMemo(() => {
    return dataHook === 'custom-columns'
      ? 'cairo.archivedFields.back.custom-columns.tooltip'
      : 'cairo.archivedFields.back.manage-custom-fields.tooltip';
  }, [dataHook]);

  return (
    <div
      data-hook={`${dataHook}-archived-items-panel-container`}
      style={slideStyle}
      onClick={(e) => e.stopPropagation()}
    >
      <SidePanel // PatternsSidePanel is overriding the back button to close the panel
        dataHook={`${dataHook}-archived-items-panel`}
        width="100%"
        closeButtonProps={{ onClick: handleClose }}
        onBackButtonClick={handleBack}
        backButtonProps={{
          description: t(tooltipKey),
          tooltipProps: {
            moveArrowTo: 80,
          },
        }}
      >
        <SidePanel.Header
          title={t('cairo.archivedFields.title')}
          subtitle={t('cairo.archivedFields.subtitle')}
        />
        <ScrollableContent
          overflowY
          dataHook={`${dataHook}-archived-items-panel-scroll-container`}
        >
          <ArchivedItemsList
            items={items}
            onRestore={handleRestore}
            onDelete={handleDelete}
            dataHook={dataHook}
          />
        </ScrollableContent>
      </SidePanel>
    </div>
  );
}

export const ArchivedItemsPanel = observer(_ArchivedItemsPanel);
