import { getAuthHeaders } from "./api-client";
import {
  CreateScheduleEventDTO,
  ScheduleEvent,
  ScheduleFilterParams,
  ScheduleStats,
  UpdateScheduleEventDTO,
} from "@/types/schedule";

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

const today = new Date().toISOString().split("T")[0];
const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().split("T")[0];
const in3Days = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString().split("T")[0];

const INITIAL_MOCK_EVENTS: ScheduleEvent[] = [];

let localScheduleStore: ScheduleEvent[] = [...INITIAL_MOCK_EVENTS];

export async function getScheduleEvents(params?: ScheduleFilterParams): Promise<{
  items: ScheduleEvent[];
  total: number;
}> {
  try {
    const queryParams = new URLSearchParams();
    if (params?.search) queryParams.set("search", params.search);
    if (params?.type && params.type !== "ALL") queryParams.set("type", params.type);
    if (params?.status && params.status !== "ALL") queryParams.set("status", params.status);

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

    if (res.ok) {
      const data = await res.json();
      if (data && Array.isArray(data.items)) {
        localScheduleStore = data.items;
        return data;
      }
      if (Array.isArray(data)) {
        localScheduleStore = data;
        return { items: data, total: data.length };
      }
    }
  } catch {
    // fallback
  }

  let filtered = [...localScheduleStore];

  if (params?.search) {
    const term = params.search.toLowerCase();
    filtered = filtered.filter(
      (e) =>
        e.title.toLowerCase().includes(term) ||
        (e.customer && e.customer.name.toLowerCase().includes(term)) ||
        (e.equipment && e.equipment.code.toLowerCase().includes(term)) ||
        (e.equipment && e.equipment.model.toLowerCase().includes(term))
    );
  }

  if (params?.type && params.type !== "ALL") {
    filtered = filtered.filter((e) => e.type === params.type);
  }

  if (params?.status && params.status !== "ALL") {
    filtered = filtered.filter((e) => e.status === params.status);
  }

  return { items: filtered, total: filtered.length };
}

export async function getScheduleStats(): Promise<ScheduleStats> {
  try {
    const res = await fetch(`${API_BASE}/schedule/stats`, {
      headers: getAuthHeaders(),
      cache: "no-store",
    });

    if (res.ok) {
      const stats = await res.json();
      if (stats && (stats.totalEvents > 0 || stats.scheduledDeliveries > 0)) {
        return stats;
      }
    }
  } catch {
    // fallback
  }

  const todayStr = new Date().toISOString().split("T")[0];
  const totalEvents = localScheduleStore.length;
  const todayEvents = localScheduleStore.filter((e) => e.startDate.startsWith(todayStr)).length;
  const scheduledDeliveries = localScheduleStore.filter(
    (e) => e.type === "DELIVERY" && e.status === "SCHEDULED"
  ).length;
  const scheduledReturns = localScheduleStore.filter(
    (e) => e.type === "RETURN" && e.status === "SCHEDULED"
  ).length;
  const pendingMaintenance = localScheduleStore.filter(
    (e) => e.type === "MAINTENANCE" && e.status === "SCHEDULED"
  ).length;

  return {
    totalEvents,
    todayEvents,
    scheduledDeliveries,
    scheduledReturns,
    pendingMaintenance,
  };
}

export async function getScheduleEventById(id: string): Promise<ScheduleEvent | null> {
  try {
    const res = await fetch(`${API_BASE}/schedule/${id}`, {
      headers: getAuthHeaders(),
      cache: "no-store",
    });

    if (res.ok) {
      return await res.json();
    }
  } catch {
    // fallback
  }

  return localScheduleStore.find((e) => e.id === id) || null;
}

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

    if (res.ok) {
      return await res.json();
    }
  } catch {
    // fallback
  }

  const newEvt: ScheduleEvent = {
    id: `evt-${Date.now()}`,
    companyId: "comp-default",
    title: data.title,
    type: data.type,
    customerId: data.customerId || null,
    equipmentId: data.equipmentId || null,
    startDate: data.startDate,
    endDate: data.endDate,
    location: data.location || "Canteiro de Obras",
    technician: data.technician || "Equipe Técnica",
    notes: data.notes || null,
    status: data.status || "SCHEDULED",
    createdAt: new Date().toISOString(),
    customer: { id: data.customerId || "cust-1", name: "Cliente Cadastrado" },
    equipment: { id: data.equipmentId || "eq-1", code: "EQ-100", assetTag: "PAT-900", brand: "Equipamento", model: "Locado" },
  };

  localScheduleStore = [newEvt, ...localScheduleStore];
  return newEvt;
}

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

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

  const idx = localScheduleStore.findIndex((e) => e.id === id);
  if (idx !== -1) {
    const updated: ScheduleEvent = {
      ...localScheduleStore[idx],
      ...data,
    };
    localScheduleStore[idx] = updated;
    return updated;
  }

  return {
    id,
    companyId: "comp-default",
    title: "Agendamento",
    type: "DELIVERY",
    startDate: new Date().toISOString().split("T")[0],
    endDate: new Date().toISOString().split("T")[0],
    location: "Canteiro de Obras",
    technician: "Equipe Técnica",
    notes: null,
    status: data.status || "COMPLETED",
    createdAt: new Date().toISOString(),
    ...data,
  } as ScheduleEvent;
}

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

    if (res.ok) return true;
  } catch {
    // fallback
  }

  localScheduleStore = localScheduleStore.filter((e) => e.id !== id);
  return true;
}
