import { useRuntimeConfig } from "#app";
import type { FetchResponse } from "ofetch";
import { workpulseApiRaw } from "~/utils/workpulse-api-fetch";
import { normalizeWorkpulseApiBase } from "~/utils/workpulse-api-base";
import { readWorkpulseAccessToken } from "~/utils/workpulse-session-user";
import { useAuth } from "./useAuth";

type ApiEnvelope<T> = {
  ok: boolean;
  data?: T;
  error?: { code?: string; message?: string };
};

export type TeamRow = {
  id: number;
  name: string;
  slug: string;
  createdAt?: string;
};

export type TeamMemberRow = {
  id: number;
  email: string;
  name: string;
  role: string;
  isActive: boolean;
};

export type TeamSummary = {
  teamId: number;
  period: string;
  reportsDraft: number;
  reportsSubmitted: number;
  reportsTotal: number;
};

export type CalendarEventSummary = {
  taskCounts?: { todo?: number; doing?: number; done?: number };
  blockersPreview?: string;
  workStart?: string;
  workEnd?: string;
};

export type CalendarEvent = {
  id: number;
  userId: number;
  organizerName?: string;
  organizerEmail?: string;
  organizerAvatarUrl?: string;
  title: string;
  startsAt: string;
  endsAt: string;
  allDay: boolean;
  createdAt: string;
  teamId?: number;
  kind?: string;
  reportId?: number;
  /** Tanggal laporan (YYYY-MM-DD) untuk acara dari daily report. */
  reportDate?: string;
  reportStatus?: string;
  reportDivision?: string;
  summary?: CalendarEventSummary;
};

export function isReportCalendarEvent(ev: CalendarEvent): boolean {
  return ev.kind === "report_summary" || ev.reportId != null;
}

/** Hari kalender untuk acara all-day / laporan — pakai reportDate, bukan overlap zona waktu. */
export function calendarEventDayKey(ev: CalendarEvent): string {
  const rd = (ev.reportDate ?? "").trim().slice(0, 10);
  if (/^\d{4}-\d{2}-\d{2}$/.test(rd)) return rd;
  if (ev.allDay && ev.startsAt) {
    const head = ev.startsAt.slice(0, 10);
    if (/^\d{4}-\d{2}-\d{2}$/.test(head)) return head;
  }
  return "";
}

function apiBase(): string {
  return normalizeWorkpulseApiBase(String(useRuntimeConfig().public.workpulseApiBase || ""));
}

function bearerHeaders(): { Authorization: string } | undefined {
  const { accessToken } = useAuth();
  const t = accessToken.value || readWorkpulseAccessToken();
  if (!t) return undefined;
  return { Authorization: `Bearer ${t}` };
}

async function parseEnvelope<T>(raw: FetchResponse<unknown>): Promise<{
  ok: boolean;
  status: number;
  data?: T;
  message?: string;
}> {
  const status = raw.status;
  let body = raw._data as ApiEnvelope<T> | string | undefined;
  if (typeof body === "string") {
    try {
      body = JSON.parse(body) as ApiEnvelope<T>;
    } catch {
      body = undefined;
    }
  }
  if (!body) return { ok: false, status, message: `HTTP ${status}` };
  if (!body.ok) {
    return {
      ok: false,
      status,
      message: body.error?.message || body.error?.code || `HTTP ${status}`
    };
  }
  return { ok: true, status, data: body.data as T };
}

/** `from` / `to` format YYYY-MM-DD; `to` eksklusif (hari pertama setelah rentang). */
export function useWorkpulseCalendar() {
  const listTeams = async () => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap.", items: [] as TeamRow[] };
    const raw = await workpulseApiRaw(`${b}/api/v1/teams`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    const parsed = await parseEnvelope<TeamRow[]>(raw);
    if (!parsed.ok || !parsed.data) {
      return {
        ok: false as const,
        status: parsed.status,
        message: parsed.message || "Gagal memuat tim.",
        items: [] as TeamRow[]
      };
    }
    return { ok: true as const, status: parsed.status, items: Array.isArray(parsed.data) ? parsed.data : [] };
  };

  const getTeamSummary = async (teamId: number, params: { period?: "week" | "month" | "all" } = {}) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap." };
    const qs = new URLSearchParams();
    if (params.period) qs.set("period", params.period);
    const q = qs.toString();
    const raw = await workpulseApiRaw(`${b}/api/v1/teams/${teamId}/summary${q ? `?${q}` : ""}`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<TeamSummary>(raw);
  };

  const listEvents = async (from: string, to: string) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap.", items: [] as CalendarEvent[] };
    const qs = new URLSearchParams({ from, to });
    const raw = await workpulseApiRaw(`${b}/api/v1/calendar/events?${qs}`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    const parsed = await parseEnvelope<CalendarEvent[]>(raw);
    if (!parsed.ok || !parsed.data) {
      return {
        ok: false as const,
        status: parsed.status,
        message: parsed.message || "Gagal memuat acara.",
        items: [] as CalendarEvent[]
      };
    }
    return { ok: true as const, status: parsed.status, items: Array.isArray(parsed.data) ? parsed.data : [] };
  };

  const listTeamMembers = async (teamId: number) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap.", items: [] as TeamMemberRow[] };
    const raw = await workpulseApiRaw(`${b}/api/v1/teams/${teamId}/members`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    const parsed = await parseEnvelope<TeamMemberRow[]>(raw);
    if (!parsed.ok || !parsed.data) {
      return {
        ok: false as const,
        status: parsed.status,
        message: parsed.message || "Gagal memuat anggota tim.",
        items: [] as TeamMemberRow[]
      };
    }
    return { ok: true as const, status: parsed.status, items: Array.isArray(parsed.data) ? parsed.data : [] };
  };

  return { listTeams, listEvents, listTeamMembers, getTeamSummary };
}
