import type { HelpAttachmentPayload } from "@/services/apiClient";
import { helpService } from "@/services/helpService";
import type { HelpBotReply, HelpChatSyncResult } from "@/types/helpChat";
import { API_BASE_URL } from "@/utils/constants";

export const CHAT_TICKET_STORAGE_KEY = "noga-help-ticket-id";
export const CHAT_CONTACT_STORAGE_KEY = "noga-help-chat-contact";
export const MAX_CHAT_ATTACHMENT_BYTES = 10 * 1024 * 1024;

export type ChatContact = {
  name: string;
  email: string;
  phone: string;
  company?: string;
  ticketCategory: string;
  preferredContact: string;
  isCustomer: boolean;
};

export function getChatContact(): ChatContact | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = sessionStorage.getItem(CHAT_CONTACT_STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as ChatContact;
    if (!parsed.name?.trim() || !parsed.email?.trim() || !parsed.phone?.trim()) return null;
    return parsed;
  } catch {
    return null;
  }
}

export function setChatContact(contact: ChatContact) {
  sessionStorage.setItem(CHAT_CONTACT_STORAGE_KEY, JSON.stringify(contact));
}

export function clearChatSession() {
  sessionStorage.removeItem(CHAT_TICKET_STORAGE_KEY);
  sessionStorage.removeItem(CHAT_CONTACT_STORAGE_KEY);
}

export function hasChatIdentity(): boolean {
  return Boolean(getChatTicketId() || getChatContact());
}
export const CHAT_ACCEPT_FILES =
  "image/jpeg,image/png,image/gif,image/webp,application/pdf,.jpg,.jpeg,.png,.gif,.webp,.pdf";

export function resolveStorageUrl(url: string): string {
  if (url.startsWith("http") || url.startsWith("blob:") || url.startsWith("data:")) {
    return url;
  }
  const origin = API_BASE_URL.replace(/\/api\/v1\/?$/, "");
  return `${origin}${url.startsWith("/") ? url : `/${url}`}`;
}

export function getChatTicketId(): number | null {
  if (typeof window === "undefined") return null;
  const raw = sessionStorage.getItem(CHAT_TICKET_STORAGE_KEY);
  if (!raw) return null;
  const id = Number(raw);
  return Number.isFinite(id) ? id : null;
}

export function setChatTicketId(id: number) {
  sessionStorage.setItem(CHAT_TICKET_STORAGE_KEY, String(id));
}

export function clearChatTicketId() {
  sessionStorage.removeItem(CHAT_TICKET_STORAGE_KEY);
}

/** Novo ticket no painel; mantém contato para não repetir o intake. */
export function startNewSupportChat() {
  clearChatTicketId();
}

function mapBotReply(data: unknown): HelpBotReply | null {
  if (!data || typeof data !== "object") return null;
  const row = data as Record<string, unknown>;
  const nested =
    row.botReply && typeof row.botReply === "object"
      ? (row.botReply as Record<string, unknown>)
      : row;
  const message = nested.message;
  if (typeof message !== "string" || !message.trim()) return null;
  const links = Array.isArray(nested.links)
    ? (nested.links as { title: string; slug: string }[])
    : undefined;
  return {
    message,
    links,
    botActive: typeof nested.botActive === "boolean" ? nested.botActive : true,
    articleSlug: typeof nested.articleSlug === "string" ? nested.articleSlug : undefined,
  };
}

export async function uploadChatFiles(files: File[]): Promise<HelpAttachmentPayload[]> {
  const uploaded: HelpAttachmentPayload[] = [];
  for (const file of files) {
    const res = await helpService.uploadAttachment(file);
    const d = res.data;
    uploaded.push({
      url: resolveStorageUrl(d.url),
      name: d.name,
      mime: d.mime,
      size: d.size,
    });
  }
  return uploaded;
}

export async function syncChatToAttendant(
  message: string,
  attachments: HelpAttachmentPayload[],
  contactOverride?: Partial<ChatContact>,
) {
  const stored = getChatContact();
  const contact: ChatContact | null = stored
    ? { ...stored, ...contactOverride }
    : contactOverride?.name && contactOverride?.email && contactOverride?.phone
      ? {
          name: contactOverride.name,
          email: contactOverride.email,
          phone: contactOverride.phone,
          company: contactOverride.company,
          ticketCategory: contactOverride.ticketCategory ?? "technical",
          preferredContact: contactOverride.preferredContact ?? "both",
          isCustomer: contactOverride.isCustomer ?? true,
        }
      : null;

  if (!contact) {
    throw new Error("Identifique-se antes de enviar mensagens no chat.");
  }

  const ticketId = getChatTicketId();
  const body = { message: message || undefined, attachments };

  if (ticketId) {
    const res = await helpService.appendTicketMessage(ticketId, body);
    return {
      ticketId,
      botReply: mapBotReply(res.data),
      botActive:
        typeof (res.data as { botActive?: boolean })?.botActive === "boolean"
          ? (res.data as { botActive: boolean }).botActive
          : undefined,
    };
  }

  const res = await helpService.createTicket({
    subject: `Chat — ${contact.name}`,
    message:
      body.message ??
      (attachments.length ? "📎 Anexo enviado pelo chat" : "Cliente iniciou conversa pelo chat"),
    attachments: body.attachments,
    name: contact.name,
    email: contact.email,
    phone: contact.phone,
    is_customer: contact.isCustomer,
    ticket_category: contact.ticketCategory,
    preferred_contact: contact.preferredContact,
    company: contact.company,
    source: "chat",
    priority: "normal",
  });
  const payload = res.data as { id: number; botReply?: HelpBotReply; botActive?: boolean };
  setChatTicketId(payload.id);
  return {
    ticketId: payload.id,
    botReply: payload.botReply ?? mapBotReply(payload),
    botActive: payload.botActive,
  };
}

export async function fetchChatMessages(ticketId: number) {
  const res = await helpService.ticketMessages(ticketId);
  return {
    messages: res.data ?? [],
    meta: (res as { meta?: { botActive?: boolean; assignedTo?: number | null } }).meta,
  };
}
