"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function FamilySwitcher() {
  const router = useRouter();
  const [families, setFamilies] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [members, setMembers] = useState<any[]>([]);

  useEffect(() => {
    fetchFamilies();
  }, []);

  const fetchFamilies = async () => {
    try {
      // TODO: Get families from API with current user session
      // For now, show single family
      setFamilies([{ id: "default", name: "Our Family" }]);
      setLoading(false);
    } catch (err) {
      console.error("Failed to fetch families:", err);
      setLoading(false);
    }
  };

  const fetchMembers = async (familyId: string) => {
    try {
      const res = await fetch(`/api/family/members?familyId=${familyId}`);
      const data = await res.json();
      setMembers(data.members || []);
    } catch (err) {
      console.error("Failed to fetch members:", err);
    }
  };

  const handleFamilySelect = (familyId: string) => {
    setOpen(false);
    // TODO: Switch to selected family
    router.refresh();
  };

  if (loading) return null;

  if (families.length <= 1) return null; // Don't show if only one family

  return (
    <div className="relative">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-2 px-3 py-1 bg-white dark:bg-gray-800 rounded-lg text-sm"
      >
        <span>👨‍👩‍👧</span>
        <span className="max-w-[100px] truncate">{families[0]?.name || "Family"}</span>
        <span className="text-gray-400">▼</span>
      </button>

      {open && (
        <div className="absolute top-full right-0 mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg z-50">
          {families.map((family) => (
            <button
              key={family.id}
              onClick={() => handleFamilySelect(family.id)}
              className="w-full px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700"
            >
              {family.name}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}