import { ref } from 'vue'
import { apiFetch } from '@/lib/tauri'
import type { HooksApprovalPermissionRequest, HooksApprovalPlanRequest } from '@/types/hooks-approval'

export function useHooksApproval() {
  const pendingPermissions = ref<HooksApprovalPermissionRequest[]>([])
  const pendingPlans = ref<HooksApprovalPlanRequest[]>([])

  // ── WS message handler (called from useTranscriptDebug) ──

  function handleApprovalMessage(msg: { type: string; [key: string]: unknown }) {
    if (msg.type === 'hooks-approval-permission') {
      pendingPermissions.value.push({
        requestId: msg.requestId as string,
        tool_name: msg.tool_name as string | undefined,
        tool_input: msg.tool_input,
        agent_name: msg.agent_name as string | undefined,
        session_id: msg.session_id as string | undefined,
        cwd: msg.cwd as string | undefined,
        timestamp: msg.timestamp as number
      })
    } else if (msg.type === 'hooks-approval-plan') {
      pendingPlans.value.push({
        requestId: msg.requestId as string,
        session_id: msg.session_id as string | undefined,
        permission_mode: msg.permission_mode as string | undefined,
        lastAssistantText: (msg.lastAssistantText as string) || '',
        timestamp: msg.timestamp as number
      })
    }
  }

  // ── Respond to permission ──

  async function respondPermission(requestId: string, decision: 'allow' | 'deny') {
    try {
      await apiFetch('/api/hooks-approval/respond', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ requestId, decision })
      })
    } catch (e) {
      console.error('[HooksApproval] Failed to respond permission:', e)
    }
    pendingPermissions.value = pendingPermissions.value.filter(p => p.requestId !== requestId)
  }

  // ── Respond to plan ──

  async function respondPlan(requestId: string, decision: 'approve' | 'reject' | 'edit', reason?: string) {
    try {
      await apiFetch('/api/hooks-approval/respond-plan', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ requestId, decision, reason })
      })
    } catch (e) {
      console.error('[HooksApproval] Failed to respond plan:', e)
    }
    pendingPlans.value = pendingPlans.value.filter(p => p.requestId !== requestId)
  }

  // ── Fetch pending on page load (state recovery) ──

  async function fetchPending() {
    try {
      const res = await apiFetch('/api/hooks-approval')
      if (!res.ok) return
      const data = await res.json()

      if (Array.isArray(data.permissions)) {
        for (const p of data.permissions) {
          if (!pendingPermissions.value.some(e => e.requestId === p.requestId)) {
            pendingPermissions.value.push({
              requestId: p.requestId,
              tool_name: p.tool_name,
              tool_input: p.tool_input,
              agent_name: p.agent_name,
              session_id: p.session_id,
              timestamp: p.createdAt
            })
          }
        }
      }

      if (Array.isArray(data.plans)) {
        for (const p of data.plans) {
          if (!pendingPlans.value.some(e => e.requestId === p.requestId)) {
            pendingPlans.value.push({
              requestId: p.requestId,
              session_id: p.session_id,
              permission_mode: p.permission_mode,
              lastAssistantText: p.lastAssistantText || '',
              timestamp: p.createdAt
            })
          }
        }
      }
    } catch (e) {
      console.error('[HooksApproval] Failed to fetch pending:', e)
    }
  }

  return {
    pendingPermissions,
    pendingPlans,
    handleApprovalMessage,
    respondPermission,
    respondPlan,
    fetchPending
  }
}
