import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { redirect } from "next/navigation"
import { revalidatePath } from "next/cache"
import Link from "next/link"
import { romaniaCounties } from "@/lib/counties"
import { EditPhotos } from "@/components/forms/EditPhotos"
import { GpsUpdater } from "@/components/forms/GpsUpdater"
import { writeFile, mkdir, unlink } from "fs/promises"
import { join } from "path"

export default async function EditEntryPage({ params }: { params: { id: string } }) {
  const session = await auth()

  if (!session?.user) {
    redirect("/login")
  }

  const { id } = await params

  const entry = await db.entry.findUnique({
    where: { id },
    include: { photos: true },
  })

  if (!entry) {
    return (
      <main className="container" style={{ padding: "3rem 1rem", textAlign: "center" }}>
        <h1>Intrarea nu a fost găsită</h1>
        <Link href="/dashboard" style={{ color: "var(--primary)", marginTop: "1rem", display: "inline-block" }}>
          ← Înapoi la Dashboard
        </Link>
      </main>
    )
  }

  const settings = await db.appSettings.findUnique({ where: { id: "GLOBAL_SETTINGS" } })
  const isFrozen = settings?.freezeDate != null && settings.freezeDate <= new Date()

  // Only the owner or an admin can edit, and only if not APPROVED
  const isAdmin = session.user.role === "ADMIN"
  if (entry.userId !== session.user.id && !isAdmin) {
    redirect("/dashboard")
  }

  if (isFrozen && !isAdmin) {
    return (
      <main className="container" style={{ padding: "3rem 1rem", textAlign: "center", minHeight: "100vh" }}>
        <div
          style={{
            maxWidth: "500px",
            margin: "0 auto",
            padding: "2rem",
            background: "var(--surface-color)",
            borderRadius: "var(--radius-lg)",
            border: "1px solid var(--border-color)",
          }}
        >
          <div style={{ fontSize: "3rem", marginBottom: "1rem" }}>🔒</div>
          <h2 style={{ marginBottom: "0.5rem" }}>Competiție Încheiată</h2>
          <p style={{ color: "var(--text-muted)", marginBottom: "1.5rem" }}>
            Perioada de editare a contribuțiilor s-a încheiat. Nu se mai pot face modificări.
          </p>
          <Link
            href="/dashboard"
            style={{
              padding: "0.75rem 1.5rem",
              background: "var(--primary)",
              color: "white",
              borderRadius: "var(--radius-md)",
              fontWeight: 500,
            }}
          >
            ← Înapoi la Dashboard
          </Link>
        </div>
      </main>
    )
  }

  if (entry.status === "APPROVED" && !isAdmin) {
    return (
      <main className="container" style={{ padding: "3rem 1rem", textAlign: "center", minHeight: "100vh" }}>
        <div
          style={{
            maxWidth: "500px",
            margin: "0 auto",
            padding: "2rem",
            background: "var(--surface-color)",
            borderRadius: "var(--radius-lg)",
            border: "1px solid var(--border-color)",
          }}
        >
          <div style={{ fontSize: "3rem", marginBottom: "1rem" }}>🔒</div>
          <h2 style={{ marginBottom: "0.5rem" }}>Intrare Aprobată</h2>
          <p style={{ color: "var(--text-muted)", marginBottom: "1.5rem" }}>
            Această intrare a fost aprobată de un administrator și nu mai poate fi editată.
          </p>
          <Link
            href="/dashboard"
            style={{
              padding: "0.75rem 1.5rem",
              background: "var(--primary)",
              color: "white",
              borderRadius: "var(--radius-md)",
              fontWeight: 500,
            }}
          >
            ← Înapoi la Dashboard
          </Link>
        </div>
      </main>
    )
  }

  // Server action to save edits
  const updateEntry = async (formData: FormData) => {
    "use server"

    // Re-verify frozen state and authorization
    const authSession = await auth()
    const isActionAdmin = authSession?.user?.role === "ADMIN"
    const actionSettings = await db.appSettings.findUnique({ where: { id: "GLOBAL_SETTINGS" } })
    const actionFrozen = actionSettings?.freezeDate != null && actionSettings.freezeDate <= new Date()

    if (actionFrozen && !isActionAdmin) {
      throw new Error("Competiția s-a încheiat. Nu se mai pot face modificări.")
    }

    const deletedPhotoIds = formData.get("deletedPhotoIds") as string
    const ids = deletedPhotoIds ? deletedPhotoIds.split(",").filter(Boolean) : []
    
    if (ids.length > 0) {
      // Delete records and files
      const dbPhotos = await db.photo.findMany({ where: { id: { in: ids }, entryId: id } })
      for (const p of dbPhotos) {
        try {
          // Reconstruct path from url
          if (p.url.startsWith("/rovibe/uploads/")) {
            const relPath = p.url.replace("/rovibe/uploads/", "")
            const filePath = join(process.cwd(), "public", "uploads", relPath)
            await unlink(filePath).catch(() => {}) // Ignore errors if not found
          }
        } catch (e) {}
      }
      await db.photo.deleteMany({ where: { id: { in: ids }, entryId: id } })
    }

    // Update remaining existing photos metadata
    const remainingPhotos = await db.photo.findMany({ where: { entryId: id } })
    for (const rp of remainingPhotos) {
      if (ids.includes(rp.id)) continue;
      const dDate = formData.get(`existing_dateOfCapture_${rp.id}`) as string
      const eq = formData.get(`existing_equipment_${rp.id}`) as string
      const ts = formData.get(`existing_technicalSettings_${rp.id}`) as string
      
      if (dDate) {
        await db.photo.update({
          where: { id: rp.id },
          data: {
            dateOfCapture: new Date(dDate),
            equipment: eq || null,
            technicalSettings: ts || null
          }
        })
      }
    }

    // Process new photos using formData.getAll (files limit manually checked via frontend, but limit up to 5 loop later)
    const newPhotos = formData.getAll("newPhotos") as File[]
    const validNewPhotos = newPhotos.filter(f => f.size > 0 && f.name)
    
    const newDates = formData.getAll("new_dateOfCapture") as string[]
    const newEqs = formData.getAll("new_equipment") as string[]
    const newTs = formData.getAll("new_technicalSettings") as string[]
    
    if (validNewPhotos.length > 0) {
      const uploadsDir = join(process.cwd(), "public", "uploads", id)
      await mkdir(uploadsDir, { recursive: true }).catch(() => {})

      // Determine starting index so we don't overwrite if files have generic names
      // Or simply use timestamps
      const currentCount = await db.photo.count({ where: { entryId: id } })

      let addedCount = 0;
      for (let i = 0; i < validNewPhotos.length; i++) {
        const file = validNewPhotos[i];
        // Ensure strictly max 5 in DB
        if (currentCount + addedCount >= 5) break;

        const buffer = Buffer.from(await file.arrayBuffer())
        const ext = file.name.split(".").pop() || "jpg"
        const safeFilename = `photo_${Date.now()}_${addedCount}.${ext}`
        const filePath = join(uploadsDir, safeFilename)
        
        try {
          await writeFile(filePath, buffer)
          const url = `/rovibe/uploads/${id}/${safeFilename}`
          
          await db.photo.create({
            data: {
              entryId: id,
              url,
              filename: file.name,
              size: file.size,
              dateOfCapture: newDates[i] ? new Date(newDates[i]) : new Date(),
              equipment: newEqs[i] || null,
              technicalSettings: newTs[i] || null,
            }
          })
          addedCount++;
        } catch (fileErr) {
          console.error("Error saving new photo:", fileErr)
        }
      }
    }

    await db.entry.update({
      where: { id },
      data: {
        title: formData.get("title") as string,
        subjectName: formData.get("subjectName") as string,
        address: formData.get("address") as string,
        city: formData.get("city") as string,
        county: formData.get("county") as string,
        latitude: parseFloat((formData.get("latitude") as string).replace(/,/g, ".")),
        longitude: parseFloat((formData.get("longitude") as string).replace(/,/g, ".")),
        lmiRanCode: (formData.get("lmiRanCode") as string) || null,
        estimatedPeriod: (formData.get("estimatedPeriod") as string) || null,
        motivation: formData.get("motivation") as string,
        context: formData.get("context") as string,
        historicalDesc: formData.get("historicalDesc") as string,
        bibliographicSources: formData.get("bibliographicSources") as string,
        personalObservations: (formData.get("personalObservations") as string) || null,
        // Reset to SUBMITTED if it was REJECTED, so admin can review again
        status: entry.status === "REJECTED" ? "SUBMITTED" : entry.status,
      },
    })

    revalidatePath("/dashboard")
    revalidatePath("/admin")
    revalidatePath(`/entry/${id}/edit`)
    redirect(isAdmin ? "/admin" : "/dashboard")
  }

  const inputStyle = {
    width: "100%",
    padding: "0.75rem",
    borderRadius: "var(--radius-sm)",
    border: "1px solid var(--border-color)",
    background: "var(--surface-hover)",
    color: "var(--text-main)",
    fontSize: "0.95rem",
    boxSizing: "border-box" as const,
  }

  const labelStyle = {
    display: "block",
    fontWeight: 500,
    marginBottom: "0.35rem",
    fontSize: "0.9rem",
    color: "var(--text-muted)",
  }

  const groupStyle = { marginBottom: "1.25rem" }

  return (
    <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh", maxWidth: "800px" }}>
      <div style={{ marginBottom: "2rem", display: "flex", alignItems: "center", gap: "1rem" }}>
        <Link
          href={isAdmin ? "/admin" : "/dashboard"}
          style={{ color: "var(--text-muted)", display: "flex", alignItems: "center", gap: "0.25rem", textDecoration: "none" }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="m15 18-6-6 6-6" />
          </svg>
          {isAdmin ? "Admin Dashboard" : "Dashboard"}
        </Link>
        <span style={{ color: "var(--text-muted)" }}>/</span>
        <span style={{ fontWeight: 600 }}>Editează intrarea</span>

        {entry.status === "REJECTED" && (
          <span
            style={{
              marginLeft: "auto",
              fontSize: "0.8rem",
              padding: "0.25rem 0.75rem",
              borderRadius: "999px",
              background: "rgba(239,68,68,0.1)",
              color: "var(--danger)",
              fontWeight: 600,
            }}
          >
            RESPINSĂ — editarea o va retrimite spre aprobare
          </span>
        )}
      </div>

      <div style={{ background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", padding: "2rem" }}>
        <form action={updateEntry}>
          {/* Secțiunea II */}
          <h3 style={{ fontSize: "1.1rem", color: "var(--primary)", borderBottom: "1px solid var(--border-color)", paddingBottom: "0.5rem", marginBottom: "1.5rem" }}>
            II. Date despre obiectiv
          </h3>

          <div style={groupStyle}>
            <label style={labelStyle}>Titlul lucrării *</label>
            <input name="title" defaultValue={entry.title} required maxLength={100} style={inputStyle} />
          </div>

          <div style={groupStyle}>
            <label style={labelStyle}>Denumirea obiectivului / subiectului *</label>
            <input name="subjectName" defaultValue={entry.subjectName} required maxLength={100} style={inputStyle} />
          </div>

          <div style={groupStyle}>
            <label style={labelStyle}>Adresa exactă *</label>
            <input name="address" defaultValue={entry.address} required maxLength={200} style={inputStyle} />
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
            <div style={groupStyle}>
              <label style={labelStyle}>Localitate *</label>
              <input name="city" defaultValue={entry.city} required maxLength={100} style={inputStyle} />
            </div>
            <div style={groupStyle}>
              <label style={labelStyle}>Județ *</label>
              <select name="county" defaultValue={entry.county} required style={inputStyle}>
                {romaniaCounties.map((c) => (
                  <option key={c} value={c}>{c}</option>
                ))}
              </select>
            </div>
            <div style={groupStyle}>
              <label style={labelStyle}>Latitudine *</label>
              <input id="input-lat" name="latitude" type="text" inputMode="decimal" defaultValue={entry.latitude} required style={inputStyle} />
            </div>
            <div style={groupStyle}>
              <label style={labelStyle}>Longitudine *</label>
              <input id="input-lng" name="longitude" type="text" inputMode="decimal" defaultValue={entry.longitude} required style={inputStyle} />
            </div>
            <GpsUpdater />
            <div style={groupStyle}>
              <label style={labelStyle}>Cod LMI / RAN</label>
              <input name="lmiRanCode" defaultValue={entry.lmiRanCode || ""} maxLength={50} style={inputStyle} />
            </div>
            <div style={groupStyle}>
              <label style={labelStyle}>An / Perioadă estimată</label>
              <input name="estimatedPeriod" defaultValue={entry.estimatedPeriod || ""} maxLength={50} style={inputStyle} />
            </div>
          </div>

          {/* Secțiunea IV */}
          <h3 style={{ fontSize: "1.1rem", color: "var(--primary)", borderBottom: "1px solid var(--border-color)", paddingBottom: "0.5rem", marginBottom: "1.5rem", marginTop: "1.5rem" }}>
            IV. Documentare și analiză
          </h3>

          {[
            { name: "motivation", label: "Motivația personală" },
            { name: "context", label: "Context urban/social/cultural" },
            { name: "historicalDesc", label: "Descriere istorică/geografică" },
            { name: "bibliographicSources", label: "Surse bibliografice/web" },
            { name: "personalObservations", label: "Alte observații (Opțional)" },
          ].map(({ name, label }) => (
            <div key={name} style={groupStyle}>
              <label style={labelStyle}>{label}</label>
              <textarea
                name={name}
                defaultValue={(entry as any)[name] || ""}
                rows={4}
                style={{ ...inputStyle, resize: "vertical" }}
                required={name !== "personalObservations"}
              />
            </div>
          ))}

          {/* Photos manager */}
          <EditPhotos initialPhotos={entry.photos} />

          <div style={{ display: "flex", gap: "1rem", justifyContent: "flex-end", marginTop: "2rem" }}>
            <Link
              href={isAdmin ? "/admin" : "/dashboard"}
              style={{
                padding: "0.75rem 1.5rem",
                borderRadius: "var(--radius-md)",
                border: "1px solid var(--border-color)",
                background: "var(--surface-hover)",
                color: "var(--text-main)",
                fontWeight: 500,
              }}
            >
              Anulează
            </Link>
            <button
              type="submit"
              style={{
                padding: "0.75rem 1.5rem",
                borderRadius: "var(--radius-md)",
                background: "var(--primary)",
                color: "white",
                border: "none",
                fontWeight: 600,
                cursor: "pointer",
              }}
            >
              Salvează modificările
            </button>
          </div>
        </form>
      </div>
    </main>
  )
}
