import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

// TickTick CSV import
export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const formData = await req.formData();
  const file = formData.get("file") as File | null;
  const listId = formData.get("listId") as string | null;

  if (!file || !listId) {
    return NextResponse.json({ error: "file and listId required" }, { status: 400 });
  }

  const list = await prisma.list.findFirst({ where: { id: listId, userId: session.user.id } });
  if (!list) return NextResponse.json({ error: "List not found" }, { status: 404 });

  const text = await file.text();
  const ext = file.name.split(".").pop()?.toLowerCase();

  let imported = 0;

  if (ext === "csv") {
    const lines = text.split("\n");
    const header = lines[0].split(",").map((h) => h.trim().replace(/"/g, ""));
    const titleIdx = header.findIndex((h) => h.toLowerCase().includes("title") || h.toLowerCase().includes("content"));
    const noteIdx = header.findIndex((h) => h.toLowerCase().includes("note") || h.toLowerCase().includes("description"));
    const dueIdx = header.findIndex((h) => h.toLowerCase().includes("due"));
    const priorityIdx = header.findIndex((h) => h.toLowerCase().includes("priority"));
    const completedIdx = header.findIndex((h) => h.toLowerCase().includes("status") || h.toLowerCase().includes("completed"));

    const priorityMap: Record<string, number> = { high: 3, medium: 2, low: 1, none: 0, "3": 3, "2": 2, "1": 1, "0": 0 };

    for (let i = 1; i < lines.length; i++) {
      const line = lines[i].trim();
      if (!line) continue;

      // Handle quoted CSV fields
      const fields: string[] = [];
      let inQuotes = false;
      let current = "";
      for (const ch of line + ",") {
        if (ch === '"') { inQuotes = !inQuotes; }
        else if (ch === "," && !inQuotes) { fields.push(current.trim()); current = ""; }
        else { current += ch; }
      }

      const title = titleIdx >= 0 ? fields[titleIdx]?.replace(/"/g, "") : "";
      if (!title) continue;

      const note = noteIdx >= 0 ? fields[noteIdx]?.replace(/"/g, "") : null;
      const dueRaw = dueIdx >= 0 ? fields[dueIdx] : null;
      const priorityRaw = priorityIdx >= 0 ? fields[priorityIdx]?.toLowerCase() : "0";
      const completedRaw = completedIdx >= 0 ? fields[completedIdx]?.toLowerCase() : "";

      let dueDate: Date | null = null;
      if (dueRaw) {
        const d = new Date(dueRaw);
        if (!isNaN(d.getTime())) dueDate = d;
      }

      const priority = priorityMap[priorityRaw || "0"] ?? 0;
      const completed = completedRaw === "completed" || completedRaw === "true" || completedRaw === "1";

      await prisma.task.create({
        data: {
          userId: session.user.id,
          listId,
          title,
          note: note || null,
          dueDate,
          priority,
          completed,
          completedAt: completed ? new Date() : null,
          sortOrder: imported,
        },
      });
      imported++;
    }
  } else if (ext === "ics") {
    // Parse ICS / iCalendar VTODO
    const todos = text.split("BEGIN:VTODO").slice(1);
    for (const todo of todos) {
      const get = (key: string) => {
        const match = todo.match(new RegExp(`^${key}[^:]*:(.*)$`, "m"));
        return match ? match[1].trim().replace(/\\n/g, "\n") : null;
      };
      const title = get("SUMMARY");
      if (!title) continue;
      const note = get("DESCRIPTION");
      const dueDateRaw = get("DUE") || get("DTSTART");
      let dueDate: Date | null = null;
      if (dueDateRaw) {
        const d = new Date(dueDateRaw.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3"));
        if (!isNaN(d.getTime())) dueDate = d;
      }
      const statusRaw = get("STATUS");
      const completed = statusRaw === "COMPLETED";
      const priorityRaw = get("PRIORITY");
      let priority = 0;
      if (priorityRaw) {
        const p = parseInt(priorityRaw);
        if (p >= 1 && p <= 3) priority = 4 - p; // ICS: 1=high, ours: 3=high
        else if (p >= 4 && p <= 6) priority = 2;
        else if (p >= 7) priority = 1;
      }

      await prisma.task.create({
        data: {
          userId: session.user.id,
          listId,
          title,
          note: note || null,
          dueDate,
          priority,
          completed,
          completedAt: completed ? new Date() : null,
          sortOrder: imported,
        },
      });
      imported++;
    }
  } else {
    return NextResponse.json({ error: "Unsupported file format. Use CSV or ICS." }, { status: 400 });
  }

  return NextResponse.json({ imported });
}