"use client";

import Link from "next/link";
import { useState } from "react";
import { useRooSports } from "@/components/app-provider";
import { toast } from "@/components/ui/toast";
import { ChildAgeNotice } from "@/components/child-profile-feedback";
import type { ChildProfile, SportName } from "@/lib/demo-data";
import { getPublicChildDisplay } from "@/lib/privacy";
import {
  MEDICAL_ALERT_MAX_LENGTH,
  firstChildFieldError,
  getChildDateOfBirthRange,
  validateChildInput,
  type ChildFieldErrors,
} from "@/lib/registration";

const childDateOfBirthRange = getChildDateOfBirthRange();

const sportStyles: Record<SportName, { icon: string; surface: string; accent: string }> = {
  Soccer: {
    icon: "sports_soccer",
    surface: "bg-[#d8eaf2]",
    accent: "bg-[#b7d8e7]",
  },
  Basketball: {
    icon: "sports_basketball",
    surface: "bg-[#f7e5b7]",
    accent: "bg-[#efd17f]",
  },
  "Touch Rugby": {
    icon: "sports_rugby",
    surface: "bg-[#d6e9dd]",
    accent: "bg-[#b8d9c5]",
  },
};

const inputClass = (hasError = false) =>
  `rs-field w-full rounded-2xl px-4 py-3 text-sm ${
    hasError ? "ring-2 ring-[#9a4338]/20" : ""
  }`;

function ChildProfileCard({ child }: { child: ChildProfile }) {
  const { updateChild } = useRooSports();
  const [editing, setEditing] = useState(false);
  const [nickname, setNickname] = useState(child.nickname);
  const [dateOfBirth, setDateOfBirth] = useState(child.dateOfBirth);
  const [primarySport, setPrimarySport] = useState<SportName>(child.primarySport);
  const [medicalAlert, setMedicalAlert] = useState(child.medicalAlert);
  const [fieldErrors, setFieldErrors] = useState<ChildFieldErrors>({});
  const [formError, setFormError] = useState("");

  const style = sportStyles[editing ? primarySport : child.primarySport];
  const display = getPublicChildDisplay(child);

  const startEdit = () => {
    setNickname(child.nickname);
    setDateOfBirth(child.dateOfBirth);
    setPrimarySport(child.primarySport);
    setMedicalAlert(child.medicalAlert);
    setFieldErrors({});
    setFormError("");
    setEditing(true);
  };

  const cancelEdit = () => {
    setEditing(false);
    setFieldErrors({});
    setFormError("");
  };

  const saveEdit = async () => {
    const errors = validateChildInput({ nickname, dateOfBirth, medicalAlert });
    const trimmedNickname = nickname.trim();

    if (!/^[A-Za-z0-9]{10,12}$/.test(trimmedNickname)) {
      errors.nickname =
        "Nickname must be 10–12 characters and contain letters and numbers only.";
    }

    setFieldErrors(errors);
    const message = firstChildFieldError(errors);

    if (message) {
      setFormError(message);
      return;
    }

    try {
      await updateChild(child.id, {
        nickname: nickname.trim(),
        dateOfBirth,
        primarySport,
        medicalAlert: medicalAlert.trim(),
      });

      setEditing(false);
      setFormError("");
      toast.success("Child profile updated", {
        description: `${nickname.trim()}'s profile has been saved.`,
      });
    } catch (error) {
      const msg =
        error instanceof Error
          ? error.message
          : "Unable to update child profile.";
      setFormError(msg);
      toast.error("Update failed", { description: msg });
    }
  };

  return (
    <article className="overflow-hidden rounded-[2rem] border border-white/70 bg-white/45 shadow-[inset_0_1px_0_rgba(255,255,255,0.9),0_20px_55px_rgba(30,55,68,0.06)] backdrop-blur-xl">
      <div className={`relative overflow-hidden p-6 ${style.surface}`}>
        <span
          className={`absolute -right-12 -top-14 h-40 w-40 rounded-full ${style.accent}`}
        />

        <div className="relative flex items-start justify-between gap-3">
          <div className="flex items-center gap-4">
            <span className="grid h-16 w-16 place-items-center rounded-full bg-white/75 text-2xl font-extrabold shadow-[inset_0_1px_0_rgba(255,255,255,0.95)]">
              {(editing ? nickname.trim() || display : display)
                .charAt(0)
                .toUpperCase()}
            </span>

            <div>
              <h3 className="text-2xl font-extrabold tracking-[-0.04em]">
                {editing ? nickname.trim() || display : display}
              </h3>

              <p className="mt-1 flex items-center gap-2 text-xs font-bold text-[#56646c]">
                <span className="material-symbols-outlined text-lg">
                  {style.icon}
                </span>

                {editing
                  ? `${child.ageGroup} · ${primarySport}`
                  : `${child.ageGroup} · ${child.primarySport}`}
              </p>
            </div>
          </div>

          {!editing ? (
            <button
              type="button"
              onClick={startEdit}
              className="inline-flex items-center gap-1 rounded-full bg-white/70 px-3 py-1.5 text-xs font-extrabold text-[#273139]"
            >
              <span className="material-symbols-outlined text-[16px]">
                edit
              </span>
              Edit
            </button>
          ) : null}
        </div>
      </div>

      <div className="p-6">
        {editing ? (
          <div className="space-y-4">
            <div>
              <label
                htmlFor={`nickname-${child.id}`}
                className="mb-1.5 block text-xs font-bold"
              >
                Public nickname
              </label>

              <input
                id={`nickname-${child.id}`}
                value={nickname}
                minLength={10}
                maxLength={12}
                pattern="[A-Za-z0-9]+"
                title="Nickname must be 10–12 characters and contain letters and numbers only."
                onChange={(e) => {
                  setNickname(e.target.value);
                  setFieldErrors((current) => ({
                    ...current,
                    nickname: undefined,
                  }));
                  setFormError("");
                }}
                className={inputClass(Boolean(fieldErrors.nickname))}
              />

              {fieldErrors.nickname ? (
                <p className="mt-1.5 text-sm font-semibold text-[#9a4338]">
                  {fieldErrors.nickname}
                </p>
              ) : null}
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              <div>
                <div className="mb-1.5 flex items-center justify-between gap-3">
                  <label
                    htmlFor={`dob-${child.id}`}
                    className="text-xs font-bold"
                  >
                    Date of birth
                  </label>

                  <ChildAgeNotice compact />
                </div>

                <input
                  id={`dob-${child.id}`}
                  type="date"
                  min={childDateOfBirthRange.min}
                  max={childDateOfBirthRange.max}
                  value={dateOfBirth}
                  onChange={(e) => {
                    setDateOfBirth(e.target.value);
                    setFieldErrors((current) => ({
                      ...current,
                      dateOfBirth: undefined,
                    }));
                    setFormError("");
                  }}
                  className={inputClass(Boolean(fieldErrors.dateOfBirth))}
                />

                {fieldErrors.dateOfBirth ? (
                  <p className="mt-1.5 text-sm font-semibold text-[#9a4338]">
                    {fieldErrors.dateOfBirth}
                  </p>
                ) : null}
              </div>

              <div>
                <label
                  htmlFor={`sport-${child.id}`}
                  className="mb-1.5 block text-xs font-bold"
                >
                  Primary sport
                </label>

                <select
                  id={`sport-${child.id}`}
                  value={primarySport}
                  onChange={(e) =>
                    setPrimarySport(e.target.value as SportName)
                  }
                  className={inputClass()}
                >
                  <option>Soccer</option>
                  <option>Basketball</option>
                  <option>Touch Rugby</option>
                </select>
              </div>
            </div>

            <div>
              <label
                htmlFor={`medical-${child.id}`}
                className="mb-1.5 block text-xs font-bold"
              >
                Essential medical alert
              </label>

              <textarea
                id={`medical-${child.id}`}
                value={medicalAlert}
                onChange={(e) => {
                  setMedicalAlert(e.target.value);
                  setFieldErrors((current) => ({
                    ...current,
                    medicalAlert: undefined,
                  }));
                  setFormError("");
                }}
                maxLength={MEDICAL_ALERT_MAX_LENGTH}
                rows={3}
                placeholder="e.g. Asthma inhaler required"
                aria-invalid={Boolean(fieldErrors.medicalAlert)}
                className={`${inputClass(
                  Boolean(fieldErrors.medicalAlert),
                )} resize-none`}
              />

              <div className="mt-1.5 flex items-center justify-between gap-3 text-xs text-[#758293]">
                <span
                  className={
                    fieldErrors.medicalAlert
                      ? "font-semibold text-[#9a4338]"
                      : ""
                  }
                >
                  {fieldErrors.medicalAlert ||
                    "Visible only to approved staff during an active session."}
                </span>

                <span className="shrink-0 font-semibold tabular-nums">
                  {medicalAlert.length}/{MEDICAL_ALERT_MAX_LENGTH}
                </span>
              </div>
            </div>

            {formError ? (
              <p className="text-sm font-semibold text-[#9a4338]">
                {formError}
              </p>
            ) : null}

            <div className="flex gap-2 pt-1">
              <button
                type="button"
                onClick={saveEdit}
                className="rs-primary-action rounded-full px-5 py-2.5 text-sm font-bold"
              >
                Save changes
              </button>

              <button
                type="button"
                onClick={cancelEdit}
                className="rounded-full bg-white/70 px-5 py-2.5 text-sm font-bold text-[#405760] shadow-[0_10px_28px_rgba(16,38,48,0.06)] transition hover:bg-white"
              >
                Cancel
              </button>
            </div>
          </div>
        ) : (
          <>
            <p className="flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.14em] text-[#68747c]">
              <span className="material-symbols-outlined text-[19px] text-[#c36d1c]">
                health_and_safety
              </span>
              Essential safety note
            </p>

            <p className="mt-3 text-sm leading-6 text-[#2e373c]">
              {child.medicalAlert || "No essential medical alert added."}
            </p>

            <p className="mt-4 text-xs text-[#68747c]">
              Born {child.dateOfBirth}
            </p>

            <p className="mt-4 flex items-center gap-2 text-xs font-semibold text-[#758188]">
              <span className="material-symbols-outlined text-[18px]">
                visibility_lock
              </span>
              Private profile · public nickname only
            </p>
          </>
        )}
      </div>
    </article>
  );
}

export default function FamilyPage() {
  const { children } = useRooSports();
  const hasProfiles = children.length > 0;

  return (
    <div className="pb-8 text-[#0b0f12]">
      <section className="grid items-stretch gap-8 pb-12 pt-4 lg:grid-cols-[1fr_0.94fr] lg:gap-14 lg:pb-16 lg:pt-10">
        <div className="flex min-h-[22rem] flex-col justify-center py-5">
          <p className="flex items-center gap-3 text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#5d686f]">
            <span className="h-2.5 w-2.5 rounded-full bg-[#ef7d00]" />
            Family profiles
          </p>

          <h1 className="mt-5 max-w-3xl text-[clamp(3.15rem,5vw,4.8rem)] font-extrabold leading-[0.94] tracking-[-0.07em]">
            Every player,
            <br />
            thoughtfully covered.
          </h1>

          <p className="mt-7 max-w-xl text-base leading-7 text-[#657078] sm:text-lg">
            Keep age groups, sport preferences and essential safety details
            together without oversharing.
          </p>

        </div>

        <aside className="relative min-h-[22rem] overflow-hidden rounded-[2.5rem] bg-[#dcebf1] p-7 sm:p-9">
          <span className="absolute -right-20 -top-24 h-64 w-64 rounded-full bg-[#ffd47e]" />
          <span className="absolute -right-3 top-4 h-40 w-40 rounded-full border-[24px] border-white/40" />

          <div className="relative flex h-full max-w-md flex-col justify-between">
            <div>
              <span className="inline-flex rounded-full bg-[#0b0f12] px-3 py-1.5 text-[10px] font-extrabold uppercase tracking-[0.16em] text-white">
                {hasProfiles ? "Family at a glance" : "Start here"}
              </span>

              <h2 className="mt-6 max-w-sm text-4xl font-extrabold leading-[1.02] tracking-[-0.055em] sm:text-5xl">
                {hasProfiles
                  ? `${children.length} ${
                      children.length === 1 ? "profile" : "profiles"
                    }. One organised place.`
                  : "One small profile. Much better matches."}
              </h2>

              <p className="mt-5 max-w-sm text-sm leading-6 text-[#526169]">
                {hasProfiles
                  ? "Edit a profile anytime, or add another player when you are ready."
                  : "A public nickname and date of birth are enough to check age eligibility and find the right activities."}
              </p>
            </div>

            <Link
              href="/onboarding/family"
              className="mt-8 flex w-full items-center justify-between rounded-full bg-[#ff9a2f] py-2 pl-6 pr-2 text-sm font-extrabold transition duration-300 hover:bg-[#0b0f12] hover:text-white"
            >
              {hasProfiles ? "Add another profile" : "Add child profile"}

              <span className="grid h-11 w-11 place-items-center rounded-full bg-white text-[#0b0f12]">
                <span className="material-symbols-outlined">
                  add
                </span>
              </span>
            </Link>
          </div>
        </aside>
      </section>

      {hasProfiles && (
        <section className="pt-8 sm:pt-12">
          <div className="mb-7">
            <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#66727a]">
              Your players
            </p>

            <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.05em] sm:text-4xl">
              Ready for the next activity
            </h2>
          </div>

          <div className="grid gap-5 md:grid-cols-2">
            {children.map((child) => (
              <ChildProfileCard
                key={child.id}
                child={child}
              />
            ))}
          </div>
        </section>
      )}
    </div>
  );
}