import { useState, useCallback } from 'react';

export default function PostcodeSearch({
  onFlyTo,
}: {
  onFlyTo: (lat: number, lng: number, zoom: number) => void;
}) {
  const [query, setQuery] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      const trimmed = query.trim();
      if (!trimmed) return;

      setError(null);
      setLoading(true);
      try {
        const res = await fetch(
          `https://api.postcodes.io/postcodes/${encodeURIComponent(trimmed)}`
        );
        if (!res.ok) {
          setError('Postcode not found');
          return;
        }
        const json = await res.json();
        if (json.status === 200 && json.result) {
          onFlyTo(json.result.latitude, json.result.longitude, 14);
          setQuery('');
        } else {
          setError('Postcode not found');
        }
      } catch {
        setError('Lookup failed');
      } finally {
        setLoading(false);
      }
    },
    [query, onFlyTo]
  );

  return (
    <form onSubmit={handleSubmit} className="absolute top-3 left-3 z-10 flex flex-col gap-1">
      <div className="flex shadow-lg rounded overflow-hidden">
        <input
          type="text"
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            setError(null);
          }}
          placeholder="Search postcode..."
          className="px-3 py-2 text-sm w-40 border-none outline-none bg-white dark:bg-navy-800 dark:text-warm-100 dark:placeholder-warm-500"
        />
        <button
          type="submit"
          disabled={loading}
          className="px-3 py-2 bg-teal-600 text-white text-sm hover:bg-teal-700 disabled:opacity-50"
        >
          {loading ? '...' : 'Go'}
        </button>
      </div>
      {error && (
        <span className="text-xs text-red-600 dark:text-red-400 bg-white/90 dark:bg-navy-800/90 rounded px-2 py-0.5 shadow">
          {error}
        </span>
      )}
    </form>
  );
}
