'use client';

import { Search } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useId, useState, type FormEvent } from 'react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';

/** Pill tracking search, same design as the /track entry page. */
export function TrackSearchForm({ initialValue = '', className }: { initialValue?: string; className?: string }) {
  const router = useRouter();
  const id = useId();
  const [trackingNumber, setTrackingNumber] = useState(initialValue);
  const [error, setError] = useState<string | undefined>(undefined);

  const onSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const value = trackingNumber.trim();
    if (value.length === 0) {
      setError('Enter a tracking number.');
      return;
    }
    router.push(`/track/${encodeURIComponent(value)}`);
  };

  return (
    <form className={cn('w-full max-w-[640px]', className)} onSubmit={onSubmit} noValidate>
      <label htmlFor={id} className="sr-only">
        Tracking number
      </label>
      <div
        className={cn(
          'flex h-[60px] items-center gap-2 rounded-pill border border-border bg-surface pl-2 pr-1.5 shadow-md transition-[border-color,box-shadow] duration-180 focus-within:border-primary focus-within:shadow-glow',
          error !== undefined && 'border-danger focus-within:border-danger',
        )}
      >
        <Search className="ml-3 h-5 w-5 shrink-0 text-muted-foreground" aria-hidden="true" />
        <Input
          id={id}
          value={trackingNumber}
          placeholder="e.g. SHP1042XYZ"
          aria-invalid={error !== undefined}
          aria-describedby={error === undefined ? undefined : `${id}-error`}
          className="h-11 min-w-0 flex-1 border-0 bg-transparent px-2 font-mono tracking-wide shadow-none placeholder:font-sans placeholder:tracking-normal focus-visible:shadow-none"
          onChange={(event) => {
            setTrackingNumber(event.target.value);
            if (error !== undefined) setError(undefined);
          }}
        />
        <Button type="submit" size="lg" className="shrink-0 rounded-pill px-6">
          Track
        </Button>
      </div>
      {error === undefined ? null : (
        <p id={`${id}-error`} role="alert" className="mt-2 text-left text-small text-danger">
          {error}
        </p>
      )}
    </form>
  );
}
