import { getAuthHeaders } from "./api-client";
import {
  CreateSupplierDTO,
  Supplier,
  SupplierFilterParams,
  SupplierStats,
  UpdateSupplierDTO,
} from "@/types/supplier";

const API_BASE = (process.env.NEXT_PUBLIC_API_URL || "http://localhost:3333").replace(/\/$/, "") + "/api";

const INITIAL_MOCK_SUPPLIERS: Supplier[] = [];

let localSupplierStore: Supplier[] = [...INITIAL_MOCK_SUPPLIERS];

export async function getSuppliers(params?: SupplierFilterParams): Promise<{
  items: Supplier[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}> {
  try {
    const queryParams = new URLSearchParams();
    if (params?.search) queryParams.set("search", params.search);
    if (params?.page) queryParams.set("page", String(params.page));
    if (params?.limit) queryParams.set("limit", String(params.limit));

    const res = await fetch(`${API_BASE}/suppliers?${queryParams.toString()}`, {
      headers: getAuthHeaders(),
      cache: "no-store",
    });

    if (res.ok) {
      const data = await res.json();
      if (data && Array.isArray(data.items)) {
        localSupplierStore = data.items;
        return data;
      }
      if (Array.isArray(data)) {
        localSupplierStore = data;
        return { items: data, total: data.length, page: 1, limit: 50, totalPages: 1 };
      }
    }
  } catch {
    // fallback
  }

  let filtered = [...localSupplierStore];

  if (params?.search) {
    const term = params.search.toLowerCase();
    filtered = filtered.filter(
      (s) =>
        s.name.toLowerCase().includes(term) ||
        (s.document && s.document.toLowerCase().includes(term)) ||
        (s.email && s.email.toLowerCase().includes(term)) ||
        (s.contactName && s.contactName.toLowerCase().includes(term))
    );
  }

  const page = params?.page || 1;
  const limit = params?.limit || 20;
  const total = filtered.length;
  const totalPages = Math.ceil(total / limit) || 1;
  const startIndex = (page - 1) * limit;
  const items = filtered.slice(startIndex, startIndex + limit);

  return { items, total, page, limit, totalPages };
}

export async function getSupplierStats(): Promise<SupplierStats> {
  try {
    const res = await fetch(`${API_BASE}/suppliers/stats`, {
      headers: getAuthHeaders(),
      cache: "no-store",
    });
    if (res.ok) {
      const stats = await res.json();
      if (stats && typeof stats.total === "number") {
        return stats;
      }
    }
  } catch {
    // fallback
  }

  const total = localSupplierStore.length;
  const activeWithPayables = localSupplierStore.filter((s) => (s.openPayablesCount || 0) > 0).length;
  const totalPayableAmount = localSupplierStore.reduce((acc, s) => acc + (s.totalOpenAmount || 0), 0);

  return { total, activeWithPayables, totalPayableAmount };
}

export async function getSupplierById(id: string): Promise<Supplier | null> {
  try {
    const res = await fetch(`${API_BASE}/suppliers/${id}`, {
      headers: getAuthHeaders(),
      cache: "no-store",
    });
    if (res.ok) {
      return await res.json();
    }
  } catch {
    // fallback
  }

  return localSupplierStore.find((s) => s.id === id) || null;
}

export async function createSupplier(data: CreateSupplierDTO): Promise<Supplier> {
  try {
    const res = await fetch(`${API_BASE}/suppliers`, {
      method: "POST",
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });

    if (res.ok) {
      const created = await res.json();
      localSupplierStore = [created, ...localSupplierStore.filter((s) => s.id !== created.id)];
      return created;
    }
  } catch {
    // fallback
  }

  const newSupplier: Supplier = {
    id: `sup-${Date.now()}`,
    companyId: "comp-default",
    name: data.name,
    document: data.document || null,
    email: data.email || null,
    phone: data.phone || null,
    contactName: data.contactName || null,
    openPayablesCount: 0,
    totalOpenAmount: 0,
    payables: [],
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };

  localSupplierStore = [newSupplier, ...localSupplierStore];
  return newSupplier;
}

export async function updateSupplier(id: string, data: UpdateSupplierDTO): Promise<Supplier> {
  try {
    const res = await fetch(`${API_BASE}/suppliers/${id}`, {
      method: "PATCH",
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });

    if (res.ok) {
      const updated = await res.json();
      const index = localSupplierStore.findIndex((s) => s.id === updated.id);
      if (index !== -1) {
        localSupplierStore[index] = { ...localSupplierStore[index], ...updated };
      }
      return updated;
    }
  } catch {
    // fallback
  }

  const index = localSupplierStore.findIndex((s) => s.id === id);
  if (index === -1) {
    throw new Error("Fornecedor não encontrado.");
  }

  const updated: Supplier = {
    ...localSupplierStore[index],
    ...data,
    updatedAt: new Date().toISOString(),
  };

  localSupplierStore[index] = updated;
  return updated;
}

export async function deleteSupplier(id: string): Promise<boolean> {
  try {
    const res = await fetch(`${API_BASE}/suppliers/${id}`, {
      method: "DELETE",
      headers: getAuthHeaders(),
    });

    if (res.ok) {
      localSupplierStore = localSupplierStore.filter((s) => s.id !== id);
      return true;
    }
  } catch {
    // fallback
  }

  localSupplierStore = localSupplierStore.filter((s) => s.id !== id);
  return true;
}
