/**
 * Parent: My Child's Medical Record (read + edit).
 * Lists linked children via /api/users/children and lets the parent pick which
 * child's record to view. Each child view goes through ParentMedicalView in
 * MedicalViews.tsx which fetches the medical profile + logs + history and
 * allows editing the profile (parents write directly per the user's answer).
 */

import { useEffect, useState } from 'react';
import api from '../../store/auth';
import { ParentMedicalView } from '../medical/MedicalViews';

interface Child { id: number; uid: string; first_name: string; last_name: string; }

export default function ParentMedical() {
  const [children, setChildren] = useState<Child[]>([]);
  const [active, setActive] = useState<Child | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const r = await api.get('/users/children');
        const list = r.data || [];
        setChildren(list);
        if (list.length > 0) setActive(list[0]);
      } catch (e: any) {
        setError(e?.message || 'Failed to load children');
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  if (loading) {
    return (
      <div className="space-y-8 animate-in fade-in duration-700 pb-10 p-10 text-center text-text-muted">
        Loading your children…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6 m-6 bg-red-50 border border-red-200 rounded-2xl text-red-700 text-xs font-bold">
        {error}
      </div>
    );
  }

  if (children.length === 0) {
    return (
      <div className="space-y-8 animate-in fade-in duration-700 pb-10">
        <h1 className="text-3xl font-black text-text tracking-tight uppercase">No Children Linked</h1>
        <p className="text-text-muted">Ask the school office to link your children to your account.</p>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-in fade-in duration-700 pb-10">
      <div className="flex flex-wrap gap-2 p-2 bg-card border border-border rounded-2xl">
        {children.map((c) => (
          <button
            key={c.id}
            onClick={() => setActive(c)}
            className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-widest transition-all
              ${active?.id === c.id ? 'bg-primary text-white' : 'text-text-muted hover:text-text hover:bg-muted'}`}
          >
            {c.first_name} {c.last_name}
          </button>
        ))}
      </div>
      {active && <ParentMedicalView key={active.id} studentUid={active.uid} />}
    </div>
  );
}
