import { ref } from 'vue';
import { buildInfoConfig, buildConfirmConfig, safeErrorMessage } from '../utils/dialogUtils.js';

/**
 * Composable für einfache Dialog-Verwaltung
 * 
 * Verwendung:
 * 
 * // In der Component:
 * const { isOpen, open, close } = useDialog();
 * 
 * // Dialog öffnen:
 * open();
 * 
 * // Dialog schließen:
 * close();
 * 
 * // Im Template:
 * <BaseDialog v-model="isOpen" ...>
 */
export function useDialog(initialState = false) {
  const isOpen = ref(initialState);

  const open = () => {
    isOpen.value = true;
  };

  const close = () => {
    isOpen.value = false;
  };

  const toggle = () => {
    isOpen.value = !isOpen.value;
  };

  return {
    isOpen,
    open,
    close,
    toggle
  };
}

/**
 * Composable für Confirm-Dialog
 * 
 * Verwendung:
 * 
 * const { confirm } = useConfirm();
 * 
 * const deleted = await confirm({
 *   title: 'Löschen bestätigen',
 *   message: 'Möchten Sie diesen Eintrag wirklich löschen?',
 *   type: 'danger'
 * });
 * 
 * if (deleted) {
 *   // Löschvorgang durchführen
 * }
 */
export function useConfirm() {
  const isOpen = ref(false);
  const config = ref({});
  let resolvePromise = null;

  const confirm = (options = {}) => {
    config.value = buildConfirmConfig(options);

    isOpen.value = true;

    return new Promise((resolve) => {
      resolvePromise = resolve;
    });
  };

  const handleConfirm = () => {
    isOpen.value = false;
    if (resolvePromise) {
      resolvePromise(true);
      resolvePromise = null;
    }
  };

  const handleCancel = () => {
    isOpen.value = false;
    if (resolvePromise) {
      resolvePromise(false);
      resolvePromise = null;
    }
  };

  return {
    isOpen,
    config,
    confirm,
    handleConfirm,
    handleCancel
  };
}

/**
 * Composable für Info-Dialog
 * 
 * Verwendung:
 * 
 * const { showInfo } = useInfo();
 * 
 * await showInfo({
 *   title: 'Erfolg',
 *   message: 'Der Vorgang wurde erfolgreich abgeschlossen.',
 *   type: 'success'
 * });
 */
export function useInfo() {
  const isOpen = ref(false);
  const config = ref({});
  let resolvePromise = null;

  const showInfo = (options = {}) => {
    config.value = buildInfoConfig(options);

    isOpen.value = true;

    return new Promise((resolve) => {
      resolvePromise = resolve;
    });
  };

  const handleOk = () => {
    isOpen.value = false;
    if (resolvePromise) {
      resolvePromise(true);
      resolvePromise = null;
    }
  };

  const handleClose = () => {
    isOpen.value = false;
    if (resolvePromise) {
      resolvePromise(false);
      resolvePromise = null;
    }
  };

  return {
    isOpen,
    config,
    showInfo,
    handleOk,
    handleClose
  };
}

export { safeErrorMessage };

