import { memo, useState, useCallback, useEffect, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { SpinnerIcon } from '../ui/icons/SpinnerIcon';
import { SparklesIcon } from '../ui/icons/SparklesIcon';
import { ChevronIcon } from '../ui/icons/ChevronIcon';
import type { AiFilterErrorType } from '../../hooks/useAiFilters';

/** Cycle through loading messages to show progress. */
function useLoadingMessage(loading: boolean, messages: string[]): string {
  const [index, setIndex] = useState(0);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (!loading) {
      setIndex(0);
      return;
    }
    // Advance message every 1.5s
    timerRef.current = setTimeout(() => setIndex(1), 1500);
    const t2 = setTimeout(() => setIndex(2), 3500);
    const t3 = setTimeout(() => setIndex(3), 5500);
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
      clearTimeout(t2);
      clearTimeout(t3);
    };
  }, [loading]);

  return messages[index];
}

interface AiFilterInputProps {
  loading: boolean;
  error: string | null;
  errorType: AiFilterErrorType | null;
  notes: string | null;
  summary: string | null;
  onSubmit: (query: string) => void;
  isLoggedIn: boolean;
  onLoginRequired: () => void;
  defaultExpanded?: boolean;
  defaultQuery?: string;
}

export default memo(function AiFilterInput({
  loading,
  error,
  errorType,
  notes,
  summary,
  onSubmit,
  isLoggedIn,
  onLoginRequired,
  defaultExpanded = false,
  defaultQuery = '',
}: AiFilterInputProps) {
  const { t } = useTranslation();
  const [query, setQuery] = useState(defaultQuery);
  const [expanded, setExpanded] = useState(defaultExpanded);
  const exampleQueries = useMemo(
    () => [t('aiFilter.example1'), t('aiFilter.example2'), t('aiFilter.example3')],
    [t]
  );
  const loadingMessages = useMemo(
    () => [
      t('aiFilter.analysing'),
      t('aiFilter.searchingDestinations'),
      t('aiFilter.generatingFilters'),
      t('aiFilter.refiningResults'),
    ],
    [t]
  );
  const loadingMessage = useLoadingMessage(loading, loadingMessages);
  const containerRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const queryRef = useRef(query);
  queryRef.current = query;

  useEffect(() => {
    if (!expanded || loading) return;
    const handler = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        if (!queryRef.current.trim()) setExpanded(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [expanded, loading]);

  const resizeTextarea = useCallback(() => {
    const ta = textareaRef.current;
    if (!ta) return;
    ta.style.height = 'auto';
    ta.style.height = `${ta.scrollHeight}px`;
  }, []);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        const trimmed = query.trim();
        if (!trimmed || loading) return;
        if (!isLoggedIn) {
          onLoginRequired();
          return;
        }
        onSubmit(trimmed);
      }
    },
    [query, loading, isLoggedIn, onLoginRequired, onSubmit]
  );

  const handleSubmit = useCallback(
    (e: React.FormEvent) => {
      e.preventDefault();
      const trimmed = query.trim();
      if (!trimmed || loading) return;
      if (!isLoggedIn) {
        onLoginRequired();
        return;
      }
      onSubmit(trimmed);
    },
    [query, loading, isLoggedIn, onLoginRequired, onSubmit]
  );

  const handleExampleClick = useCallback(
    (example: string) => {
      if (loading) return;
      setQuery(example);
      if (!isLoggedIn) {
        onLoginRequired();
        return;
      }
      onSubmit(example);
    },
    [loading, isLoggedIn, onLoginRequired, onSubmit]
  );

  const hasContent = query.trim().length > 0;
  const showExamples = expanded && !hasContent && !loading && !error && !notes && !summary;

  if (!expanded) {
    return (
      <div ref={containerRef} className="px-3 py-2" data-tutorial="ai-filters">
        <button
          type="button"
          onClick={() => setExpanded(true)}
          className="w-full flex items-center gap-2 px-3 py-2 rounded-lg border border-dashed border-teal-300 dark:border-teal-700 bg-teal-50/50 dark:bg-teal-900/20 hover:bg-teal-50 dark:hover:bg-teal-900/30 cursor-pointer group"
        >
          <SparklesIcon className="w-4 h-4 text-teal-500 dark:text-teal-400 shrink-0" />
          <span className="text-sm text-teal-700 dark:text-teal-300 group-hover:text-teal-800 dark:group-hover:text-teal-200">
            {t('aiFilter.describeIdealArea')}
          </span>
        </button>
      </div>
    );
  }

  return (
    <div ref={containerRef} className="px-3 py-2" data-tutorial="ai-filters">
      <div className="flex items-center gap-1.5 mb-1.5">
        <SparklesIcon className="w-3.5 h-3.5 text-teal-500 dark:text-teal-400 shrink-0" />
        <span className="text-xs font-medium text-teal-700 dark:text-teal-300">
          {t('aiFilter.aiSearch')}
        </span>
        <span className="text-xs text-warm-400 dark:text-warm-500">
          {t('aiFilter.describeHint')}
        </span>
        <button
          type="button"
          onClick={() => setExpanded(false)}
          className="ml-auto text-warm-400 dark:text-warm-500 hover:text-warm-600 dark:hover:text-warm-300 cursor-pointer"
        >
          <ChevronIcon direction="up" className="w-3.5 h-3.5" />
        </button>
      </div>
      <form onSubmit={handleSubmit} className="flex items-end gap-1.5">
        <textarea
          ref={textareaRef}
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            resizeTextarea();
          }}
          onKeyDown={handleKeyDown}
          placeholder={t('aiFilter.placeholder')}
          className="flex-1 px-2.5 py-1.5 text-sm rounded-lg border border-warm-200 dark:border-warm-700 bg-warm-50 dark:bg-warm-800 text-warm-700 dark:text-warm-200 placeholder-warm-400 dark:placeholder-warm-500 focus:outline-none focus:ring-2 focus:ring-teal-400 focus:bg-white dark:focus:bg-warm-800 resize-none overflow-hidden"
          rows={1}
          style={{ maxHeight: '6rem' }}
          disabled={loading}
          autoFocus
        />
        <button
          type="submit"
          disabled={loading || !hasContent}
          className="shrink-0 px-3 py-1.5 rounded-lg bg-teal-600 hover:bg-teal-700 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium flex items-center gap-1.5"
        >
          {loading ? (
            <SpinnerIcon className="w-3.5 h-3.5 animate-spin" />
          ) : (
            <>
              <SparklesIcon className="w-3.5 h-3.5" />
              <span>{t('common.search')}</span>
            </>
          )}
        </button>
      </form>
      {loading && <p className="mt-1 text-xs text-teal-600 dark:text-teal-400">{loadingMessage}</p>}
      {showExamples && (
        <div className="mt-1.5 flex flex-wrap gap-1">
          {exampleQueries.map((example) => (
            <button
              key={example}
              type="button"
              onClick={() => handleExampleClick(example)}
              className="text-xs px-2 py-0.5 rounded-full border border-warm-200 dark:border-warm-700 text-warm-500 dark:text-warm-400 hover:border-teal-400 hover:text-teal-600 dark:hover:text-teal-400 cursor-pointer"
            >
              {example}
            </button>
          ))}
        </div>
      )}
      {error && errorType === 'limit' && (
        <p className="mt-1.5 text-xs text-amber-600 dark:text-amber-400">
          {t('aiFilter.weeklyLimitReached')}
        </p>
      )}
      {error && errorType === 'error' && (
        <p className="mt-1 text-xs text-red-600 dark:text-red-400 truncate" title={error}>
          {error}
        </p>
      )}
      {summary && !error && !loading && (
        <p className="mt-1 text-xs text-teal-600 dark:text-teal-400">{summary}</p>
      )}
      {notes && !error && !loading && (
        <p className="mt-1 text-xs text-warm-500 dark:text-warm-400 italic">{notes}</p>
      )}
    </div>
  );
});
