import { redirect } from "next/navigation";
import Link from "next/link";
import { Shell } from "@/components/Shell";
import { PageHeader } from "@/components/PageHeader";
import { db, people, skills, personSkills } from "@/db";
import { asc, eq } from "drizzle-orm";
import { requireSession } from "@/lib/session";
import { z } from "zod";
import { officeLabel } from "@/lib/format";

const Form = z.object({
  title: z.string().min(1).max(80),
  department: z.string().min(1).max(60),
  office: z.enum(["DUBLIN", "BOSTON", "VANCOUVER", "REMOTE"]),
  bio: z.string().max(1000).optional(),
  linkedinUrl: z.string().url().optional().or(z.literal("")),
  photoUrl: z.string().url().optional().or(z.literal("")),
  interests: z.string().max(500).optional(),
  skills: z.string().max(2000).optional(),
});

async function save(formData: FormData) {
  "use server";
  const session = await requireSession();
  const d = Form.parse(Object.fromEntries(formData));
  const person = await db.query.people.findFirst({ where: eq(people.userId, session.user.id) });
  if (!person) redirect("/");
  const interests = (d.interests ?? "").split(",").map((s) => s.trim()).filter(Boolean);
  await db.update(people).set({ title: d.title, department: d.department, office: d.office, bio: d.bio ?? null, linkedinUrl: d.linkedinUrl || null, photoUrl: d.photoUrl || null, interests, updatedAt: new Date() }).where(eq(people.id, person.id));
  // Skills: "React:5, Copywriting:3" – creates skills that don't exist yet.
  const entries = (d.skills ?? "").split(",").map((s) => s.trim()).filter(Boolean);
  await db.delete(personSkills).where(eq(personSkills.personId, person.id));
  for (const e of entries) {
    const [name, lvl] = e.split(":").map((x) => x.trim());
    if (!name) continue;
    const [skill] = await db.insert(skills).values({ name, category: "craft" }).onConflictDoUpdate({ target: skills.name, set: { name } }).returning({ id: skills.id });
    await db.insert(personSkills).values({ personId: person.id, skillId: skill.id, level: Math.min(5, Math.max(1, parseInt(lvl ?? "3", 10) || 3)) }).onConflictDoNothing();
  }
  redirect(`/people/${person.slug}`);
}

export default async function MePage() {
  const session = await requireSession();
  const person = await db.query.people.findFirst({ where: eq(people.userId, session.user.id), with: { skills: { with: { skill: true } } } });
  if (!person) return <Shell><p className="p-10">Your profile hasn't been created yet – sign out and back in.</p></Shell>;
  const allSkills = await db.query.skills.findMany({ orderBy: asc(skills.name) });
  const field = "w-full rounded-xl border border-line bg-white px-4 py-2.5 text-sm focus:outline-none focus:border-ink";
  return (
    <Shell>
      <PageHeader eyebrow="Your profile" title={<>Tell us who <span className="serif-i">you are.</span></>} intro="Your project history comes from Workamajig automatically. Everything else here is yours – and it's what the team finder searches.">
        <div className="flex gap-3"><Link href={`/people/${person.slug}`} className="btn btn-ghost">View my profile</Link><form action="/api/auth/signout" method="post"><button className="btn btn-ghost">Sign out</button></form></div>
      </PageHeader>
      <form action={save} className="mx-auto max-w-2xl px-5 pb-20 space-y-5">
        <div className="grid gap-3 sm:grid-cols-2">
          <label className="text-sm">Job title<input name="title" defaultValue={person.title} required className={field} /></label>
          <label className="text-sm">Team<input name="department" defaultValue={person.department} required list="depts" className={field} /><datalist id="depts">{["Creative", "UX", "Development", "Analytics", "Brand", "Strategy", "Account", "Media", "Social", "Production", "Operations"].map((d) => <option key={d} value={d} />)}</datalist></label>
        </div>
        <label className="text-sm">Office<select name="office" defaultValue={person.office} className={field}>{Object.entries(officeLabel).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></label>
        <label className="text-sm">Bio<textarea name="bio" defaultValue={person.bio ?? ""} rows={3} placeholder="Two sentences. What you do, what you're into." className={field} /></label>
        <label className="text-sm">LinkedIn URL<input name="linkedinUrl" type="url" defaultValue={person.linkedinUrl ?? ""} className={field} /></label>
        <label className="text-sm">Photo URL <span className="text-mist">(leave blank to use your Google photo)</span><input name="photoUrl" type="url" defaultValue={person.photoUrl ?? ""} className={field} /></label>
        <label className="text-sm">Interests <span className="text-mist">(comma separated)</span><input name="interests" defaultValue={person.interests.join(", ")} placeholder="sea swimming, typography, GAA" className={field} /></label>
        <label className="text-sm">Skills <span className="text-mist">(comma separated, optional :level 1–5)</span>
          <textarea name="skills" rows={3} defaultValue={person.skills.map((s) => `${s.skill.name}:${s.level}`).join(", ")} placeholder="React:5, Art Direction:4, Spanish:3" className={field} />
        </label>
        <p className="text-xs text-mist">Existing skills: {allSkills.map((s) => s.name).join(" · ")}</p>
        <button className="btn btn-soul">Save profile</button>
      </form>
    </Shell>
  );
}
