"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { FollowButton } from "@/components/social/follow-button";
import { Search } from "lucide-react";

type PersonResult = {
  id: string;
  name: string;
  username: string | null;
  avatarUrl: string | null;
  bio: string | null;
};

export function PeopleSearch() {
  const [q, setQ] = useState("");
  const [results, setResults] = useState<PersonResult[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (q.trim().length < 2) {
      setResults([]);
      return;
    }
    const timeout = setTimeout(async () => {
      setLoading(true);
      try {
        const res = await fetch(`/api/v1/users/search?q=${encodeURIComponent(q.trim())}`);
        if (res.ok) {
          const data = (await res.json()) as { users: PersonResult[] };
          setResults(data.users);
        }
      } finally {
        setLoading(false);
      }
    }, 300);
    return () => clearTimeout(timeout);
  }, [q]);

  return (
    <div className="space-y-4">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Search people by name or username…"
          className="pl-9"
        />
      </div>

      {loading && <p className="text-sm text-muted-foreground">Searching…</p>}

      {!loading && q.trim().length >= 2 && results.length === 0 && (
        <p className="text-sm text-muted-foreground">No one found.</p>
      )}

      <div className="space-y-2">
        {results.map((person) => (
          <div key={person.id} className="flex items-center gap-3 rounded-lg border p-3">
            <Link href={`/u/${person.username}`} className="flex items-center gap-3 flex-1 min-w-0">
              <Avatar className="h-10 w-10 shrink-0">
                {person.avatarUrl && <AvatarImage src={person.avatarUrl} alt={person.name} />}
                <AvatarFallback>{person.name.slice(0, 2).toUpperCase()}</AvatarFallback>
              </Avatar>
              <div className="min-w-0">
                <p className="font-medium text-sm truncate">{person.name}</p>
                <p className="text-xs text-muted-foreground truncate">@{person.username}</p>
              </div>
            </Link>
            {person.username && (
              <FollowButton targetUserId={person.id} targetUsername={person.username} />
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
