'use client';

import { useEffect, useMemo, useState } from 'react';
import type { FlightFilters, SortKey } from '@/services/flights/filterSort';
import type { FlightData } from '../types';
import { useSmartFilters, type SmartFiltersBanner, type SmartFiltersSnapshot } from '@/services/flights/smartFilters/useSmartFilters';
import type { OpenSearchEditDetail } from '../searchEditEvents';
import '../flight-filter-chips.css';
import './smart-filters-card.css';

const MAX_PROMPT_LEN = 200;
const PLACEHOLDER_ROTATE_MS = 3500;
const PLACEHOLDERS = [
  'Try "non-stop under $700"',
  'Try "morning departures with checked bag"',
  'Try "refundable fares only"',
  'Try "cheapest, arriving before noon"',
];

interface SmartFiltersCardProps {
  /** The unfiltered offers for whichever leg/step this card is scoped to. */
  offers: FlightData[];
  filters: FlightFilters;
  activeSort: SortKey;
  tripType: 'oneway' | 'roundtrip' | 'multicity';
  origin: string;
  destination: string;
  departDate: string;
  returnDate?: string;
  currency: string;
  /** Multi-city only. */
  legIndex?: number;
  /** Round-trip only: 0 = outbound, 1 = return. */
  step?: 0 | 1;
  /** Round-trip only: the prompt named "return"/"outbound" explicitly — the
   *  parent decides what that means for its own step state. Omitted, this
   *  card has no opinion on legs beyond passing the hint up. */
  onLegHint?: (leg: 'outbound' | 'return' | 'current') => void;
}

/**
 * Natural-language flight filtering (LEIS-924) — the filter panel's own
 * first section (mounted by FlightFilterSidebar, both its `sidebar` and
 * `sheet` variants), not a separate card: it draws no white/shadow/rounded
 * chrome of its own, just a bottom border like every other section in that
 * panel, so it's part of the same sticky/scrollable box as "Stops"/
 * "Airlines"/etc. rather than a sibling the page scrolls past on its own.
 * The condensed mobile bar (SmartFiltersPinned) shares the same
 * submit/apply/undo logic via useSmartFilters and only differs in how little
 * chrome it draws.
 *
 * Every path — a typed prompt, a chip click, the fast-path parser, the LLM
 * fallback — funnels into the exact same `dispatch(setFilters(patch))` every
 * manual checkbox already uses, so an AI-set filter is indistinguishable from
 * a manually-clicked one everywhere downstream (Applied Filters chips, the
 * sidebar's own controls, the URL, the Back button).
 */
export default function SmartFiltersCard({
  offers,
  filters,
  activeSort,
  tripType,
  origin,
  destination,
  departDate,
  returnDate,
  currency,
  legIndex,
  step,
  onLegHint,
}: SmartFiltersCardProps) {
  const inputId = useMemo(() => `smart-filters-input-${Math.random().toString(36).slice(2, 8)}`, []);
  const [placeholderIdx, setPlaceholderIdx] = useState(0);
  const [focused, setFocused] = useState(false);

  const { text, setText, loading, banner, chips, handleSubmit, handleUndo, handleUpdateSearch } = useSmartFilters({
    offers,
    filters,
    activeSort,
    tripType,
    origin,
    destination,
    departDate,
    returnDate,
    currency,
    legIndex,
    step,
    onLegHint,
  });

  useEffect(() => {
    if (focused || text) return;
    const timer = setInterval(() => setPlaceholderIdx((i) => (i + 1) % PLACEHOLDERS.length), PLACEHOLDER_ROTATE_MS);
    return () => clearInterval(timer);
  }, [focused, text]);

  return (
    <div className="smart-filters-card">
      <div className="smart-filters-card__head">
        <SparkleIcon />
        <div>
          <label htmlFor={inputId} className="smart-filters-card__label">Smart Filters</label>
          <p className="smart-filters-card__subtitle">Powered by leisure.com AI</p>
        </div>
      </div>

      <form
        className="smart-filters-card__form"
        onSubmit={(e) => {
          e.preventDefault();
          void handleSubmit(text);
        }}
      >
        <input
          id={inputId}
          type="text"
          className="form-control form-control-sm text-sm smart-filters-card__input"
          value={text}
          maxLength={MAX_PROMPT_LEN}
          placeholder={PLACEHOLDERS[placeholderIdx]}
          disabled={loading}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onChange={(e) => setText(e.target.value)}
          // Matches the airline-search box: .filterDetails input.form-control:focus
          // swaps the background otherwise, so this field would look different
          // at rest vs. focused.
          style={{ backgroundColor: '#f3f4f6', border: '1px solid #d9dde2' }}
        />
        <button
          type="submit"
          className="smart-filters-card__send"
          disabled={loading || !text.trim()}
          aria-label="Apply filter request"
        >
          {loading ? <SpinnerIcon /> : <SendIcon />}
        </button>
      </form>

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

      {!loading && banner ? (
        <BannerView banner={banner} onUndo={handleUndo} onUpdateSearch={handleUpdateSearch} />
      ) : null}

      {chips.length > 0 && (
        <div className="smart-filters-card__chips">
          {chips.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>
  );
}

function BannerView({
  banner,
  onUndo,
  onUpdateSearch,
}: {
  banner: SmartFiltersBanner;
  onUndo: (snapshot: SmartFiltersSnapshot) => void;
  onUpdateSearch: (detail: OpenSearchEditDetail) => void;
}) {
  if (banner.kind === 'applied') {
    return (
      <div className="smart-filters-card__status smart-filters-card__status--applied" role="status" aria-live="polite">
        Applied <strong>{banner.appliedLabels.join(', ')}</strong> — {banner.matchCount} flight{banner.matchCount === 1 ? '' : 's'} match.
        {banner.unsupported.length > 0 ? (
          <span className="smart-filters-card__unsupported"> Couldn&apos;t apply {banner.unsupported.join(', ')} — no filter for that yet.</span>
        ) : null}
        <button type="button" className="smart-filters-card__undo" onClick={() => onUndo(banner.undoSnapshot)}>
          Undo
        </button>
      </div>
    );
  }
  if (banner.kind === 'unsupported-only') {
    return (
      <div className="smart-filters-card__status smart-filters-card__status--warn" role="status" aria-live="polite">
        Couldn&apos;t apply {banner.unsupported.join(', ')} — no filter for that yet.
      </div>
    );
  }
  if (banner.kind === 'out-of-scope') {
    return (
      <div className="smart-filters-card__status" role="status" aria-live="polite">
        That sounds like a question, not a filter — opening the travel assistant…
      </div>
    );
  }
  if (banner.kind === 'search-change') {
    return (
      <div className="smart-filters-card__status" role="status" aria-live="polite">
        This changes your search ({banner.description}).
        <button
          type="button"
          className="smart-filters-card__undo"
          onClick={() => onUpdateSearch(banner.editDetail)}
        >
          Update search
        </button>
      </div>
    );
  }
  return (
    <div className="smart-filters-card__status smart-filters-card__status--warn" role="status" aria-live="polite">
      That took too long to understand — your filters are unchanged. Try rephrasing, or use the filters below.
    </div>
  );
}

function SparkleIcon() {
  return (
    <svg width={16} height={16} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M12 2l1.8 5.2L19 9l-5.2 1.8L12 16l-1.8-5.2L5 9l5.2-1.8L12 2z" fill="currentColor" />
      <path d="M19 15l.9 2.1L22 18l-2.1.9L19 21l-.9-2.1L16 18l2.1-.9L19 15z" fill="currentColor" />
    </svg>
  );
}

function SendIcon() {
  return (
    <svg width={16} height={16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M22 2 11 13" />
      <path d="M22 2 15 22l-4-9-9-4 20-7z" />
    </svg>
  );
}

function SpinnerIcon() {
  return (
    <svg className="smart-filters-card__spinner" width={16} height={16} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2" opacity="0.25" />
      <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}
