"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useFamily } from "@/app/FamilyProvider";
import type { Circle } from "@/types";

type PendingInvite = {
  id: string;
  token: string;
  circleId: string;
  circleName: string;
  inviterName: string;
  memberCount: number;
  expiresAt: string;
};

export default function CirclePage() {
  const router = useRouter();
  const { familyId } = useFamily();
  const [circles, setCircles]           = useState<Circle[]>([]);
  const [pendingInvites, setPendingInvites] = useState<PendingInvite[]>([]);
  const [loading, setLoading]           = useState(true);
  const [creating, setCreating]         = useState(false);
  const [newName, setNewName]           = useState("");
  const [showCreate, setShowCreate]     = useState(false);
  const [joiningId, setJoiningId]       = useState<string | null>(null);

  useEffect(() => {
    if (familyId) { fetchCircles(); fetchPendingInvites(); }
  }, [familyId]);

  const fetchCircles = async () => {
    try {
      const res  = await fetch("/api/circles");
      const data = await res.json();
      setCircles(data.circles ?? []);
    } catch { /* silent */ }
    setLoading(false);
  };

  const fetchPendingInvites = async () => {
    try {
      const res  = await fetch("/api/circles/invites");
      const data = await res.json();
      setPendingInvites(data.invites ?? []);
    } catch { /* silent */ }
  };

  const createCircle = async () => {
    if (!newName.trim()) return;
    setCreating(true);
    try {
      const res  = await fetch("/api/circles", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ name: newName.trim() }),
      });
      const data = await res.json();
      if (data.success) {
        setNewName("");
        setShowCreate(false);
        router.push(`/circle/${data.circle.id}`);
      }
    } catch { /* silent */ }
    setCreating(false);
  };

  const acceptInvite = async (invite: PendingInvite) => {
    setJoiningId(invite.id);
    try {
      const res  = await fetch(`/api/circle/join/${invite.token}`, { method: "POST" });
      const data = await res.json();
      if (data.success) {
        router.push(`/circle/${data.circleId}`);
      } else {
        alert(data.error ?? "Could not join circle");
        setPendingInvites(prev => prev.filter(i => i.id !== invite.id));
      }
    } catch { /* silent */ }
    setJoiningId(null);
  };

  const declineInvite = (inviteId: string) => {
    setPendingInvites(prev => prev.filter(i => i.id !== inviteId));
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 pb-24">
      {/* Header */}
      <div className="p-4 flex items-center gap-3">
        <button onClick={() => router.back()} className="p-2 rounded-xl bg-white dark:bg-gray-800 shadow-sm text-xl">←</button>
        <div className="flex-1">
          <h1 className="text-xl font-bold">My Circles</h1>
          <p className="text-xs text-gray-500 dark:text-gray-400">Private groups with trusted families</p>
        </div>
        <button
          onClick={() => setShowCreate(v => !v)}
          className="px-4 py-2 bg-rose-400 text-white rounded-xl text-sm font-medium"
        >+ New</button>
      </div>

      {/* Create circle form */}
      {showCreate && (
        <div className="mx-4 mb-4 p-4 bg-white dark:bg-gray-800 rounded-2xl shadow-sm space-y-3">
          <p className="text-sm font-medium text-gray-700 dark:text-gray-200">Create a new Circle</p>
          <input
            id="circle-name"
            name="circle-name"
            autoFocus
            autoComplete="off"
            value={newName}
            onChange={e => setNewName(e.target.value)}
            onKeyDown={e => e.key === "Enter" && createCircle()}
            placeholder="e.g. NCB Mamas 2024"
            className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-xl text-sm outline-none border border-gray-200 dark:border-gray-600 focus:border-rose-400"
          />
          <div className="flex gap-2">
            <button
              onClick={createCircle}
              disabled={creating || !newName.trim()}
              className="flex-1 py-2 bg-rose-400 text-white rounded-xl text-sm font-medium disabled:opacity-50"
            >{creating ? "Creating…" : "Create Circle"}</button>
            <button onClick={() => setShowCreate(false)} className="px-4 py-2 text-gray-400 text-sm">Cancel</button>
          </div>
        </div>
      )}

      {/* Pending invites */}
      {pendingInvites.length > 0 && (
        <div className="px-4 mb-4 space-y-2">
          <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide px-1 mb-1">Pending Invites</p>
          {pendingInvites.map(inv => (
            <div key={inv.id} className="bg-rose-50 dark:bg-rose-900/20 border border-rose-200 dark:border-rose-700 rounded-2xl p-4 flex items-center gap-3">
              <div className="w-10 h-10 bg-rose-100 dark:bg-rose-900/40 rounded-full flex items-center justify-center text-xl flex-shrink-0">
                👨‍👩‍👧‍👦
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold truncate">{inv.circleName}</p>
                <p className="text-xs text-gray-500">{inv.inviterName} invited you · {inv.memberCount} {inv.memberCount === 1 ? "family" : "families"}</p>
              </div>
              <div className="flex gap-2 flex-shrink-0">
                <button
                  onClick={() => acceptInvite(inv)}
                  disabled={joiningId === inv.id}
                  className="px-3 py-1.5 bg-rose-400 text-white rounded-xl text-xs font-medium disabled:opacity-50"
                >{joiningId === inv.id ? "…" : "Join"}</button>
                <button
                  onClick={() => declineInvite(inv.id)}
                  className="px-3 py-1.5 bg-gray-100 dark:bg-gray-700 text-gray-500 rounded-xl text-xs"
                >✕</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* List */}
      <div className="px-4 space-y-3">
        {loading ? (
          <div className="flex justify-center py-16">
            <div className="flex gap-2 text-3xl">
              {["👨‍👩‍👧", "💬", "❤️"].map((e, i) => (
                <span key={i} className="animate-bounce" style={{ animationDelay: `${i * 120}ms` }}>{e}</span>
              ))}
            </div>
          </div>
        ) : circles.length === 0 && pendingInvites.length === 0 ? (
          <div className="text-center py-16 px-8">
            <p className="text-4xl mb-3">👨‍👩‍👧‍👦</p>
            <p className="font-semibold text-gray-700 dark:text-gray-200">No circles yet</p>
            <p className="text-sm text-gray-400 mt-1">Create one and invite trusted families to share milestones privately.</p>
          </div>
        ) : (
          circles.map(c => (
            <Link
              key={c.id}
              href={`/circle/${c.id}`}
              className="flex items-center gap-4 p-4 bg-white dark:bg-gray-800 rounded-2xl shadow-sm"
            >
              <div className="w-12 h-12 bg-rose-100 dark:bg-rose-900/40 rounded-full flex items-center justify-center text-2xl flex-shrink-0">
                👨‍👩‍👧
              </div>
              <div className="flex-1 min-w-0">
                <div className="font-semibold truncate">{c.name}</div>
                <div className="text-xs text-gray-400">{c.memberCount} {c.memberCount === 1 ? "family" : "families"} · {c.role === "admin" ? "Admin" : "Member"}</div>
              </div>
              <span className="text-gray-400">›</span>
            </Link>
          ))
        )}
      </div>
    </div>
  );
}
