'use client';

import { useMemo } from 'react';
import type { FlightFilters, SortKey } from '@/services/flights/filterSort';
import type { FlightData } from '../types';
import { useSmartFilters } from '@/services/flights/smartFilters/useSmartFilters';
import '../flight-filter-chips.css';
import './smart-filters-pinned.css';

interface SmartFiltersPinnedProps {
  offers: FlightData[];
  filters: FlightFilters;
  activeSort: SortKey;
  tripType: 'oneway' | 'roundtrip' | 'multicity';
  origin: string;
  destination: string;
  departDate: string;
  returnDate?: string;
  currency: string;
  legIndex?: number;
  step?: 0 | 1;
  onLegHint?: (leg: 'outbound' | 'return' | 'current') => void;
}

/**
 * The phone equivalent of SmartFiltersCard — input plus chips only, pinned
 * `d-lg-none` above FlightMobileFilterBar, no card chrome or rotating
 * placeholder. Shares useSmartFilters with the full card rather than a
 * second parser/apply/undo implementation; this only differs in how little
 * it draws. Undo lives in the one-line result banner itself, since there is
 * no room here for a second control.
 */
export default function SmartFiltersPinned({
  offers,
  filters,
  activeSort,
  tripType,
  origin,
  destination,
  departDate,
  returnDate,
  currency,
  legIndex,
  step,
  onLegHint,
}: SmartFiltersPinnedProps) {
  const inputId = useMemo(() => `smart-filters-pinned-${Math.random().toString(36).slice(2, 8)}`, []);
  const { text, setText, loading, banner, chips, handleSubmit, handleUndo, handleUpdateSearch } = useSmartFilters({
    offers,
    filters,
    activeSort,
    tripType,
    origin,
    destination,
    departDate,
    returnDate,
    currency,
    legIndex,
    step,
    onLegHint,
  });

  return (
    <div className="smart-filters-pinned d-lg-none">
      <form
        className="smart-filters-pinned__form"
        onSubmit={(e) => {
          e.preventDefault();
          void handleSubmit(text);
        }}
      >
        <label htmlFor={inputId} className="visually-hidden">Smart Filters — describe what you want</label>
        <span className="smart-filters-pinned__icon" aria-hidden="true">
          <svg width={14} height={14} viewBox="0 0 24 24" fill="none">
            <path d="M12 2l1.8 5.2L19 9l-5.2 1.8L12 16l-1.8-5.2L5 9l5.2-1.8L12 2z" fill="currentColor" />
          </svg>
        </span>
        <input
          id={inputId}
          type="text"
          className="smart-filters-pinned__input"
          value={text}
          maxLength={200}
          placeholder="Try “non-stop under $700”"
          disabled={loading}
          onChange={(e) => setText(e.target.value)}
        />
        <button
          type="submit"
          className="smart-filters-pinned__send"
          disabled={loading || !text.trim()}
          aria-label="Apply filter request"
        >
          {loading ? '…' : '→'}
        </button>
      </form>

      {loading && (
        <div className="smart-filters-pinned__status" role="status" aria-live="polite">
          Understanding your request…
        </div>
      )}

      {!loading && banner ? (
        <div className="smart-filters-pinned__status" role="status" aria-live="polite">
          {banner.kind === 'applied' && (
            <>
              Applied <strong>{banner.appliedLabels.join(', ')}</strong> — {banner.matchCount} match
              {banner.matchCount === 1 ? '' : 'es'}.
              <button type="button" className="smart-filters-pinned__undo" onClick={() => handleUndo(banner.undoSnapshot)}>
                Undo
              </button>
            </>
          )}
          {banner.kind === 'unsupported-only' && <>Couldn&apos;t apply {banner.unsupported.join(', ')} yet.</>}
          {banner.kind === 'out-of-scope' && <>Opening the travel assistant…</>}
          {banner.kind === 'search-change' && (
            <>
              This changes your search ({banner.description}).
              <button
                type="button"
                className="smart-filters-pinned__undo"
                onClick={() => handleUpdateSearch(banner.editDetail)}
              >
                Update search
              </button>
            </>
          )}
          {banner.kind === 'error' && <>That took too long — filters unchanged.</>}
        </div>
      ) : null}

      {chips.length > 0 && (
        <div className="smart-filters-pinned__chips">
          {chips.slice(0, 4).map((chip) => (
            <button
              key={chip.id}
              type="button"
              className="flights-filter-chip flights-filter-chip--relax"
              disabled={loading}
              onClick={() => void handleSubmit(chip.prompt)}
            >
              {chip.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
