import type { FastifyInstance } from "fastify";
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { type QrStandPreset } from "@menulio/shared";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DATA_FILE = path.resolve(__dirname, "../data/qr-templates.json");

export interface DynamicQrTemplate extends QrStandPreset {
  id: string;
  isActive: boolean;
  bgType?: "gradient" | "image" | "svg";
  bgImageUrl?: string;
  createdAt: string;
  updatedAt: string;
  defaultQrConfig?: {
    xPercent: number;
    yPercent: number;
    size: number;
    borderRadius: number;
    borderColor: string;
    bgBoxColor: string;
  };
  defaultLayers?: Array<{
    id: string;
    text: string;
    xPercent?: number;
    yPercent: number;
    fontSize: number;
    fontFamily?: string;
    color: string;
    fontWeight?: string;
  }>;
}

async function loadTemplatesFromDisk(): Promise<DynamicQrTemplate[]> {
  try {
    const content = await fs.readFile(DATA_FILE, "utf-8");
    const parsed = JSON.parse(content);
    return parsed.map((p: any) => ({
      ...p,
      id: p.key,
      isActive: p.isActive ?? true,
      createdAt: p.createdAt || new Date().toISOString(),
      updatedAt: p.updatedAt || new Date().toISOString(),
      defaultQrConfig: p.defaultQrConfig || p.qrConfig,
      defaultLayers: p.defaultLayers || p.layers,
    }));
  } catch {
    return [];
  }
}

async function saveTemplatesToDisk(templates: DynamicQrTemplate[]): Promise<void> {
  try {
    await fs.writeFile(DATA_FILE, JSON.stringify(templates, null, 2), "utf-8");
  } catch (err) {
    console.error("Failed to write qr-templates to disk:", err);
  }
}

export async function qrTemplatesRoutes(app: FastifyInstance) {
  // 1. Tüm Aktif Şablonları Listele (Mobil ve Web İçin)
  app.get("/qr-templates", async () => {
    const list = await loadTemplatesFromDisk();
    return {
      templates: list.filter((t) => t.isActive),
      total: list.length,
    };
  });

  // 2. Admin Şablon Listesi (Aktif + Taslak hepsi)
  app.get("/admin/qr-templates", async () => {
    const list = await loadTemplatesFromDisk();
    return {
      templates: list,
      total: list.length,
    };
  });

  // 3. Yeni Şablon Ekle veya Mevcut Olanı Güncelle
  app.post<{ Body: Partial<DynamicQrTemplate> }>("/admin/qr-templates", async (req, reply) => {
    const body = req.body;
    if (!body.name) {
      return reply.status(400).send({ error: "Şablon adı zorunludur." });
    }

    const key = body.key || `qr-${Date.now()}`;
    const list = await loadTemplatesFromDisk();
    const existingIndex = list.findIndex((t) => t.id === key || t.key === key);

    const now = new Date().toISOString();
    const newTemplate: DynamicQrTemplate = {
      key,
      id: key,
      name: body.name,
      categoryName: body.categoryName || "Özel Şablon",
      svgTemplateUrl: body.svgTemplateUrl || `/templates/${key}.svg`,
      aspectRatio: body.aspectRatio || "1/1",
      bgType: body.bgType || "gradient",
      bgImageUrl: body.bgImageUrl,
      bgGradient: body.bgGradient || "radial-gradient(circle at 50% 50%, #132034 0%, #0b0d13 100%)",
      plaqueColor: body.plaqueColor || "#132034",
      borderAccent: body.borderAccent || "#D4AF37",
      accentText: body.accentText || "#D4AF37",
      headerText: body.headerText || "#FFFFFF",
      subText: body.subText || "#E5C378",
      dividerColor: body.dividerColor || "rgba(212, 175, 55, 0.3)",
      isActive: body.isActive !== undefined ? body.isActive : true,
      createdAt: existingIndex >= 0 ? list[existingIndex].createdAt : now,
      updatedAt: now,
      defaultQrConfig: body.defaultQrConfig || (body as any).qrConfig || {
        xPercent: 50,
        yPercent: 38,
        size: 115,
        borderRadius: 14,
        borderColor: body.borderAccent || "#D4AF37",
        bgBoxColor: "#FFFFFF",
      },
      defaultLayers: body.defaultLayers || (body as any).layers || [
        {
          id: "rName",
          text: "{{RESTAURANT_NAME}}",
          yPercent: 16,
          fontSize: 18,
          color: body.accentText || "#D4AF37",
          fontWeight: "800",
        },
      ],
    };

    if (existingIndex >= 0) {
      list[existingIndex] = newTemplate;
    } else {
      list.unshift(newTemplate);
    }

    await saveTemplatesToDisk(list);
    return { success: true, template: newTemplate };
  });

  // 4. Şablon Sil
  app.delete<{ Params: { id: string } }>("/admin/qr-templates/:id", async (req, reply) => {
    const { id } = req.params;
    const list = await loadTemplatesFromDisk();
    const filtered = list.filter((t) => t.id !== id && t.key !== id);

    if (filtered.length === list.length) {
      return reply.status(404).send({ error: "Şablon bulunamadı." });
    }

    await saveTemplatesToDisk(filtered);
    return { success: true, deletedId: id };
  });
}
