"use client";

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

interface User {
  id: string;
  email: string;
  name: string;
  phone?: string | null;
  familyId: string;
  familyName: string;
  createdAt: string;
  memberId?: string;
  hasPassword?: boolean;
}

interface Family {
  id: string;
  name: string;
}

export default function AdminUsers() {
  const [users, setUsers] = useState<User[]>([]);
  const [families, setFamilies] = useState<Family[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [showAdd, setShowAdd] = useState(false);
  const [showPassword, setShowPassword] = useState<string | null>(null);
  const [passwordValue, setPasswordValue] = useState("");
  const [newUser, setNewUser] = useState({ email: "", name: "", familyId: "", role: "caregiver" });
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  useEffect(() => {
    fetchUsers();
    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 fetchUsers = async () => {
    try {
      const res = await fetch("/api/admin/users", { credentials: "include" });
      const data = await res.json();
      if (data.error) throw new Error(data.error);
      setUsers(data.users || []);
    } catch (err: any) {
      showMessage(err.message || "Failed to load users", "error");
    }
    setLoading(false);
  };

  const fetchFamilies = async () => {
    try {
      const res = await fetch("/api/admin/families", { credentials: "include" });
      const data = await res.json();
      setFamilies(data.families || []);
    } catch {}
  };

  const handleAddUser = async () => {
    if (!newUser.email) return;
    try {
      const res = await fetch("/api/admin/users", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify(newUser),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create user");
      showMessage("User created", "success");
      setShowAdd(false);
      setNewUser({ email: "", name: "", familyId: "", role: "caregiver" });
      fetchUsers();
    } catch (err: any) {
      showMessage(err.message, "error");
    }
  };

  const handleDeleteUser = async (userId: string) => {
    if (!window.confirm("Delete this user permanently? This cannot be undone.")) return;
    setDeletingId(userId);
    try {
      const res = await fetch(`/api/admin/users?userId=${userId}`, {
        method: "DELETE",
        credentials: "include",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Delete failed");
      showMessage("User deleted", "success");
      setUsers(prev => prev.filter(u => u.id !== userId));
    } catch (err: any) {
      showMessage(err.message, "error");
    }
    setDeletingId(null);
  };

  const handleSetPassword = async (userId: string, password: string) => {
    if (!password) return;
    try {
      const res = await fetch("/api/admin/users", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ userId, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to set password");
      showMessage("Password updated", "success");
      setShowPassword(null);
      setPasswordValue("");
      fetchUsers();
    } catch (err: any) {
      showMessage(err.message, "error");
    }
  };

  const filteredUsers = users.filter((u) =>
    u.email.toLowerCase().includes(search.toLowerCase()) ||
    (u.name || "").toLowerCase().includes(search.toLowerCase()) ||
    (u.phone || "").includes(search)
  );

  const exportCSV = () => {
    const headers = ["Email", "Name", "Phone", "Family", "Created"];
    const rows = filteredUsers.map((u) => [u.email, u.name, u.phone || "", u.familyName, u.createdAt]);
    // Quote each cell so commas/empties don't shift columns
    const csv = [headers, ...rows]
      .map((row) => row.map((cell) => `"${String(cell ?? "").replace(/"/g, '""')}"`).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 = "users.csv";
    a.click();
  };

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

  return (
    <div className="p-6 space-y-4">
      {/* Toast notifications */}
      {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">Users</h1>
          <p className="text-gray-400">{users.length} total users</p>
        </div>
        <div className="flex gap-2">
          <Button variant="secondary" onClick={exportCSV}>Export CSV</Button>
          <Button onClick={() => setShowAdd(!showAdd)}>+ Add User</Button>
        </div>
      </div>

      {showAdd && (
        <div className="bg-gray-800 p-4 rounded-xl flex gap-2 flex-wrap items-end border border-gray-700">
          <div className="flex-1 min-w-[200px]">
            <label className="text-xs text-gray-400 block mb-1">Email *</label>
            <Input
              type="email"
              placeholder="user@example.com"
              value={newUser.email}
              onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
            />
          </div>
          <div>
            <label className="text-xs text-gray-400 block mb-1">Name</label>
            <Input
              type="text"
              placeholder="Display name"
              value={newUser.name}
              onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
            />
          </div>
          <div>
            <label className="text-xs text-gray-400 block mb-1">Family</label>
            <Select
              value={newUser.familyId}
              onChange={(e) => setNewUser({ ...newUser, familyId: e.target.value })}
            >
              <option value="">No family</option>
              {families.map((f) => (
                <option key={f.id} value={f.id}>{f.name}</option>
              ))}
            </Select>
          </div>
          <div className="flex gap-2">
            <Button onClick={handleAddUser}>Create</Button>
            <Button variant="secondary" onClick={() => setShowAdd(false)}>Cancel</Button>
          </div>
        </div>
      )}

      <Input
        type="text"
        placeholder="Search by name, email or phone…"
        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">User</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Phone</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">Password</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Joined</th>
              <th className="px-4 py-3 text-left text-sm font-medium">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-700">
            {filteredUsers.map((user) => (
              <tr key={user.id} className="hover:bg-gray-750">
                <td className="px-4 py-3">
                  <div className="font-medium">{user.name || user.email}</div>
                  <div className="text-xs text-gray-500">{user.email}</div>
                </td>
                <td className="px-4 py-3 text-sm">
                  {user.phone
                    ? <a href={`tel:${user.phone}`} className="text-gray-300 hover:text-rose-400">{user.phone}</a>
                    : <span className="text-gray-600">—</span>}
                </td>
                <td className="px-4 py-3 text-gray-300">{user.familyName || <span className="text-gray-600">—</span>}</td>
                <td className="px-4 py-3">
                  <button
                    onClick={() => setShowPassword(user.id)}
                    className={`text-sm hover:underline ${user.hasPassword ? "text-emerald-400" : "text-amber-400"}`}
                  >
                    {user.hasPassword ? "✓ Set" : "Not set"}
                  </button>
                </td>
                <td className="px-4 py-3 text-sm text-gray-400">
                  {user.createdAt?.slice(0, 10)}
                </td>
                <td className="px-4 py-3">
                  <Button
                    variant="danger"
                    size="sm"
                    loading={deletingId === user.id}
                    disabled={!!deletingId}
                    onClick={() => handleDeleteUser(user.id)}
                  >
                    Delete
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {filteredUsers.length === 0 && (
          <div className="p-8 text-center text-gray-500">No users found</div>
        )}
      </div>

      <Modal
        open={!!showPassword}
        onClose={() => { setShowPassword(null); setPasswordValue(""); }}
        title="Set Password"
      >
        <div className="space-y-4">
          <Input
            type="password"
            placeholder="Enter new password"
            value={passwordValue}
            onChange={(e) => setPasswordValue(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && showPassword) handleSetPassword(showPassword, passwordValue);
            }}
          />
          <div className="flex gap-2">
            <Button fullWidth onClick={() => showPassword && handleSetPassword(showPassword, passwordValue)}>
              Set Password
            </Button>
            <Button variant="secondary" fullWidth onClick={() => { setShowPassword(null); setPasswordValue(""); }}>
              Cancel
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
