"use server";

import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { randomUUID } from "node:crypto";

function slugify(value: string): string {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "");
}

function normalizeImageUrl(value: string): string {
  const input = value.trim();
  if (!input) return "";
  if (input.startsWith("http://") || input.startsWith("https://") || input.startsWith("data:") || input.startsWith("blob:")) return input;
  if (input.startsWith("//")) return `https:${input}`;
  if (input.startsWith("/")) return input;
  return `/${input}`;
}

async function saveUpload(file: File): Promise<string> {
  if (!file || file.size === 0) throw new Error("No file uploaded");
  if (!file.type.startsWith("image/")) throw new Error("Only image uploads are allowed");

  const ext = path.extname(file.name || "").toLowerCase() || ".jpg";
  const safeExt = ext.replace(/[^.a-z0-9]/g, "") || ".jpg";
  const fileName = `${Date.now()}-${randomUUID()}${safeExt}`;
  const dir = path.join(process.cwd(), "public", "uploads", "visa-slides");

  await mkdir(dir, { recursive: true });
  const bytes = Buffer.from(await file.arrayBuffer());
  await writeFile(path.join(dir, fileName), bytes);

  return `/uploads/visa-slides/${fileName}`;
}

export async function saveVisaTypeAction(formData: FormData) {
  const id = String(formData.get("id") || "").trim();
  const name = String(formData.get("name") || "").trim();
  const slugRaw = String(formData.get("slug") || "").trim();
  const description = String(formData.get("description") || "").trim() || null;
  const iconKey = String(formData.get("iconKey") || "").trim() || "globe";
  const badge = String(formData.get("badge") || "").trim() || null;
  const colorClass = String(formData.get("colorClass") || "").trim() || "bg-neutral-50 text-neutral-600 border-neutral-200";
  const sortOrder = Number(formData.get("sortOrder") || 0) || 0;
  const isActive = String(formData.get("isActive") || "true") === "true";

  if (!name) return { ok: false, error: "Visa type name is required" };
  const slug = slugRaw || slugify(name);

  const data = { name, slug, description, iconKey, badge, colorClass, sortOrder, isActive };

  if (id) {
    await db.visaType.update({ where: { id }, data });
  } else {
    await db.visaType.create({ data });
  }

  revalidatePath("/admin/visa");
  revalidatePath("/visa");
  return { ok: true };
}

export async function deleteVisaTypeAction(id: string) {
  try {
    await db.visaType.delete({ where: { id } });
    revalidatePath("/admin/visa");
    revalidatePath("/visa");
    return { ok: true };
  } catch {
    return { ok: false, error: "Visa type is in use by enquiries." };
  }
}

export async function saveVisaSlideAction(formData: FormData) {
  const id = String(formData.get("id") || "").trim();
  const imageUrlRaw = String(formData.get("imageUrl") || "").trim();
  const imageFile = formData.get("imageFile") as File | null;
  const badge = String(formData.get("badge") || "").trim() || null;
  const badgeIcon = String(formData.get("badgeIcon") || "").trim() || "globe";
  const title = String(formData.get("title") || "").trim() || null;
  const highlight = String(formData.get("highlight") || "").trim() || null;
  const description = String(formData.get("description") || "").trim() || null;
  const subtitle = String(formData.get("subtitle") || "").trim() || null;
  const ctaText = String(formData.get("ctaText") || "").trim() || null;
  const ctaLink = String(formData.get("ctaLink") || "").trim() || null;
  const ctaSecondaryText = String(formData.get("ctaSecondaryText") || "").trim() || null;
  const ctaSecondaryLink = String(formData.get("ctaSecondaryLink") || "").trim() || null;
  const stat1Label = String(formData.get("stat1Label") || "").trim() || null;
  const stat1Value = String(formData.get("stat1Value") || "").trim() || null;
  const stat2Label = String(formData.get("stat2Label") || "").trim() || null;
  const stat2Value = String(formData.get("stat2Value") || "").trim() || null;
  const stat3Label = String(formData.get("stat3Label") || "").trim() || null;
  const stat3Value = String(formData.get("stat3Value") || "").trim() || null;
  const sortOrder = Number(formData.get("sortOrder") || 0) || 0;
  const isActive = String(formData.get("isActive") || "true") === "true";

  const uploaded = imageFile && imageFile.size > 0 ? await saveUpload(imageFile) : "";
  const imageUrl = normalizeImageUrl(uploaded || imageUrlRaw);
  if (!imageUrl) return { ok: false, error: "Provide image URL or upload an image." };

  const data = {
    imageUrl,
    badge,
    badgeIcon,
    title,
    highlight,
    description,
    subtitle,
    ctaText,
    ctaLink,
    ctaSecondaryText,
    ctaSecondaryLink,
    stat1Label,
    stat1Value,
    stat2Label,
    stat2Value,
    stat3Label,
    stat3Value,
    sortOrder,
    isActive,
  };

  if (id) {
    await db.visaSlide.update({ where: { id }, data });
  } else {
    await db.visaSlide.create({ data });
  }

  revalidatePath("/admin/visa");
  revalidatePath("/visa");
  return { ok: true };
}

export async function deleteVisaSlideAction(id: string) {
  await db.visaSlide.delete({ where: { id } });
  revalidatePath("/admin/visa");
  revalidatePath("/visa");
  return { ok: true };
}

export async function updateVisaEnquiryStatusAction(id: string, status: "new" | "in_progress" | "resolved") {
  await db.visaEnquiry.update({ where: { id }, data: { status } });
  revalidatePath("/admin/visa");
  return { ok: true };
}

export async function deleteVisaEnquiryAction(id: string) {
  await db.visaEnquiry.delete({ where: { id } });
  revalidatePath("/admin/visa");
  return { ok: true };
}
