"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export function AgencyLinkEscortForm({
  agencyId,
  agencyCityId,
}: {
  agencyId: number;
  agencyCityId: number | null;
}) {
  const router = useRouter();
  const [search, setSearch] = useState("");
  const [results, setResults] = useState<
    { id: number; username: string | null; email: string }[]
  >([]);
  const [searching, setSearching] = useState(false);
  const [message, setMessage] = useState("");

  async function handleSearch() {
    if (!search.trim()) return;
    setSearching(true);
    setMessage("");
    try {
      const res = await fetch(
        `/api/admin/users/export?search=${encodeURIComponent(search)}&limit=10`
      );
      if (res.ok) {
        const data = await res.json();
        const users = (data.users || data || []).filter(
          (u: { user_type: string }) => u.user_type === "escort"
        );
        setResults(users);
        if (users.length === 0) {
          setMessage("No escorts found matching that search");
        }
      }
    } catch {
      setMessage("Search failed");
    } finally {
      setSearching(false);
    }
  }

  async function handleLink(escortId: number) {
    // Placeholder: move escort to same city as agency
    if (!agencyCityId) {
      setMessage("Agency has no city set. Cannot link escorts.");
      return;
    }
    try {
      const res = await fetch(`/api/admin/users/${escortId}/role`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ city_id: agencyCityId }),
      });
      if (res.ok) {
        setMessage(`Escort #${escortId} linked to agency city`);
        router.refresh();
      } else {
        setMessage("Failed to link escort");
      }
    } catch {
      setMessage("Failed to link escort");
    }
  }

  return (
    <div className="space-y-3">
      <div className="flex gap-2">
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleSearch()}
          placeholder="Search by username or email..."
          className="flex-1 bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary"
        />
        <button
          onClick={handleSearch}
          disabled={searching}
          className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg text-sm transition-colors disabled:opacity-50"
        >
          {searching ? "..." : "Search"}
        </button>
      </div>

      {message && (
        <p className="text-text-muted text-sm">{message}</p>
      )}

      {results.length > 0 && (
        <div className="space-y-1">
          {results.map((u) => (
            <div
              key={u.id}
              className="flex items-center justify-between bg-surface-light rounded-lg px-4 py-2"
            >
              <span className="text-sm">
                <span className="font-medium">{u.username || "—"}</span>
                <span className="text-text-muted ml-2">{u.email}</span>
                <span className="text-text-muted ml-2 font-mono text-xs">
                  #{u.id}
                </span>
              </span>
              <button
                onClick={() => handleLink(u.id)}
                className="text-primary hover:text-primary-dark text-sm transition-colors"
              >
                Link
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
