import React, { useState } from 'react';
import { Search } from 'lucide-react';

interface Props {
  onSearch: (imo: string) => void;
}

export function YachtSearch({ onSearch }: Props) {
  const [imo, setImo] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const cleanedImo = imo.trim().replace(/[^0-9]/g, '');
    if (cleanedImo.length === 7) {
      onSearch(cleanedImo);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/[^0-9]/g, '').slice(0, 7);
    setImo(value);
  };

  return (
    <form onSubmit={handleSubmit} className="w-full max-w-md">
      <div className="relative">
        <input
          type="text"
          value={imo}
          onChange={handleChange}
          placeholder="Enter Vessel IMO Number (7 digits)"
          pattern="[0-9]{7}"
          maxLength={7}
          className="w-full px-4 py-2 text-gray-700 bg-white border rounded-lg focus:border-blue-500 focus:outline-none"
        />
        <button
          type="submit"
          disabled={imo.length !== 7}
          className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-600 hover:text-blue-500 disabled:opacity-50 disabled:hover:text-gray-600"
        >
          <Search size={20} />
        </button>
      </div>
      {imo.length > 0 && imo.length < 7 && (
        <p className="mt-2 text-sm text-gray-600">IMO number must be 7 digits</p>
      )}
    </form>
  );
}