"use client";

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

interface Child {
  id: string;
  name: string;
  birthDate: string;
  familyId: string;
  familyName: string;
  age: string;
}

export default function AdminChildren() {
  const [children, setChildren] = useState<Child[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

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

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

  const fetchChildren = async () => {
    try {
      const res = await fetch("/api/admin/children", { credentials: "include" });
      const data = await res.json();
      setChildren(data.children || []);
    } catch (err) {
      console.error("Failed to fetch children:", err);
    }
    setLoading(false);
  };

  const handleDeleteChild = async (child: Child) => {
    // Fetch counts for the confirmation message
    let confirmMsg = `Delete ${child.name}? This will permanently delete all their logs, growth records, vaccinations, and associated data. This cannot be undone.`;
    try {
      const res = await fetch(`/api/admin/children/${child.id}`, { credentials: "include" });
      if (res.ok) {
        const counts = await res.json();
        const total =
          Number(counts.feed_count || 0) +
          Number(counts.diaper_count || 0) +
          Number(counts.sleep_count || 0);
        const parts: string[] = [];
        if (total > 0) parts.push(`${total} activity logs`);
        if (Number(counts.growth_count || 0) > 0) parts.push(`${counts.growth_count} growth records`);
        if (Number(counts.vaccination_count || 0) > 0) parts.push(`${counts.vaccination_count} vaccination records`);
        if (parts.length > 0) {
          confirmMsg = `Delete ${child.name}? This will permanently delete ${parts.join(", ")}, and all associated data. This cannot be undone.`;
        }
      }
    } catch {}

    if (!window.confirm(confirmMsg)) return;

    setDeletingId(child.id);
    try {
      const res = await fetch(`/api/admin/children/${child.id}`, {
        method: "DELETE",
        credentials: "include",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Delete failed");
      showMessage(`${child.name} and all data deleted`, "success");
      setChildren(prev => prev.filter(c => c.id !== child.id));
    } catch (err: any) {
      showMessage(err.message, "error");
    }
    setDeletingId(null);
  };

  const filteredChildren = children.filter((c) =>
    c.name.toLowerCase().includes(search.toLowerCase()) ||
    (c.familyName || "").toLowerCase().includes(search.toLowerCase())
  );

  const exportCSV = () => {
    const headers = ["Name", "Birth Date", "Family", "Age"];
    const rows = filteredChildren.map((c) => [c.name, c.birthDate, c.familyName, c.age]);
    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 = "children.csv";
    a.click();
  };

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

  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 items-center">
          <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">Children</h1>
          <p className="text-gray-400">{children.length} total children</p>
        </div>
        <Button variant="secondary" onClick={exportCSV}>Export CSV</Button>
      </div>

      <Input
        type="text"
        placeholder="Search children..."
        value={search}
        onChange={(e) => setSearch(e.target.value)}
      />

      <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">Child</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Birth Date</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Age</th>
              <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">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-700">
            {filteredChildren.map((child) => (
              <tr key={child.id} className="hover:bg-gray-750">
                <td className="px-4 py-3 font-medium">{child.name}</td>
                <td className="px-4 py-3 text-sm text-gray-400">
                  {child.birthDate?.slice(0, 10)}
                </td>
                <td className="px-4 py-3 text-sm text-gray-400">{child.age}</td>
                <td className="px-4 py-3">{child.familyName}</td>
                <td className="px-4 py-3">
                  <Button
                    variant="danger"
                    size="sm"
                    loading={deletingId === child.id}
                    disabled={!!deletingId}
                    onClick={() => handleDeleteChild(child)}
                  >
                    Delete
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {filteredChildren.length === 0 && (
          <div className="p-8 text-center text-gray-500">No children found</div>
        )}
      </div>
    </div>
  );
}
