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 { DataExtensionState } from '@wix/bex-core';
import type { ArchivedItem } from './types';

export interface ArchivedItemsPanelProps {
  items: ArchivedItem[];
  onBackButtonClick: () => void;
  onCloseButtonClick: () => void;
  dataExtension: DataExtensionState;
  dataHook?: string;
}

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

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

  const closeIfEmpty = () => {
    const remainingItems = dataExtension.archivedItems;
    if (remainingItems.length === 0) {
      handleBack();
    }
  };

  const handleRestore = async (item: ArchivedItem) => {
    await dataExtension.restoreField({
      id: item.id,
      origin: 'Archived items panel',
      reportBi: dataExtension.container.createBILogger({
        componentType: 'ArchivedItemsPanel',
      }),
    });

    closeIfEmpty();
  };

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

  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);
