'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type {
  GembaAudit,
  GembaFinding,
  GembaComplianceScore,
  FindingSeverity,
  AuditStatus,
} from '@/types/integrations';

/** Query key factory */
export const gembadocsKeys = {
  all: ['gembadocs'] as const,
  audits: (filters?: { status?: AuditStatus }) =>
    [...gembadocsKeys.all, 'audits', filters] as const,
  upcomingAudits: (limit?: number) =>
    [...gembadocsKeys.all, 'audits', 'upcoming', limit] as const,
  audit: (id: string) => [...gembadocsKeys.all, 'audit', id] as const,
  findings: (filters?: { severity?: FindingSeverity; auditId?: string }) =>
    [...gembadocsKeys.all, 'findings', filters] as const,
  openFindings: ['gembadocs', 'findings', 'open'] as const,
  findingCounts: ['gembadocs', 'findings', 'counts'] as const,
  complianceScore: ['gembadocs', 'compliance'] as const,
};

interface FetchAuditsParams {
  status?: AuditStatus;
  limit?: number;
  upcoming?: boolean;
}

/**
 * Fetch GembaDocs audits
 */
async function fetchAudits(params?: FetchAuditsParams): Promise<GembaAudit[]> {
  if (params?.upcoming) {
    const response = await api.get<{ audits: GembaAudit[] } | GembaAudit[]>(
      '/integrations/gembadocs/audits/upcoming',
      { params: { limit: params.limit } },
    );
    return Array.isArray(response) ? response : response.audits;
  }

  const queryParams: Record<string, string | number | boolean | undefined> = {};
  if (params?.status) queryParams.status = params.status;
  if (params?.limit) queryParams.pageSize = params.limit;

  const response = await api.get<{ audits: GembaAudit[] } | GembaAudit[]>(
    '/integrations/gembadocs/audits',
    { params: queryParams },
  );
  return Array.isArray(response) ? response : response.audits;
}

interface FetchFindingsParams {
  severity?: FindingSeverity;
  auditId?: string;
  status?: 'open' | 'all';
  limit?: number;
}

/**
 * Fetch GembaDocs findings
 */
async function fetchFindings(params?: FetchFindingsParams): Promise<GembaFinding[]> {
  if (params?.status === 'open') {
    const response = await api.get<{ findings: GembaFinding[] } | GembaFinding[]>(
      '/integrations/gembadocs/findings/open',
      { params: { limit: params?.limit } },
    );
    return Array.isArray(response) ? response : response.findings;
  }

  const queryParams: Record<string, string | number | boolean | undefined> = {};
  if (params?.severity) queryParams.severity = params.severity;
  if (params?.auditId) queryParams.auditId = params.auditId;
  if (params?.limit) queryParams.pageSize = params.limit;

  const response = await api.get<{ findings: GembaFinding[] } | GembaFinding[]>(
    '/integrations/gembadocs/findings',
    { params: queryParams },
  );
  return Array.isArray(response) ? response : response.findings;
}

/**
 * Fetch compliance score
 */
async function fetchComplianceScore(): Promise<GembaComplianceScore> {
  return api.get<GembaComplianceScore>('/integrations/gembadocs/compliance-score');
}

/**
 * Hook to fetch upcoming audits
 */
export function useUpcomingAudits(limit: number = 3) {
  return useQuery({
    queryKey: gembadocsKeys.upcomingAudits(limit),
    queryFn: () => fetchAudits({ upcoming: true, limit }),
    staleTime: 60 * 1000,
  });
}

/**
 * Hook to fetch all audits with optional filters
 */
export function useAudits(params?: FetchAuditsParams) {
  return useQuery({
    queryKey: gembadocsKeys.audits(params),
    queryFn: () => fetchAudits(params),
    staleTime: 60 * 1000,
  });
}

/**
 * Hook to fetch open findings
 */
export function useOpenFindings(limit?: number) {
  return useQuery({
    queryKey: gembadocsKeys.openFindings,
    queryFn: () => fetchFindings({ status: 'open', limit }),
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to get finding counts by severity
 */
export function useFindingCounts() {
  return useQuery({
    queryKey: gembadocsKeys.findingCounts,
    queryFn: async () => {
      const findings = await fetchFindings({ status: 'open' });
      return {
        total: findings.length,
        critical: findings.filter((f) => f.severity === 'critical').length,
        high: findings.filter((f) => f.severity === 'high').length,
        medium: findings.filter((f) => f.severity === 'medium').length,
        low: findings.filter((f) => f.severity === 'low').length,
      };
    },
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to fetch compliance score
 */
export function useComplianceScore() {
  return useQuery({
    queryKey: gembadocsKeys.complianceScore,
    queryFn: fetchComplianceScore,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Calculate days until audit
 */
export function getDaysUntilAudit(scheduledDate: Date): number {
  const now = new Date();
  const diffTime = new Date(scheduledDate).getTime() - now.getTime();
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}
