import type { AdminState, PartnerReportDeliveryLog, PartnerReportSchedule } from "./mpc-types";
import { adminAnalytics } from "./lead-crm-analytics";

export function partnerReportPeriodLabel(days: number) {
  if (days === 7) return "Weekly";
  if (days === 30) return "Monthly";
  if (days === 365) return "Yearly";
  if (days === 0) return "All-time";
  return `${days}-day`;
}

export function cleanWhatsappNumber(value: string) {
  const trimmed = String(value || "").trim();
  if (!trimmed) return "";
  const digits = trimmed.replace(/[^0-9]/g, "");
  if (digits.startsWith("00")) return digits.slice(2);
  if (digits.startsWith("0") && digits.length === 10) return `27${digits.slice(1)}`;
  return digits;
}

function metricLine(label: string, value: string | number) {
  return `• ${label}: ${value}`;
}

function percentage(value: number | undefined) {
  return `${Number(value || 0).toLocaleString("en-ZA")}%`;
}

export function buildPartnerReportText(state: AdminState, days = 30, listingIds?: string[]) {
  const analytics = adminAnalytics(state, days);
  const label = partnerReportPeriodLabel(days);
  const s = analytics.summary;
  const selectedIds = new Set((listingIds || []).filter(Boolean));
  const reports = (analytics.listingReports || [])
    .filter((report) => selectedIds.size === 0 || selectedIds.has(report.id))
    .slice(0, 20);

  const lines = [
    `MPC ${label} Partner Production Report`,
    `Generated: ${new Date(analytics.generatedAt).toLocaleString("en-ZA")}`,
    "",
    "General production flow",
    metricLine("Page views", s.pageViews || 0),
    metricLine("Unique sessions", s.uniqueSessions || 0),
    metricLine("CTA clicks", s.ctaClicks || 0),
    metricLine("Form submits", s.formSubmits || 0),
    metricLine("Leads", s.leads || 0),
    metricLine("Page-to-lead rate", percentage(s.pageToLeadRate)),
    metricLine("Public stay listings", s.publicAccommodationListings || 0),
    "",
    "Per-listing public flow",
  ];

  if (!reports.length) {
    lines.push("• No listing activity is available for this period yet.");
  } else {
    for (const report of reports) {
      lines.push(
        `• ${report.name}: ${report.views} views, ${report.contactClicks} contact clicks, ${report.enquiries} enquiries, ${percentage(report.conversionRate)} conversion. ${report.publicFlowStatus}. Next: ${report.nextAction}`,
      );
    }
  }

  lines.push("", "MPC note: reports show recorded MPC public page flow and tracked actions. They do not promise bookings.");
  return { analytics, text: lines.join("\n") };
}

export function computeNextRunAt(schedule: PartnerReportSchedule, from = new Date()) {
  const next = new Date(from.getTime());
  if (schedule.frequency === "weekly") next.setDate(next.getDate() + 7);
  if (schedule.frequency === "monthly") next.setMonth(next.getMonth() + 1);
  if (schedule.frequency === "yearly") next.setFullYear(next.getFullYear() + 1);
  return next.toISOString();
}

export function duePartnerReportSchedules(state: AdminState, now = new Date()) {
  const nowTime = now.getTime();
  return (state.partnerReportSchedules || []).filter((schedule) => {
    if (!schedule.enabled || !schedule.recipientWhatsapp || !schedule.nextRunAt) return false;
    const dueTime = new Date(schedule.nextRunAt).getTime();
    return Number.isFinite(dueTime) && dueTime <= nowTime;
  });
}

type SendResult = {
  status: PartnerReportDeliveryLog["status"];
  message: string;
  providerMessageId?: string;
};

export async function sendWhatsAppText(recipientWhatsapp: string, text: string): Promise<SendResult> {
  const to = cleanWhatsappNumber(recipientWhatsapp);
  if (!to) return { status: "failed", message: "No WhatsApp recipient number supplied." };

  const token = process.env.WHATSAPP_ACCESS_TOKEN || process.env.MPC_WHATSAPP_ACCESS_TOKEN || "";
  const phoneNumberId = process.env.WHATSAPP_PHONE_NUMBER_ID || process.env.MPC_WHATSAPP_PHONE_NUMBER_ID || "";
  const apiVersion = process.env.WHATSAPP_GRAPH_API_VERSION || "v20.0";

  if (!token || !phoneNumberId) {
    return {
      status: "not-configured",
      message: "WhatsApp Cloud API is not configured. Report was generated but not sent. Set WHATSAPP_ACCESS_TOKEN and WHATSAPP_PHONE_NUMBER_ID in cPanel environment variables.",
    };
  }

  const response = await fetch(`https://graph.facebook.com/${apiVersion}/${phoneNumberId}/messages`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      messaging_product: "whatsapp",
      recipient_type: "individual",
      to,
      type: "text",
      text: { preview_url: false, body: text.slice(0, 3900) },
    }),
  });

  const data = await response.json().catch(() => ({})) as { messages?: { id?: string }[]; error?: { message?: string } };
  if (!response.ok) {
    return { status: "failed", message: data.error?.message || `WhatsApp API failed with HTTP ${response.status}.` };
  }
  return { status: "sent", message: "WhatsApp report sent.", providerMessageId: data.messages?.[0]?.id };
}

export function makeReportDeliveryLog(params: {
  recipientWhatsapp: string;
  periodDays: number;
  status: PartnerReportDeliveryLog["status"];
  message: string;
  scheduleId?: string;
  providerMessageId?: string;
}): PartnerReportDeliveryLog {
  return {
    id: `REPORT-${Date.now().toString(36).toUpperCase()}-${Math.random().toString(36).slice(2, 7).toUpperCase()}`,
    createdAt: new Date().toISOString(),
    channel: "whatsapp",
    recipientWhatsapp: params.recipientWhatsapp,
    periodDays: params.periodDays,
    status: params.status,
    message: params.message,
    scheduleId: params.scheduleId,
    providerMessageId: params.providerMessageId,
  };
}
