"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

const inputClass =
  "mt-2 h-11 w-full rounded-xl border border-slate-200/80 bg-white px-4 text-sm font-medium text-[#0D1B2A] outline-none transition focus:border-[#1D4ED8] focus:ring-2 focus:ring-[#1D4ED8]/20";

type FamilyManagementFormProps = {
  family: {
    id: string;
    parentName: string;
    email: string;
    phone: string;
    suburb: string;
    postcode: string;
    children: Array<{
      id: string;
      nickname: string;
      dateOfBirth: string;
      primarySport: string;
    }>;
  };
};

function formatChildDate(value: string) {
  const [year, month, day] = value.split("-");

  if (!year || !month || !day) {
    return value;
  }

  return `${day}/${month}/${year}`;
}

export function FamilyManagementForm({
  family,
}: FamilyManagementFormProps) {
  const router = useRouter();

  const [isSaving, setIsSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const save = async (
    formEvent: React.FormEvent<HTMLFormElement>,
  ) => {
    formEvent.preventDefault();

    setIsSaving(true);
    setMessage("");
    setError("");

    const form = new FormData(formEvent.currentTarget);

    try {
      // Added: only parent contact/profile fields are sent for updating.
      const response = await fetch(
        `/api/admin/families/${family.id}`,
        {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(Object.fromEntries(form)),
        },
      );

      const payload = (await response.json()) as {
        error?: string;
      };

      if (!response.ok) {
        setError(
          payload.error || "Unable to update this family.",
        );
      } else {
        setMessage("Family changes saved.");
        router.refresh();
      }
    } catch {
      setError("Unable to update this family.");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="mt-6 grid gap-5 xl:grid-cols-[0.9fr_1.1fr]">
      {/* Parent details are editable. */}
      <form
        onSubmit={save}
        className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs sm:p-7"
      >
        <div>
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#F97316]">
            Parent details
          </p>

          <h2 className="mt-1 text-lg font-bold tracking-tight text-[#0D1B2A]">
            Account information
          </h2>

          <p className="mt-2 text-sm leading-6 text-[#6f8087]">
            Update the parent&apos;s basic contact and location
            information.
          </p>
        </div>

        <div className="mt-6 grid gap-5">
          <label className="text-xs font-extrabold text-[#405760]">
            Parent name
            <input
              required
              name="name"
              defaultValue={family.parentName}
              maxLength={201}
              className={inputClass}
            />
          </label>

          <label className="text-xs font-extrabold text-[#405760]">
            Email
            <input
              required
              type="email"
              name="email"
              defaultValue={family.email}
              maxLength={255}
              className={inputClass}
            />
          </label>

          <label className="text-xs font-extrabold text-[#405760]">
            Phone
            <input
              type="tel"
              name="phone"
              defaultValue={family.phone}
              maxLength={30}
              className={inputClass}
            />
          </label>

          <div className="grid gap-5 sm:grid-cols-2">
            <label className="text-xs font-extrabold text-[#405760]">
              Suburb
              <input
                name="suburb"
                defaultValue={family.suburb}
                maxLength={120}
                className={inputClass}
              />
            </label>

            <label className="text-xs font-extrabold text-[#405760]">
              Postcode
              <input
                name="postcode"
                defaultValue={family.postcode}
                maxLength={12}
                className={inputClass}
              />
            </label>
          </div>
        </div>

        {error ? (
          <div className="mt-5 rounded-2xl bg-[#fff0ed] px-4 py-3 text-sm font-bold text-[#a33a2b]">
            {error}
          </div>
        ) : null}

        {message ? (
          <div className="mt-5 rounded-2xl bg-[#eaf6ee] px-4 py-3 text-sm font-bold text-[#2f6b48]">
            {message}
          </div>
        ) : null}

        <div className="mt-6">
          <button
            type="submit"
            disabled={isSaving}
            className="inline-flex h-10 items-center justify-center rounded-xl bg-[#1D4ED8] px-5 text-xs font-semibold text-white shadow-xs transition hover:bg-[#1e40af] disabled:cursor-not-allowed disabled:opacity-55"
          >
            {isSaving ? "Saving..." : "Save changes"}
          </button>
        </div>
      </form>

      {/* Child information is intentionally read-only and privacy-safe. */}
      <section className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs sm:p-7">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#F97316]">
              Child profiles
            </p>

            <h2 className="mt-1 text-lg font-bold tracking-tight text-[#0D1B2A]">
              Linked children
            </h2>

            <p className="mt-1.5 text-xs leading-relaxed text-slate-500">
              Basic profile information only. Child details
              cannot be edited from this page.
            </p>
          </div>

          <span className="rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1 text-[10px] font-semibold text-emerald-700">
            Read only
          </span>
        </div>

        {family.children.length === 0 ? (
          <div className="mt-6 rounded-2xl border border-dashed border-slate-200 bg-slate-50/50 px-5 py-8 text-center">
            <span className="material-symbols-outlined text-3xl text-slate-400">
              family_restroom
            </span>

            <p className="mt-2 text-sm font-semibold text-[#0D1B2A]">
              No child profiles
            </p>

            <p className="mt-1 text-xs text-slate-400">
              This parent does not currently have an active
              child profile.
            </p>
          </div>
        ) : (
          <div className="mt-6 grid gap-3">
            {family.children.map((child) => (
              <article
                key={child.id}
                className="rounded-xl border border-slate-200/80 bg-slate-50/50 p-4"
              >
                <div className="flex items-center gap-3">
                  <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-orange-50 text-[#F97316]">
                    <span className="material-symbols-outlined text-[20px]">
                      child_care
                    </span>
                  </div>

                  <div>
                    <h3 className="text-sm font-bold text-[#0D1B2A]">
                      {child.nickname}
                    </h3>
                    <p className="mt-0.5 text-[10px] font-semibold uppercase tracking-wider text-slate-400">
                      Child profile
                    </p>
                  </div>
                </div>

                <dl className="mt-4 grid gap-3 sm:grid-cols-2">
                  <div>
                    <dt className="text-[10px] font-semibold uppercase tracking-wider text-slate-400">
                      Date of birth
                    </dt>
                    <dd className="mt-0.5 text-xs font-semibold text-[#0D1B2A]">
                      {formatChildDate(child.dateOfBirth)}
                    </dd>
                  </div>

                  <div>
                    <dt className="text-[10px] font-semibold uppercase tracking-wider text-slate-400">
                      Primary sport
                    </dt>
                    <dd className="mt-0.5 text-xs font-semibold text-[#0D1B2A]">
                      {child.primarySport}
                    </dd>
                  </div>
                </dl>
              </article>
            ))}
          </div>
        )}

        <div className="mt-5 flex items-start gap-2 rounded-xl border border-emerald-100 bg-emerald-50/60 px-4 py-3 text-xs leading-5 text-emerald-800">
          <span className="material-symbols-outlined mt-0.5 text-[18px] text-emerald-600">
            shield_person
          </span>

          <p>
            Medical, allergy and emergency information is not
            displayed on this general family management page.
          </p>
        </div>
      </section>
    </div>
  );
}