"use client";

import { useEffect, useState } from "react";
import { Button, Input, Select, Badge } from "@/components/ui";

interface Member {
  id: string;
  userId: string;
  email: string;
  role: string;
  displayName: string;
}

interface Family {
  id: string;
  name: string;
  tier: string;
  maxChildren: number;
  maxMembers: number;
  createdAt: string;
  userCount: number;
  childCount: number;
  logCount: number;
  memoryCount: number;
  members: Member[];
}

export default function AdminFamilies() {
  const [families, setFamilies] = useState<Family[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [tierFilter, setTierFilter] = useState("all");
  const [showMembers, setShowMembers] = useState<string | null>(null);
  const [tierChanging, setTierChanging] = useState<string | null>(null);
  const [removingMemberId, setRemovingMemberId] = useState<string | null>(null);
  const [deletingFamilyId, setDeletingFamilyId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // New family form
  const [showNewFamily, setShowNewFamily] = useState(false);
  const [newFamilyName, setNewFamilyName] = useState("");
  const [creatingFamily, setCreatingFamily] = useState(false);

  // Add member form
  const [memberForms, setMemberForms] = useState<Record<string, { email: string; role: string }>>({});

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

  const showMessage = (msg: string, type: "success" | "error") => {
    if (type === "success") { setSuccess(msg); setTimeout(() => setSuccess(null), 3000); }
    else { setError(msg); setTimeout(() => setError(null), 5000); }
  };

  const fetchFamilies = async () => {
    try {
      const res = await fetch("/api/admin/families", { credentials: "include" });
      const data = await res.json();
      if (data.error) throw new Error(data.error);
      setFamilies(data.families || []);
    } catch (err: any) {
      showMessage(err.message || "Failed to load families", "error");
    }
    setLoading(false);
  };

  const handleCreateFamily = async () => {
    if (!newFamilyName.trim()) return;
    setCreatingFamily(true);
    try {
      const res = await fetch("/api/admin/families", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ name: newFamilyName.trim() }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create family");
      showMessage(`Family "${newFamilyName.trim()}" created`, "success");
      setNewFamilyName("");
      setShowNewFamily(false);
      fetchFamilies();
    } catch (err: any) {
      showMessage(err.message, "error");
    }
    setCreatingFamily(false);
  };

  const handleAddMember = async (familyId: string) => {
    const form = memberForms[familyId];
    if (!form?.email) return;
    try {
      const res = await fetch("/api/admin/families", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ familyId, email: form.email, role: form.role || "caregiver", displayName: form.email }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to add member");
      showMessage("Member added", "success");
      setMemberForms(prev => ({ ...prev, [familyId]: { email: "", role: "caregiver" } }));
      fetchFamilies();
    } catch (err: any) {
      showMessage(err.message, "error");
    }
  };

  const handleRemoveMember = async (memberId: string) => {
    if (!window.confirm("Remove this member from the family?")) return;
    setRemovingMemberId(memberId);
    try {
      const res = await fetch(`/api/admin/families?memberId=${memberId}`, {
        method: "DELETE",
        credentials: "include",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to remove member");
      showMessage("Member removed", "success");
      fetchFamilies();
    } catch (err: any) {
      showMessage(err.message, "error");
    }
    setRemovingMemberId(null);
  };

  const handleDeleteFamily = async (family: Family) => {
    const parts: string[] = [];
    if (family.childCount > 0) parts.push(`${family.childCount} ${family.childCount === 1 ? "child" : "children"}`);
    if (family.logCount > 0) parts.push(`${family.logCount} activity logs`);
    if (family.memoryCount > 0) parts.push(`${family.memoryCount} memories`);
    const detail = parts.length > 0 ? ` This will permanently delete ${parts.join(", ")}, and all associated data.` : "";
    if (!window.confirm(`Delete "${family.name}"?${detail} This cannot be undone.`)) return;

    setDeletingFamilyId(family.id);
    try {
      const res = await fetch(`/api/admin/families/${family.id}`, {
        method: "DELETE",
        credentials: "include",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to delete family");
      showMessage(`"${family.name}" and all data deleted`, "success");
      setFamilies(prev => prev.filter(f => f.id !== family.id));
    } catch (err: any) {
      showMessage(err.message, "error");
    }
    setDeletingFamilyId(null);
  };

  const handleTierChange = async (familyId: string, currentTier: string) => {
    const newTier = currentTier === "pro" ? "free" : "pro";
    const label = newTier === "pro" ? "Upgrade to Pro?" : "Downgrade to Free?";
    if (!window.confirm(label)) return;
    setTierChanging(familyId);
    try {
      const res = await fetch("/api/admin/families", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          familyId,
          tier: newTier,
          maxChildren: newTier === "pro" ? 10 : 1,
          maxMembers: newTier === "pro" ? 10 : 2,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to update tier");
      showMessage(`Family moved to ${newTier}`, "success");
      fetchFamilies();
    } catch (err: any) {
      showMessage(err.message, "error");
    }
    setTierChanging(null);
  };

  const updateMemberForm = (familyId: string, field: "email" | "role", value: string) => {
    setMemberForms(prev => {
      const current = prev[familyId] || { email: "", role: "caregiver" };
      return { ...prev, [familyId]: { ...current, [field]: value } };
    });
  };

  const filteredFamilies = families.filter((f) => {
    const matchesSearch = f.name.toLowerCase().includes(search.toLowerCase());
    const isOrphaned = f.userCount === 0;
    if (tierFilter === "orphaned") return matchesSearch && isOrphaned;
    const matchesTier = tierFilter === "all" || f.tier === tierFilter;
    return matchesSearch && matchesTier;
  });

  const exportCSV = () => {
    const headers = ["Name", "Tier", "Users", "Children", "Logs", "Max Children", "Max Members", "Created"];
    const rows = filteredFamilies.map((f) => [
      f.name, f.tier, f.userCount, f.childCount, f.logCount, f.maxChildren, f.maxMembers, f.createdAt,
    ]);
    const csv = [headers, ...rows].map((row) => row.join(",")).join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "families.csv";
    a.click();
  };

  if (loading) return <div className="p-6 text-white">Loading...</div>;

  const proCount = families.filter(f => f.tier === "pro").length;
  const freeCount = families.filter(f => f.tier !== "pro").length;
  const orphanedCount = families.filter(f => f.userCount === 0).length;

  return (
    <div className="p-6 space-y-4">
      {error && (
        <div className="bg-red-500/15 border border-red-500/30 text-red-400 px-4 py-3 rounded-xl text-sm flex justify-between">
          <span>⚠ {error}</span>
          <button onClick={() => setError(null)} className="ml-4 opacity-60 hover:opacity-100">✕</button>
        </div>
      )}
      {success && (
        <div className="bg-emerald-500/15 border border-emerald-500/30 text-emerald-400 px-4 py-3 rounded-xl text-sm">
          ✓ {success}
        </div>
      )}

      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">Families</h1>
          <p className="text-gray-400">
            {families.length} total · <span className="text-rose-400">{proCount} Pro</span> · <span className="text-gray-500">{freeCount} Free</span>
            {orphanedCount > 0 && <> · <span className="text-amber-400">{orphanedCount} Orphaned</span></>}
          </p>
        </div>
        <div className="flex gap-2">
          <Button onClick={() => setShowNewFamily(!showNewFamily)}>+ New Family</Button>
          <Button variant="secondary" onClick={exportCSV}>Export CSV</Button>
        </div>
      </div>

      {/* New family inline form */}
      {showNewFamily && (
        <div className="bg-gray-800 border border-gray-700 p-4 rounded-xl flex gap-2 items-end">
          <div className="flex-1">
            <label className="text-xs text-gray-400 block mb-1">Family Name *</label>
            <Input
              type="text"
              placeholder="e.g. The Smith Family"
              value={newFamilyName}
              onChange={(e) => setNewFamilyName(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") handleCreateFamily(); }}
              autoFocus
            />
          </div>
          <Button onClick={handleCreateFamily} loading={creatingFamily} disabled={!newFamilyName.trim()}>
            Create
          </Button>
          <Button variant="secondary" onClick={() => { setShowNewFamily(false); setNewFamilyName(""); }}>
            Cancel
          </Button>
        </div>
      )}

      {/* Filters */}
      <div className="flex gap-3">
        <Input
          type="text"
          placeholder="Search families…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="flex-1"
        />
        <Select value={tierFilter} onChange={(e) => setTierFilter(e.target.value)}>
          <option value="all">All Tiers</option>
          <option value="free">Free</option>
          <option value="pro">Pro</option>
          <option value="orphaned">Orphaned (0 members)</option>
        </Select>
      </div>

      {/* Table */}
      <div className="bg-gray-800 rounded-xl overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-700">
            <tr>
              <th className="px-4 py-3 text-left text-sm font-medium">Family</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Tier</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Members</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Children</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Logs</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Limits</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Created</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-700">
            {filteredFamilies.map((family) => {
              const memberForm = memberForms[family.id] || { email: "", role: "caregiver" };
              const isOrphaned = family.userCount === 0;
              return (
                <>
                  <tr key={family.id} className={`hover:bg-gray-750 ${isOrphaned ? "bg-amber-950/20" : ""}`}>
                    <td className="px-4 py-3">
                      <div className="font-medium">{family.name}</div>
                      <div className="text-xs text-gray-600 font-mono">{family.id.slice(0, 8)}…</div>
                      {isOrphaned && (
                        <span className="text-xs text-amber-400 bg-amber-400/10 px-1.5 py-0.5 rounded mt-0.5 inline-block">
                          No members
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <Badge variant={family.tier === "pro" ? "rose" : "default"}>{family.tier}</Badge>
                    </td>
                    <td className="px-4 py-3">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setShowMembers(showMembers === family.id ? null : family.id)}
                      >
                        {family.userCount} {showMembers === family.id ? "▲" : "▼"}
                      </Button>
                    </td>
                    <td className="px-4 py-3 text-gray-300">{family.childCount}</td>
                    <td className="px-4 py-3 text-sm text-gray-400">{family.logCount}</td>
                    <td className="px-4 py-3 text-sm text-gray-500">
                      {family.maxChildren} kids · {family.maxMembers} members
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-400">
                      {family.createdAt?.slice(0, 10)}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-1.5">
                        <Button
                          variant={family.tier === "pro" ? "secondary" : "primary"}
                          size="sm"
                          onClick={() => handleTierChange(family.id, family.tier)}
                          loading={tierChanging === family.id}
                          disabled={!!tierChanging || !!deletingFamilyId}
                        >
                          {family.tier === "pro" ? "↓ Free" : "↑ Pro"}
                        </Button>
                        {isOrphaned && (
                          <Button
                            variant="danger"
                            size="sm"
                            onClick={() => handleDeleteFamily(family)}
                            loading={deletingFamilyId === family.id}
                            disabled={!!deletingFamilyId || !!tierChanging}
                          >
                            Delete
                          </Button>
                        )}
                      </div>
                    </td>
                  </tr>

                  {showMembers === family.id && (
                    <tr key={`${family.id}-members`}>
                      <td colSpan={8} className="bg-gray-900 px-6 py-4">
                        <div className="space-y-3">
                          <div className="text-xs text-gray-500 font-semibold uppercase">Members</div>

                          {/* Add member form */}
                          <div className="flex gap-2 items-center">
                            <Input
                              type="email"
                              placeholder="Email address"
                              value={memberForm.email}
                              onChange={(e) => updateMemberForm(family.id, "email", e.target.value)}
                              className="flex-1 max-w-xs"
                              onKeyDown={(e) => { if (e.key === "Enter") handleAddMember(family.id); }}
                            />
                            <Select
                              value={memberForm.role}
                              onChange={(e) => updateMemberForm(family.id, "role", e.target.value)}
                            >
                              <option value="caregiver">Caregiver</option>
                              <option value="owner">Owner</option>
                            </Select>
                            <Button
                              size="sm"
                              onClick={() => handleAddMember(family.id)}
                              disabled={!memberForm.email}
                            >
                              Add
                            </Button>
                          </div>

                          {/* Member list */}
                          <div className="space-y-1">
                            {(family.members || []).map((m) => (
                              <div key={m.id} className="flex justify-between items-center bg-gray-800 px-3 py-2 rounded-lg">
                                <div>
                                  <span className="text-sm">{m.email}</span>
                                  <span className="ml-2 text-xs text-gray-500 bg-gray-700 px-1.5 py-0.5 rounded">{m.role}</span>
                                </div>
                                <Button
                                  variant="danger"
                                  size="sm"
                                  loading={removingMemberId === m.id}
                                  disabled={!!removingMemberId}
                                  onClick={() => handleRemoveMember(m.id)}
                                >
                                  Remove
                                </Button>
                              </div>
                            ))}
                            {(family.members || []).length === 0 && (
                              <div className="text-gray-600 text-sm py-1">No members yet</div>
                            )}
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </>
              );
            })}
          </tbody>
        </table>
        {filteredFamilies.length === 0 && (
          <div className="p-8 text-center text-gray-500">No families found</div>
        )}
      </div>
    </div>
  );
}
