"use client";

import Swal from "sweetalert2";

// Types for the confirm dialog
export interface ConfirmDialogOptions {
  title?: string;
  text?: string;
  html?: string;
  icon?: "warning" | "error" | "success" | "info" | "question";
  confirmButtonText?: string;
  cancelButtonText?: string;
  confirmButtonColor?: string;
  cancelButtonColor?: string;
  showLoading?: boolean;
}

export interface DeleteConfirmOptions {
  itemName: string;
  itemType?: string; // e.g., "payment term", "invoice", "user"
}

// Generic confirm dialog
export const confirmDialog = async (
  options: ConfirmDialogOptions
): Promise<boolean> => {
  const result = await Swal.fire({
    title: options.title || "Are you sure?",
    text: options.text,
    html: options.html,
    icon: options.icon || "warning",
    showCancelButton: true,
    confirmButtonColor: options.confirmButtonColor || "#3085d6",
    cancelButtonColor: options.cancelButtonColor || "#6b7280",
    confirmButtonText: options.confirmButtonText || "Yes",
    cancelButtonText: options.cancelButtonText || "Cancel",
    reverseButtons: true,
    allowOutsideClick: !options.showLoading,
    allowEscapeKey: !options.showLoading,
  });

  return result.isConfirmed;
};

// Delete confirmation dialog
export const confirmDelete = async (
  options: DeleteConfirmOptions
): Promise<boolean> => {
  const result = await Swal.fire({
    title: "Are you sure?",
    html: `Delete <strong>${options.itemName}</strong>?<br><small style="color: #ef4444; margin-top: 8px; display: block;">This action cannot be undone.</small>`,
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#ef4444",
    cancelButtonColor: "#6b7280",
    confirmButtonText: "Yes, delete it!",
    cancelButtonText: "Cancel",
    reverseButtons: true,
  });

  return result.isConfirmed;
};

// Success toast
export const showSuccess = (
  title: string = "Success!",
  text?: string
): void => {
  Swal.fire({
    title,
    text,
    icon: "success",
    timer: 2000,
    timerProgressBar: true,
    showConfirmButton: false,
  });
};

// Error toast
export const showError = (
  title: string = "Error!",
  text?: string
): void => {
  Swal.fire({
    title,
    text,
    icon: "error",
  });
};

// Loading dialog
export const showLoading = (title: string = "Please wait..."): void => {
  Swal.fire({
    title,
    allowOutsideClick: false,
    allowEscapeKey: false,
    showConfirmButton: false,
    didOpen: () => {
      Swal.showLoading();
    },
  });
};

// Close loading
export const closeLoading = (): void => {
  Swal.close();
};

// Confirm with async action (handles loading state)
export const confirmWithAction = async <T,>(
  options: ConfirmDialogOptions & {
    onConfirm: () => Promise<T>;
    successMessage?: string;
    errorMessage?: string;
  }
): Promise<{ confirmed: boolean; result?: T; error?: any }> => {
  const confirmed = await confirmDialog(options);

  if (!confirmed) {
    return { confirmed: false };
  }

  try {
    showLoading("Processing...");
    const result = await options.onConfirm();
    closeLoading();
    
    if (options.successMessage) {
      showSuccess("Success!", options.successMessage);
    }
    
    return { confirmed: true, result };
  } catch (error: any) {
    closeLoading();
    showError("Error!", options.errorMessage || error.message || "Something went wrong");
    return { confirmed: true, error };
  }
};

// Delete with async action (most common use case)
export const deleteWithConfirm = async <T,>(
  itemName: string,
  onDelete: () => Promise<T>,
  options?: {
    itemType?: string;
    successMessage?: string;
    errorMessage?: string;
  }
): Promise<{ confirmed: boolean; result?: T; error?: any }> => {
  const confirmed = await confirmDelete({ itemName, itemType: options?.itemType });

  if (!confirmed) {
    return { confirmed: false };
  }

  try {
    showLoading("Deleting...");
    const result = await onDelete();
    closeLoading();
    showSuccess("Deleted!", options?.successMessage || `${itemName} has been deleted.`);
    return { confirmed: true, result };
  } catch (error: any) {
    closeLoading();
    showError("Error!", options?.errorMessage || error.message || "Failed to delete");
    return { confirmed: true, error };
  }
};