import { useEffect, useState } from 'react';
import { useSearchParams, useNavigate, Link } from 'react-router-dom';
import { Search as SearchIcon, Box, Hash, Wallet, Loader2 } from 'lucide-react';
import { api } from '../lib/api';
import type { SearchResult } from '../lib/types';

export default function Search() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const query = searchParams.get('q') || '';

  const [result, setResult] = useState<SearchResult | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!query.trim()) {
      setResult(null);
      setError(null);
      return;
    }

    const doSearch = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const searchResult = await api.search(query);
        setResult(searchResult);
        // Auto-redirect to the result
        navigate(searchResult.redirectUrl, { replace: true });
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Search failed');
        setResult(null);
      } finally {
        setIsLoading(false);
      }
    };

    doSearch();
  }, [query, navigate]);

  const getIcon = (type: string) => {
    switch (type) {
      case 'block':
        return <Box size={24} className="text-synor-400" />;
      case 'transaction':
        return <Hash size={24} className="text-synor-400" />;
      case 'address':
        return <Wallet size={24} className="text-synor-400" />;
      default:
        return <SearchIcon size={24} className="text-synor-400" />;
    }
  };

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div className="flex items-center gap-3">
        <div className="p-2 rounded-lg bg-synor-900/50">
          <SearchIcon size={24} className="text-synor-400" />
        </div>
        <div>
          <h1 className="text-2xl font-bold">Search</h1>
          {query && (
            <p className="text-sm text-gray-400">
              Searching for "{query}"
            </p>
          )}
        </div>
      </div>

      {!query ? (
        <div className="card p-8 text-center">
          <SearchIcon size={48} className="mx-auto mb-4 text-gray-600" />
          <h2 className="text-xl font-semibold mb-2">Search the blockchain</h2>
          <p className="text-gray-400 mb-6">
            Enter a block hash, transaction ID, or address in the search bar above.
          </p>
          <div className="grid sm:grid-cols-3 gap-4 text-sm">
            <div className="card p-4">
              <Box className="mx-auto mb-2 text-synor-400" />
              <p className="font-medium">Block Hash</p>
              <p className="text-gray-500">64 hex characters</p>
            </div>
            <div className="card p-4">
              <Hash className="mx-auto mb-2 text-synor-400" />
              <p className="font-medium">Transaction ID</p>
              <p className="text-gray-500">64 hex characters</p>
            </div>
            <div className="card p-4">
              <Wallet className="mx-auto mb-2 text-synor-400" />
              <p className="font-medium">Address</p>
              <p className="text-gray-500">Starts with synor1</p>
            </div>
          </div>
        </div>
      ) : isLoading ? (
        <div className="card p-8 text-center">
          <Loader2 size={48} className="mx-auto mb-4 text-synor-400 animate-spin" />
          <p className="text-gray-400">Searching...</p>
        </div>
      ) : error ? (
        <div className="card p-8 text-center">
          <SearchIcon size={48} className="mx-auto mb-4 text-gray-600" />
          <h2 className="text-xl font-semibold mb-2 text-red-400">Not Found</h2>
          <p className="text-gray-400 mb-4">{error}</p>
          <p className="text-sm text-gray-500">
            Make sure you've entered a valid block hash, transaction ID, or address.
          </p>
        </div>
      ) : result ? (
        <div className="card p-6">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-lg bg-synor-900/50">
              {getIcon(result.resultType)}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm text-gray-400 capitalize">
                {result.resultType}
              </p>
              <Link
                to={result.redirectUrl}
                className="text-synor-400 hover:text-synor-300 font-mono text-sm break-all"
              >
                {result.value}
              </Link>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
