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 { userCounties } from "@/lib/userCounties"

export default async function AccountSettingsPage() {
  const session = await auth()
  if (!session?.user) redirect("/login")

  const user = await db.user.findUnique({
    where: { id: session.user.id },
    select: { id: true, name: true, email: true, class: true, county: true, role: true, image: true },
  })

  if (!user) redirect("/login")

  const updateProfile = async (formData: FormData) => {
    "use server"
    const name = (formData.get("name") as string).trim()
    const studentClass = formData.get("class") as string
    const county = formData.get("county") as string

    if (!name) return

    await db.user.update({
      where: { id: session.user.id! },
      data: {
        name,
        class: studentClass || null,
        county: county || null,
      },
    })
    revalidatePath("/dashboard")
    revalidatePath("/admin")
    revalidatePath("/account/settings")
    redirect(user.role === "ADMIN" ? "/admin" : "/dashboard")
  }

  const backHref = user.role === "ADMIN" ? "/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)",
  }

  return (
    <main
      className="container"
      style={{ padding: "3rem 1rem", minHeight: "100vh", maxWidth: "600px" }}
    >
      {/* Breadcrumb */}
      <div style={{ display: "flex", alignItems: "center", gap: "0.75rem", marginBottom: "2rem" }}>
        <Link
          href={backHref}
          style={{ color: "var(--text-muted)", display: "flex", alignItems: "center", gap: "0.3rem", 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>
          {user.role === "ADMIN" ? "Dashboard Admin" : "Dashboard"}
        </Link>
        <span style={{ color: "var(--text-muted)" }}>/</span>
        <span style={{ fontWeight: 600 }}>Setări cont</span>
      </div>

      {/* Avatar + current info */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: "1.25rem",
          padding: "1.5rem",
          background: "var(--surface-color)",
          border: "1px solid var(--border-color)",
          borderRadius: "var(--radius-lg)",
          marginBottom: "1.5rem",
        }}
      >
        <div
          style={{
            width: "60px",
            height: "60px",
            borderRadius: "999px",
            background: "var(--primary)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: "1.5rem",
            fontWeight: 700,
            color: "white",
            flexShrink: 0,
          }}
        >
          {user.name ? user.name[0].toUpperCase() : user.email?.[0].toUpperCase() ?? "?"}
        </div>
        <div>
          <div style={{ fontWeight: 700, fontSize: "1.1rem" }}>{user.name || "—"}</div>
          <div style={{ color: "var(--text-muted)", fontSize: "0.9rem" }}>{user.email}</div>
          <div style={{ marginTop: "0.35rem", display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
            <span
              style={{
                padding: "0.15rem 0.6rem",
                borderRadius: "999px",
                fontSize: "0.78rem",
                fontWeight: 600,
                background: user.role === "ADMIN" ? "rgba(99,102,241,0.12)" : "rgba(16,185,129,0.1)",
                color: user.role === "ADMIN" ? "var(--primary)" : "var(--success)",
              }}
            >
              {user.role === "ADMIN" ? "Administrator" : "Elev"}
            </span>
            {user.class && (
              <span
                style={{
                  padding: "0.15rem 0.6rem",
                  borderRadius: "999px",
                  fontSize: "0.78rem",
                  fontWeight: 600,
                  background: "var(--surface-hover)",
                  color: "var(--text-muted)",
                }}
              >
                Clasa a {user.class}-a
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Edit form */}
      <div
        style={{
          background: "var(--surface-color)",
          border: "1px solid var(--border-color)",
          borderRadius: "var(--radius-lg)",
          padding: "2rem",
        }}
      >
        <h2 style={{ fontSize: "1.1rem", fontWeight: 600, marginBottom: "1.5rem" }}>
          ✏️ Modifică informațiile contului
        </h2>

        <form action={updateProfile}>
          {/* Name */}
          <div style={{ marginBottom: "1.25rem" }}>
            <label style={labelStyle}>Nume și prenume *</label>
            <input
              name="name"
              defaultValue={user.name || ""}
              required
              maxLength={100}
              placeholder="Ex: Ion Popescu"
              style={inputStyle}
            />
            <p style={{ fontSize: "0.8rem", color: "var(--text-muted)", marginTop: "0.3rem" }}>
              Acesta este numele care va apărea pe intrările tale.
            </p>
          </div>

          {/* Email (read-only) */}
          <div style={{ marginBottom: "1.25rem" }}>
            <label style={labelStyle}>Adresă e-mail</label>
            <input
              type="email"
              disabled
              value={user.email || ""}
              style={{ ...inputStyle, opacity: 0.6, cursor: "not-allowed" }}
            />
            <p style={{ fontSize: "0.8rem", color: "var(--text-muted)", marginTop: "0.3rem" }}>
              Adresa de e-mail nu poate fi modificată direct. Contactează un administrator dacă este nevoie.
            </p>
          </div>

          {/* Class (only for students) */}
          {user.role === "STUDENT" && (
            <div style={{ marginBottom: "1.25rem" }}>
              <label style={labelStyle}>Clasa</label>
              <select name="class" defaultValue={user.class || ""} style={inputStyle}>
                <option value="">— Neselectat —</option>
                <option value="9">Clasa a IX-a</option>
                <option value="10">Clasa a X-a</option>
                <option value="11">Clasa a XI-a</option>
                <option value="12">Clasa a XII-a</option>
              </select>
            </div>
          )}

          {/* County */}
          <div style={{ marginBottom: "1.25rem" }}>
            <label style={labelStyle}>Județ</label>
            <select name="county" defaultValue={user.county || ""} style={inputStyle}>
              <option value="">— Neselectat —</option>
              {userCounties.map(countyItem => (
                <option key={countyItem} value={countyItem}>{countyItem}</option>
              ))}
            </select>
          </div>

          <div style={{ display: "flex", gap: "1rem", justifyContent: "flex-end", marginTop: "2rem" }}>
            <Link
              href={backHref}
              style={{
                padding: "0.75rem 1.5rem",
                borderRadius: "var(--radius-md)",
                background: "var(--surface-hover)",
                border: "1px solid var(--border-color)",
                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>

      {/* Future fields note */}
      <p style={{ marginTop: "1.25rem", fontSize: "0.85rem", color: "var(--text-muted)", textAlign: "center" }}>
        Alte câmpuri de profil pot fi adăugate în viitor (școală, oraș, telefon etc.)
      </p>
    </main>
  )
}
