import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/Button";
import { getTeamMemberForAdmin } from "@/lib/team/queries";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  SelectField,
  StatusBadge,
  ConfirmButton,
  ImageUpload,
  MarkdownEditor,
} from "@/components/admin";
import { updateTeamMember, setTeamMemberStatus, deleteTeamMember } from "../actions";

export const dynamic = "force-dynamic";

const statusOptions = ["active", "archived"] as const;

export default async function AdminTeamMemberEditor({
  params,
}: {
  params: Promise<{ memberId: string }>;
}) {
  const { memberId } = await params;
  const member = await getTeamMemberForAdmin(memberId);
  if (!member) notFound();

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/team"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          All members
        </Link>
      </div>

      <AdminHeading
        eyebrow={`Member · ${member.slug}`}
        title={member.name}
        lede={member.title || "—"}
        actions={
          <div className="flex gap-2">
            <StatusBadge label={member.role} />
            <StatusBadge label={member.status} dot />
          </div>
        }
      />

      <div className="grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-6">
          <FormSection title="Profile">
            <form action={updateTeamMember} className="grid gap-4 md:grid-cols-2">
              <input type="hidden" name="id" value={member.id} />
              <InputField label="Name" name="name" defaultValue={member.name} required />
              <InputField label="Title" name="title" defaultValue={member.title} />
              <SelectField
                label="Role"
                name="role"
                defaultValue={member.role}
                options={[
                  { value: "lead", label: "Lead" },
                  { value: "committee", label: "Committee" },
                  { value: "contributor", label: "Contributor" },
                ]}
              />
              <InputField
                label="Position (sort order)"
                name="position"
                type="number"
                defaultValue={String(member.position)}
              />
              <InputField label="Country" name="country" defaultValue={member.country} />
              <InputField label="Institution" name="institution" defaultValue={member.institution} />
              <div className="md:col-span-2">
                <ImageUpload
                  name="photo"
                  altName="photoAlt"
                  folder="team"
                  label="Portrait"
                  defaultValue={member.photo}
                  defaultAlt={member.photoAlt}
                />
              </div>
              <InputField label="ORCID URL" name="orcidUrl" defaultValue={member.orcidUrl ?? ""} />
              <InputField label="LinkedIn URL" name="linkedinUrl" defaultValue={member.linkedinUrl ?? ""} />
              <InputField
                label="Website URL"
                name="websiteUrl"
                defaultValue={member.websiteUrl ?? ""}
                wrapClassName="md:col-span-2"
              />
              <div className="md:col-span-2">
                <MarkdownEditor
                  name="bio"
                  label="Bio"
                  defaultValue={member.bio}
                  rows={10}
                  maxLength={10000}
                  folder="team"
                  hint="A couple of paragraphs describing the member's role, affiliations, and research interests"
                />
              </div>
              <div className="md:col-span-2">
                <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                  Save member
                </Button>
              </div>
            </form>
          </FormSection>

          <FormSection
            title="Danger zone"
            description="Deleting removes this member from the public team page."
            tone="danger"
          >
            <form action={deleteTeamMember}>
              <input type="hidden" name="id" value={member.id} />
              <ConfirmButton
                label="Delete member"
                confirmLabel="Click again to delete permanently"
                tone="danger"
              />
            </form>
          </FormSection>
        </div>

        <aside className="flex flex-col gap-6">
          <FormSection title="Status">
            <div className="flex flex-col gap-2">
              {statusOptions.map((s) => (
                <form key={s} action={setTeamMemberStatus}>
                  <input type="hidden" name="id" value={member.id} />
                  <input type="hidden" name="status" value={s} />
                  <button
                    type="submit"
                    disabled={member.status === s}
                    className={
                      member.status === s
                        ? "w-full rounded-lg bg-[var(--color-blue)] px-3 py-2 text-[13px] font-semibold text-white"
                        : "w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                    }
                  >
                    {member.status === s ? `Current · ${s}` : `Set to ${s}`}
                  </button>
                </form>
              ))}
            </div>
          </FormSection>
        </aside>
      </div>
    </>
  );
}
