import { fetchApi, API_BASE_URL } from "./http";

export interface MineItem { id: number; item_text: string; category: string | null; sort_order: number; is_active: boolean }
export interface MineFile { id: number; original_name: string; size_bytes: number; mime: string | null; created_at: string }
export interface MineChecklist {
  id: number;
  name: string;
  created_by: number | null;
  can_edit: boolean;
  standard_id: number | null;
  standard_ids: number[];
  is_shareable: boolean;
  items: MineItem[];
  files: MineFile[];
  shared_user_ids: number[];
}
export interface MineResponse { is_admin: boolean; checklists: MineChecklist[] }
export interface UploadResult { file: MineFile; format: string; supported: boolean; items_added: number; items_skipped: number }

const token = () =>
  typeof window === "undefined" ? null : localStorage.getItem("access_token") || sessionStorage.getItem("access_token");
const authHeaders = (): Record<string, string> => {
  const t = token();
  return t ? { Authorization: `Bearer ${t}` } : {};
};
const json = (method: string, body?: unknown): RequestInit => ({
  method,
  body: body === undefined ? undefined : JSON.stringify(body),
});

export const listMine = () => fetchApi<MineResponse>(`${API_BASE_URL}/checklist-templates/mine`);

export interface CreateTemplatePayload {
  name: string;
  is_generic: boolean;
  standard_ids: number[];
  items?: { item_text: string; sort_order: number }[];
  allow_empty_items?: boolean;
}

export const createTemplate = (p: CreateTemplatePayload) =>
  fetchApi<{ id: number }>(
    `${API_BASE_URL}/checklist-templates`,
    json("POST", {
      name: p.name,
      is_generic: p.is_generic ?? false,
      standard_id: p.standard_ids[0] ?? null,
      standard_ids: p.standard_ids,
      items: p.items ?? [],
      allow_empty_items: !!p.allow_empty_items,
    }),
  );

export const renameTemplate = (id: number, name: string) =>
  fetchApi(`${API_BASE_URL}/checklist-templates/${id}/name`, json("PATCH", { name }));

export const removeTemplate = (id: number) =>
  fetchApi(`${API_BASE_URL}/checklist-templates/${id}/remove`, json("DELETE"));
export const setShareable = (id: number, is_shareable: boolean) =>
  fetchApi(`${API_BASE_URL}/checklist-templates/${id}/shareable`, json("PATCH", { is_shareable }));

export const setStandards = (id: number, standard_ids: number[]) =>
  fetchApi(`${API_BASE_URL}/checklist-templates/${id}/standards`, json("PATCH", { standard_ids }));
export const addItem = (id: number, item_text: string) =>
  fetchApi<MineItem>(`${API_BASE_URL}/checklist-templates/${id}/items`, json("POST", { item_text }));

export const updateItem = (itemId: number, body: { item_text?: string; category?: string | null; is_active?: boolean; sort_order?: number }) =>
  fetchApi<MineItem>(`${API_BASE_URL}/checklist-template-items/${itemId}`, json("PATCH", body));

export const deleteItem = (itemId: number) =>
  fetchApi(`${API_BASE_URL}/checklist-template-items/${itemId}`, json("DELETE"));

export const setShares = (id: number, user_ids: number[]) =>
  fetchApi(`${API_BASE_URL}/checklist-templates/${id}/shares`, json("PUT", { user_ids }));

export const deleteTemplateFile = (fileId: number) =>
  fetchApi(`${API_BASE_URL}/checklist-template-files/${fileId}`, json("DELETE"));

export async function uploadTemplateFile(id: number, file: File): Promise<UploadResult> {
  const fd = new FormData();
  fd.append("file", file);
  const res = await fetch(`${API_BASE_URL}/checklist-templates/${id}/files`, {
    method: "POST",
    credentials: "include",
    headers: authHeaders(),
    body: fd,
  });
  const text = await res.text();
  let body: any = null;
  try { body = JSON.parse(text); } catch { /* not json */ }
  if (!res.ok) {
    throw new Error(Array.isArray(body?.message) ? body.message.join(", ") : body?.message || `Upload failed (${res.status})`);
  }
  return body as UploadResult;
}

export async function downloadTemplateFile(fileId: number, name: string): Promise<void> {
  const res = await fetch(`${API_BASE_URL}/checklist-template-files/${fileId}/download`, {
    credentials: "include",
    headers: authHeaders(),
  });
  if (!res.ok) throw new Error(`Download failed (${res.status})`);
  const url = URL.createObjectURL(await res.blob());
  const a = document.createElement("a");
  a.href = url;
  a.download = name;
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 5000);
}