"use client";

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

import { SearchIcon } from "@/components/icons/search";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { searchExplorer } from "@/lib/explorer-mock";

export function ExplorerSearch() {
  const router = useRouter();
  const [q, setQ] = useState("");
  const [error, setError] = useState<string | null>(null);

  function onSubmit(e: FormEvent) {
    e.preventDefault();
    const hit = searchExplorer(q);
    if (hit.kind === "tx") {
      setError(null);
      router.push(`/portal/explorer/tx/${encodeURIComponent(hit.id)}`);
      return;
    }
    if (hit.kind === "block") {
      setError(null);
      router.push(`/portal/explorer/block/${encodeURIComponent(hit.id)}`);
      return;
    }
    setError(
      "No mock match. Try a full or partial tx hash, a block height (e.g. 1284901), or an address from the lists.",
    );
  }

  return (
    <form onSubmit={onSubmit} className="w-full max-w-2xl">
      <div className="flex gap-2">
        <div className="relative flex-1">
          <SearchIcon
            size={16}
            className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
          />
          <Input
            value={q}
            onChange={(e) => {
              setQ(e.target.value);
              if (error) setError(null);
            }}
            placeholder="Search by tx hash, block height, or address…"
            className="h-11 pl-9 font-mono text-sm"
            aria-label="Search explorer"
            autoComplete="off"
          />
        </div>
        <Button type="submit" size="lg" className="h-11 shrink-0 px-5">
          Search
        </Button>
      </div>
      {error ? (
        <p className="mt-2 text-sm text-pending" role="status">
          {error}
        </p>
      ) : (
        <p className="mt-2 text-xs text-muted-foreground">
          Mock data only — try height{" "}
          <button
            type="button"
            className="font-mono text-accent-hover hover:underline"
            onClick={() => setQ("1284901")}
          >
            1284901
          </button>{" "}
          or paste a hash from the tables below.
        </p>
      )}
    </form>
  );
}
