// ApprovalQueueComponent.tsx - Example React component for approval queue UI
import { useQuery, useMutation } from "convex/react";
import { api } from "../_generated/api";
import { Id } from "../_generated/dataModel";

/**
 * Approval Queue Dashboard Component
 * 
 * Shows pending approvals with ability to approve/decline
 */
export function ApprovalQueueDashboard({ organizationId }: { organizationId: string }) {
  // Fetch pending approvals
  const pendingApprovals = useQuery(api.humanInTheLoop.getPendingApprovals, {
    organizationId,
    status: "pending",
    limit: 50,
  });

  // Fetch queue statistics
  const stats = useQuery(api.humanInTheLoop.getApprovalQueueStats, {
    organizationId,
  });

  // Mutations
  const approveConfirmation = useMutation(api.humanInTheLoop.approveConfirmation);
  const declineConfirmation = useMutation(api.humanInTheLoop.declineConfirmation);

  const handleApprove = async (confirmationId: Id<"pendingConfirmations">) => {
    try {
      await approveConfirmation({
        confirmationId,
        approvedBy: "current-user@example.com", // Get from auth context
        autoResume: true,
      });
      alert("Approval successful!");
    } catch (error) {
      alert(`Error: ${error.message}`);
    }
  };

  const handleDecline = async (confirmationId: Id<"pendingConfirmations">) => {
    const reason = prompt("Reason for declining:");
    if (!reason) return;

    try {
      await declineConfirmation({
        confirmationId,
        declinedBy: "current-user@example.com",
        reason,
        cancelWorkflow: true,
      });
      alert("Request declined");
    } catch (error) {
      alert(`Error: ${error.message}`);
    }
  };

  if (!pendingApprovals || !stats) {
    return <div>Loading...</div>;
  }

  return (
    <div className="approval-queue">
      <h1>Approval Queue</h1>
      
      {/* Statistics */}
      <div className="stats-grid">
        <StatCard label="Total" value={stats.total} />
        <StatCard label="Pending" value={stats.pending} color="yellow" />
        <StatCard label="Confirmed" value={stats.confirmed} color="green" />
        <StatCard label="Declined" value={stats.declined} color="red" />
        <StatCard label="Expired" value={stats.expired} color="gray" />
        <StatCard label="Expiring Soon" value={stats.expiringSoon} color="orange" />
      </div>

      {/* Pending Approvals List */}
      <div className="approvals-list">
        <h2>Pending Approvals ({pendingApprovals.length})</h2>
        
        {pendingApprovals.length === 0 ? (
          <p>No pending approvals</p>
        ) : (
          <div className="approval-cards">
            {pendingApprovals.map((approval) => (
              <ApprovalCard
                key={approval._id}
                approval={approval}
                onApprove={() => handleApprove(approval._id)}
                onDecline={() => handleDecline(approval._id)}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

/**
 * Individual Approval Card Component
 */
function ApprovalCard({ 
  approval, 
  onApprove, 
  onDecline 
}: { 
  approval: any;
  onApprove: () => void;
  onDecline: () => void;
}) {
  const details = useQuery(api.humanInTheLoop.getApprovalDetails, {
    confirmationId: approval._id,
  });

  if (!details) return null;

  const timeRemaining = Math.floor(details.timeRemaining / 1000 / 60); // minutes
  const isExpiringSoon = timeRemaining < 5;

  return (
    <div className={`approval-card ${isExpiringSoon ? 'expiring-soon' : ''}`}>
      <div className="approval-header">
        <span className="action-type">{approval.actionType}</span>
        <span className={`time-remaining ${isExpiringSoon ? 'urgent' : ''}`}>
          {timeRemaining}m remaining
        </span>
      </div>

      <div className="approval-body">
        <p className="action-details">{approval.actionDetails}</p>
        
        {details.conversation && (
          <div className="context">
            <small>
              Conversation: {details.conversation.threadId}
              <br />
              Channel: {details.conversation.channel}
            </small>
          </div>
        )}

        {details.workflowExecution && (
          <div className="workflow-context">
            <small>
              Workflow Step: {details.workflowExecution.currentStep}
              <br />
              Status: {details.workflowExecution.status}
            </small>
          </div>
        )}
      </div>

      <div className="approval-actions">
        <button 
          onClick={onApprove}
          className="btn-approve"
          disabled={details.isExpired}
        >
          ✓ Approve
        </button>
        <button 
          onClick={onDecline}
          className="btn-decline"
          disabled={details.isExpired}
        >
          ✗ Decline
        </button>
      </div>

      {details.isExpired && (
        <div className="expired-badge">EXPIRED</div>
      )}
    </div>
  );
}

/**
 * Statistics Card Component
 */
function StatCard({ 
  label, 
  value, 
  color = "blue" 
}: { 
  label: string; 
  value: number; 
  color?: string;
}) {
  return (
    <div className={`stat-card stat-${color}`}>
      <div className="stat-value">{value}</div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

/**
 * Workflow Monitor Component
 * 
 * Shows active workflows with pause/resume controls
 */
export function WorkflowMonitor({ organizationId }: { organizationId: string }) {
  const activeWorkflows = useQuery(api.workflowManager.getActiveWorkflowExecutions, {
    organizationId,
    limit: 20,
  });

  const pausedWorkflows = useQuery(api.humanInTheLoop.getPausedWorkflows, {
    organizationId,
    limit: 20,
  });

  const pauseWorkflow = useMutation(api.humanInTheLoop.pauseWorkflow);
  const resumeWorkflow = useMutation(api.humanInTheLoop.resumeWorkflow);
  const cancelWorkflow = useMutation(api.workflowManager.cancelWorkflowExecution);

  const handlePause = async (executionId: Id<"workflowExecutions">) => {
    const reason = prompt("Reason for pausing:");
    if (!reason) return;

    try {
      await pauseWorkflow({
        workflowExecutionId: executionId,
        reason,
        pausedBy: "current-user@example.com",
      });
    } catch (error) {
      alert(`Error: ${error.message}`);
    }
  };

  const handleResume = async (executionId: Id<"workflowExecutions">) => {
    try {
      await resumeWorkflow({
        workflowExecutionId: executionId,
        resumedBy: "current-user@example.com",
        skipCurrentStep: false,
      });
    } catch (error) {
      alert(`Error: ${error.message}`);
    }
  };

  const handleCancel = async (executionId: Id<"workflowExecutions">) => {
    if (!confirm("Are you sure you want to cancel this workflow?")) return;

    try {
      await cancelWorkflow({
        executionId,
        reason: "Cancelled by user",
        cancelledBy: "current-user@example.com",
      });
    } catch (error) {
      alert(`Error: ${error.message}`);
    }
  };

  if (!activeWorkflows || !pausedWorkflows) {
    return <div>Loading...</div>;
  }

  return (
    <div className="workflow-monitor">
      <h1>Workflow Monitor</h1>

      {/* Active Workflows */}
      <section>
        <h2>Active Workflows ({activeWorkflows.length})</h2>
        <div className="workflow-list">
          {activeWorkflows.map((item) => (
            <WorkflowCard
              key={item.execution._id}
              execution={item.execution}
              workflow={item.workflow}
              progress={item.progress}
              onPause={() => handlePause(item.execution._id)}
              onCancel={() => handleCancel(item.execution._id)}
            />
          ))}
        </div>
      </section>

      {/* Paused Workflows */}
      <section>
        <h2>Paused Workflows ({pausedWorkflows.length})</h2>
        <div className="workflow-list">
          {pausedWorkflows.map((item) => (
            <WorkflowCard
              key={item.execution._id}
              execution={item.execution}
              workflow={item.workflow}
              progress={{
                currentStep: item.execution.currentStep,
                totalSteps: item.workflow?.steps.length || 0,
                percentComplete: 0,
              }}
              onResume={() => handleResume(item.execution._id)}
              onCancel={() => handleCancel(item.execution._id)}
            />
          ))}
        </div>
      </section>
    </div>
  );
}

/**
 * Workflow Card Component
 */
function WorkflowCard({
  execution,
  workflow,
  progress,
  onPause,
  onResume,
  onCancel,
}: {
  execution: any;
  workflow: any;
  progress: any;
  onPause?: () => void;
  onResume?: () => void;
  onCancel: () => void;
}) {
  return (
    <div className="workflow-card">
      <div className="workflow-header">
        <h3>{workflow?.name || "Unknown Workflow"}</h3>
        <span className={`status-badge status-${execution.status}`}>
          {execution.status}
        </span>
      </div>

      <div className="workflow-progress">
        <div className="progress-bar">
          <div 
            className="progress-fill" 
            style={{ width: `${progress.percentComplete}%` }}
          />
        </div>
        <span className="progress-text">
          Step {progress.currentStep} of {progress.totalSteps} ({progress.percentComplete}%)
        </span>
      </div>

      <div className="workflow-actions">
        {onPause && (
          <button onClick={onPause} className="btn-secondary">
            ⏸ Pause
          </button>
        )}
        {onResume && (
          <button onClick={onResume} className="btn-primary">
            ▶ Resume
          </button>
        )}
        <button onClick={onCancel} className="btn-danger">
          ✕ Cancel
        </button>
      </div>
    </div>
  );
}

/**
 * Example CSS (add to your stylesheet)
 */
export const exampleStyles = `
.approval-queue {
  padding: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
  margin-bottom: 32px;
}

.stat-card {
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.stat-card.stat-yellow { background: #fef3c7; }
.stat-card.stat-green { background: #d1fae5; }
.stat-card.stat-red { background: #fee2e2; }
.stat-card.stat-gray { background: #f3f4f6; }
.stat-card.stat-orange { background: #fed7aa; }

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.approval-cards {
  display: grid;
  gap: 16px;
}

.approval-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  position: relative;
}

.approval-card.expiring-soon {
  border-color: #f59e0b;
  background: #fffbeb;
}

.approval-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.action-type {
  background: #3b82f6;
  color: white;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  text-transform: uppercase;
}

.time-remaining.urgent {
  color: #dc2626;
  font-weight: bold;
}

.approval-actions {
  display: flex;
  gap: 8px;
  margin-top: 16px;
}

.btn-approve {
  flex: 1;
  padding: 8px;
  background: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-decline {
  flex: 1;
  padding: 8px;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.workflow-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.progress-bar {
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
  margin: 8px 0;
}

.progress-fill {
  height: 100%;
  background: #3b82f6;
  transition: width 0.3s;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  text-transform: uppercase;
}

.status-in_progress { background: #dbeafe; color: #1e40af; }
.status-waiting_confirmation { background: #fef3c7; color: #92400e; }
.status-completed { background: #d1fae5; color: #065f46; }
.status-failed { background: #fee2e2; color: #991b1b; }
.status-cancelled { background: #f3f4f6; color: #374151; }
`;
