import { useCallback, useState, ReactNode } from 'react';
import { useEditorStore } from '@/core/store';
import { useSecurity } from '@/contexts/SecurityContext';
import { isSecureItem, getSecureFolderId } from '@/lib/security-utils';
import { SecureUnlockDialog } from '@/components/SecureUnlockDialog';

/**
 * Hook that wraps openFile with security checks
 * Returns a secure version of openFile that checks if files/folders are unlocked before opening
 */
export function useSecureFileOpen() {
  const { files, openFile: storeOpenFile } = useEditorStore();
  const { isUnlocked } = useSecurity();
  const [unlockDialogState, setUnlockDialogState] = useState<{
    open: boolean;
    itemId: string | null;
    itemName: string;
    itemType: 'file' | 'folder';
    fileIdToOpen: string | null;
  }>({
    open: false,
    itemId: null,
    itemName: '',
    itemType: 'file',
    fileIdToOpen: null,
  });

  const secureOpenFile = useCallback(
    (fileId: string) => {
      const file = files.find((f) => f.id === fileId);
      if (!file) return;

      // Check if file is secure (directly or inherited from parent)
      const isSecure = isSecureItem(file, files);

      if (isSecure) {
        // Get secure folder ID (for files inside secure folders)
        const secureFolderId = getSecureFolderId(file, files);
        const idToCheck = secureFolderId || file.id;

        // Check if unlocked
        if (!isUnlocked(idToCheck)) {
          // Show unlock dialog
          const folderName = secureFolderId
            ? files.find((f) => f.id === secureFolderId)?.name || 'Secure Folder'
            : file.name;

          setUnlockDialogState({
            open: true,
            itemId: idToCheck,
            itemName: folderName,
            itemType: secureFolderId ? 'folder' : 'file',
            fileIdToOpen: fileId,
          });
          return;
        }
      }

      // File is not secure or is unlocked, proceed with opening
      storeOpenFile(fileId);
    },
    [files, isUnlocked, storeOpenFile]
  );

  const handleUnlocked = useCallback(() => {
    // After unlocking, open the file that was requested
    if (unlockDialogState.fileIdToOpen) {
      storeOpenFile(unlockDialogState.fileIdToOpen);
    }
    setUnlockDialogState({
      open: false,
      itemId: null,
      itemName: '',
      itemType: 'file',
      fileIdToOpen: null,
    });
  }, [unlockDialogState.fileIdToOpen, storeOpenFile]);

  const UnlockDialog: ReactNode = unlockDialogState.open ? (
    <SecureUnlockDialog
      open={unlockDialogState.open}
      onOpenChange={(open) => {
        if (!open) {
          setUnlockDialogState({
            open: false,
            itemId: null,
            itemName: '',
            itemType: 'file',
            fileIdToOpen: null,
          });
        }
      }}
      itemId={unlockDialogState.itemId || ''}
      itemName={unlockDialogState.itemName}
      itemType={unlockDialogState.itemType}
      onUnlocked={handleUnlocked}
    />
  ) : null;

  return {
    openFile: secureOpenFile,
    UnlockDialog,
  };
}
