import { useCallback, useEffect, useState } from "react";
import { api } from "../lib/api";

type User = {
  id: string;
  name: string;
  email: string;
  role: string | null;
  email_verified: boolean;
  created_at: string;
  rides: number;
};

const ROLES = ["rider", "driver", "owner"];

export default function Users() {
  const [users, setUsers] = useState<User[]>([]);
  const [query, setQuery] = useState("");
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async (q: string) => {
    try {
      const res = await api<{ data: User[] }>(
        `/admin/users${q ? `?q=${encodeURIComponent(q)}` : ""}`,
      );
      setUsers(res.data);
      setError(null);
    } catch (e) {
      setError((e as Error).message);
    }
  }, []);

  useEffect(() => {
    load("");
  }, [load]);

  const setRole = async (id: string, role: string) => {
    try {
      await api(`/admin/users/${id}`, {
        method: "PATCH",
        body: JSON.stringify({ role }),
      });
      await load(query);
    } catch (e) {
      setError((e as Error).message);
    }
  };

  const toggleVerified = async (u: User) => {
    try {
      await api(`/admin/users/${u.id}`, {
        method: "PATCH",
        body: JSON.stringify({ email_verified: !u.email_verified }),
      });
      await load(query);
    } catch (e) {
      setError((e as Error).message);
    }
  };

  const remove = async (u: User) => {
    if (
      !window.confirm(
        `Delete ${u.name} (${u.email})? This also removes their rides and cannot be undone.`,
      )
    ) {
      return;
    }

    try {
      await api(`/admin/users/${u.id}`, { method: "DELETE" });
      await load(query);
    } catch (e) {
      setError((e as Error).message);
    }
  };

  return (
    <>
      <h2>Users</h2>
      <div className="toolbar">
        <input
          placeholder="Search name or email…"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && load(query)}
        />
        <button className="secondary" onClick={() => load(query)}>
          Search
        </button>
      </div>
      {error && <div className="error">{error}</div>}
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Role</th>
            <th>Verified</th>
            <th>Rides</th>
            <th>Joined</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {users.map((u) => (
            <tr key={u.id}>
              <td>{u.name}</td>
              <td>{u.email}</td>
              <td>
                <select
                  value={u.role ?? ""}
                  onChange={(e) => setRole(u.id, e.target.value)}
                >
                  <option value="">— none —</option>
                  {ROLES.map((r) => (
                    <option key={r} value={r}>
                      {r}
                    </option>
                  ))}
                </select>
              </td>
              <td>
                <span className={`badge ${u.email_verified ? "paid" : "unpaid"}`}>
                  {u.email_verified ? "yes" : "no"}
                </span>
              </td>
              <td>{u.rides}</td>
              <td>{new Date(u.created_at).toLocaleDateString()}</td>
              <td className="row-actions">
                <button className="secondary" onClick={() => toggleVerified(u)}>
                  {u.email_verified ? "Unverify" : "Verify"}
                </button>
                <button className="danger" onClick={() => remove(u)}>
                  Delete
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}
