// hooks/useDeleteRequest.ts
import { useState, useCallback, useMemo } from 'react';
import {
  updateDeleteStatus,
  type DeleteStatus,
} from '../services/deleteRequestService';

export type UserRoleContext = {
  userRoles: string[];
  isSystemManager: boolean;
};

export type DeleteRequestAction =
  | 'raise_request'      // End user cannot; roles below Supervisor raise to Supervisor
  | 'approve_supervisor' // Contractor Supervisor → set to "Delete Request With CM"
  | 'approve_cm'         // Cluster Manager → set to "Deleted"
  | 'direct_delete'      // CM or System Manager can skip straight to "Deleted"
  | null;

export interface DeleteRequestState {
  /** What button(s) to show */
  showRaiseRequest: boolean;
  showApproveAsSupervisor: boolean;   // "Approve Request" (Supervisor view)
  showApproveAsCM: boolean;           // "Approve & Delete" (CM view)
  showDirectDelete: boolean;          // CM / System Manager direct delete
  /** Current status */
  deleteStatus: DeleteStatus;
  /** Loading / error */
  loading: boolean;
  error: string | null;
}

/**
 * Role resolution order (highest first):
 *   System Manager > Cluster Manager > Contractor Supervisor > everyone else (non-End-user)
 *
 * "End user" role: cannot raise a request at all.
 */
function resolveHighestRole(userRoles: string[], isSystemManager: boolean): string {

console.log('[DeleteRequest] userRoles:', userRoles, '| isSystemManager:', isSystemManager);

  if (isSystemManager || userRoles.includes('System Manager')) return 'System Manager';
  if (userRoles.includes('Cluster Manager')) return 'Cluster Manager';
  // if (userRoles.includes('Contractor Supervisor')) return 'Contractor Supervisor';
  if (userRoles.includes('Contractor Supervisor') || userRoles.includes('DR Approver'))
    return 'Contractor Supervisor';
  if (userRoles.includes('End user')) return 'End user';
  // Any other authenticated role (Work Control, Technician, etc.) can raise to Supervisor
  return 'Other';
}

/**
 * Derive which buttons should be visible given the current delete status and user role.
 *
 * Rules (from your spec):
 * ─────────────────────────────────────────────────────────────────────────────
 * No status set yet (null / ''):
 *   • End user          → nothing (no delete rights at all)
 *   • Other / Work Ctrl → show "Request Deletion" → sets to "Delete Request With Supervisor"
 *   • Contractor Sup    → show "Request Deletion" → sets to "Delete Request With CM"
 *   • Cluster Manager   → show "Delete" (direct) → sets to "Deleted"
 *   • System Manager    → show "Delete" (direct) → sets to "Deleted"
 *
 * status = "Delete Request With Supervisor":
 *   • Contractor Sup    → show "Approve Request" → sets to "Delete Request With CM"
 *   • CM / Sys Mgr      → show "Approve & Delete" → sets to "Deleted"
 *   • Others            → nothing new (request already raised)
 *
 * status = "Delete Request With CM":
 *   • CM / Sys Mgr      → show "Approve & Delete" → sets to "Deleted"
 *   • Others            → nothing
 *
 * status = "Deleted":
 *   → nothing (entry already marked deleted)
 * ─────────────────────────────────────────────────────────────────────────────
 */
function computeVisibility(
  role: string,
  deleteStatus: string | null | undefined,
): Pick<
  DeleteRequestState,
  'showRaiseRequest' | 'showApproveAsSupervisor' | 'showApproveAsCM' | 'showDirectDelete'
> {
  const none = {
    showRaiseRequest: false,
    showApproveAsSupervisor: false,
    showApproveAsCM: false,
    showDirectDelete: false,
  };

  // Already deleted — nothing to show
  if (deleteStatus === 'Deleted') return none;

  if (!deleteStatus || deleteStatus === '') {
    // Fresh document — no delete request raised yet
    if (role === 'End user') return none;
    if (role === 'System Manager' || role === 'Cluster Manager') {
      return { ...none, showDirectDelete: true };
    }
    // Contractor Supervisor: raise directly to CM level
    if (role === 'Contractor Supervisor') {
      return { ...none, showRaiseRequest: true };
    }
    // Work Control / Other authenticated roles
    return { ...none, showRaiseRequest: true };
  }

  if (deleteStatus === 'Delete Request With Supervisor') {
    if (role === 'Contractor Supervisor') {
      return { ...none, showApproveAsSupervisor: true };
    }
    if (role === 'System Manager' || role === 'Cluster Manager') {
      return { ...none, showApproveAsCM: true };
    }
    return none; // request already in-flight for others
  }

  if (deleteStatus === 'Delete Request With CM') {
    if (role === 'System Manager' || role === 'Cluster Manager') {
      return { ...none, showApproveAsCM: true };
    }
    return none;
  }

  return none;
}

/**
 * Determine the next status to set when a button is clicked.
 * Reject always resets to '' (empty) regardless of role — clears the request entirely.
 */
function nextStatus(
  action: 'raise' | 'supervisor_approve' | 'cm_approve' | 'direct' | 'reject',
  role: string
): DeleteStatus {
  if (action === 'reject') return '' as DeleteStatus;
  if (action === 'direct' || action === 'cm_approve') return 'Deleted';
  if (action === 'supervisor_approve') return 'Delete Request With CM';
  // raise_request
  if (role === 'Contractor Supervisor') return 'Delete Request With CM';
  return 'Delete Request With Supervisor';
}

// ─────────────────────────────────────────────────────────────────────────────

interface UseDeleteRequestOptions {
  doctype: string;
  docname: string | null | undefined;
  currentDeleteStatus: DeleteStatus;
  userRoles: string[];
  isSystemManager: boolean;
  onSuccess?: (newStatus: DeleteStatus) => void;
}

export function useDeleteRequest({
  doctype,
  docname,
  currentDeleteStatus,
  userRoles,
  isSystemManager,
  onSuccess,
}: UseDeleteRequestOptions) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [localStatus, setLocalStatus] = useState<DeleteStatus>(currentDeleteStatus);

  // Keep local status in sync when prop changes (e.g. after refetch)
  const effectiveStatus: DeleteStatus =
    localStatus !== currentDeleteStatus ? localStatus : currentDeleteStatus;

  const highestRole = useMemo(
    () => resolveHighestRole(userRoles, isSystemManager),
    [userRoles, isSystemManager]
  );

  const visibility = useMemo(
    () => computeVisibility(highestRole, effectiveStatus),
    [highestRole, effectiveStatus]
  );

  const execute = useCallback(
    async (action: 'raise' | 'supervisor_approve' | 'cm_approve' | 'direct' | 'reject') => {
      if (!docname) return;
      setLoading(true);
      setError(null);

      const targetStatus = nextStatus(action, highestRole);
      const result = await updateDeleteStatus(doctype, docname, targetStatus);

      setLoading(false);

      if (result.success) {
        setLocalStatus(targetStatus);
        onSuccess?.(targetStatus);
      } else {
        setError(result.error || 'Failed to update delete status');
      }
    },
    [doctype, docname, highestRole, onSuccess]
  );

  return {
    ...visibility,
    deleteStatus: effectiveStatus,
    loading,
    error,
    highestRole,
    /** Actions */
    raiseRequest: () => execute('raise'),
    approveAsSupervisor: () => execute('supervisor_approve'),
    approveAsCM: () => execute('cm_approve'),
    directDelete: () => execute('direct'),
    rejectRequest: () => execute('reject'), // ← resets status to '' (empty)
  };
}

export type { DeleteStatus };