/**
 * Custom hook for handling modeler close functionality
 * Manages close, save and close, and minimize actions
 */

import { useCallback, useRef, useEffect } from 'react';
import { useStore } from '../store/store';
import type { Settings } from '../types/settings';

interface UseCloseHandlerProps {
  settings: Settings;
  hasUnsavedChanges: boolean;
  showConfirmationDialog: (
    title: string,
    message: string,
    type: 'danger' | 'warning' | 'info',
    onSaveAndCloseCallback?: () => void,
    onCloseWithoutSaveCallback?: () => void
  ) => void;
}

// ID for the restore bar element
const RESTORE_BAR_ID = 'workflow-modeler-restore-bar';

export function useCloseHandler({
  settings,
  hasUnsavedChanges,
  showConfirmationDialog,
}: UseCloseHandlerProps) {
  const pendingCloseAfterSaveRef = useRef(false);
  const saveButtonRef = useRef<HTMLButtonElement>(null);
  const modelData = useStore(state => state.modelData);

  // Remove the restore bar from the DOM
  const removeRestoreBar = useCallback(() => {
    const existingBar = document.getElementById(RESTORE_BAR_ID);
    if (existingBar) {
      existingBar.remove();
    }
  }, []);

  // Restore the modeler from minimized state
  const handleRestore = useCallback(() => {
    const wrapper = document.getElementById('workflow-modeler-wrapper');
    if (wrapper) {
      wrapper.style.display = '';
    }
    removeRestoreBar();
  }, [removeRestoreBar]);

  // Create and show the restore bar
  const createRestoreBar = useCallback(() => {
    // Remove any existing restore bar first
    removeRestoreBar();

    // Get the model name
    const modelName = modelData?.metadata?.label || 'Workflow Modeler';

    // Create the restore bar element
    const restoreBar = document.createElement('div');
    restoreBar.id = RESTORE_BAR_ID;
    restoreBar.className = 'workflow-restore-bar';

    // Create the restore button
    const restoreBtn = document.createElement('button');
    restoreBtn.type = 'button';
    restoreBtn.className = 'restore-btn';
    restoreBtn.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <polyline points="15 3 21 3 21 9"></polyline>
        <polyline points="9 21 3 21 3 15"></polyline>
        <line x1="21" y1="3" x2="14" y2="10"></line>
        <line x1="3" y1="21" x2="10" y2="14"></line>
      </svg>
      <span>${modelName}</span>
    `;
    restoreBtn.title = 'Restore Modeler';
    restoreBtn.onclick = handleRestore;

    restoreBar.appendChild(restoreBtn);

    // Append to body so it's visible when wrapper is hidden
    document.body.appendChild(restoreBar);
  }, [modelData?.metadata?.label, handleRestore, removeRestoreBar]);

  // Cleanup restore bar on unmount
  useEffect(() => {
    return () => {
      removeRestoreBar();
    };
  }, [removeRestoreBar]);

  // Perform the actual close action
  const performClose = useCallback(() => {
    // Always remove restore bar when closing
    removeRestoreBar();

    if (settings.modeler?.stayInContextOnClose) {
      // Close the overlay by hiding the modeler wrapper
      const wrapper = document.getElementById('workflow-modeler-wrapper');
      if (wrapper) {
        wrapper.style.display = 'none';
      }
    } else {
      // Navigate to collection URL
      const collectionUrl = settings.modeler_api?.collection_url;
      if (collectionUrl) {
        window.location.href = collectionUrl;
      }
    }
  }, [settings, removeRestoreBar]);

  // Handle save and close - triggers save then closes on completion
  const handleSaveAndClose = useCallback(() => {
    pendingCloseAfterSaveRef.current = true;
    // Trigger save by clicking the save button
    if (saveButtonRef.current) {
      saveButtonRef.current.click();
    }
  }, []);

  // Handle close with unsaved changes check
  const handleClose = useCallback(() => {
    if (hasUnsavedChanges) {
      showConfirmationDialog(
        'Unsaved Changes',
        'You have unsaved changes. What would you like to do?',
        'warning',
        handleSaveAndClose,
        performClose
      );
    } else {
      performClose();
    }
  }, [hasUnsavedChanges, showConfirmationDialog, handleSaveAndClose, performClose]);

  // Handle minimize - hides the modeler wrapper and shows restore bar
  const handleMinimize = useCallback(() => {
    const wrapper = document.getElementById('workflow-modeler-wrapper');
    if (wrapper) {
      wrapper.style.display = 'none';
    }
    // Show the restore bar
    createRestoreBar();
  }, [createRestoreBar]);

  // Callback for when save completes - checks if we should close
  const handleSaveComplete = useCallback((setHasUnsavedChanges: (value: boolean) => void) => {
    setHasUnsavedChanges(false);
    if (pendingCloseAfterSaveRef.current) {
      pendingCloseAfterSaveRef.current = false;
      performClose();
    }
  }, [performClose]);

  return {
    handleClose,
    handleMinimize,
    handleSaveComplete,
    saveButtonRef,
  };
}
