import { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Modal, Input, Typography, Tag, Empty, Spin, Grid } from 'antd';
import {
  SearchOutlined,
  SendOutlined,
  CalendarOutlined,
  ScheduleOutlined,
  FileTextOutlined,
  PlayCircleOutlined,
} from '@ant-design/icons';
import axios from 'axios';

const { Text } = Typography;

interface SearchResult {
  type: 'campaign' | 'shift' | 'page' | 'video' | 'event';
  id: string;
  title: string;
  description: string | null;
  link: string;
}

const TYPE_ICONS: Record<string, React.ReactNode> = {
  campaign: <SendOutlined />,
  shift: <ScheduleOutlined />,
  page: <FileTextOutlined />,
  video: <PlayCircleOutlined />,
  event: <CalendarOutlined />,
};

const TYPE_COLORS: Record<string, string> = {
  campaign: 'blue',
  shift: 'green',
  page: 'purple',
  video: 'magenta',
  event: 'orange',
};

interface PublicSearchModalProps {
  open: boolean;
  onClose: () => void;
}

export default function PublicSearchModal({ open, onClose }: PublicSearchModalProps) {
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeIndex, setActiveIndex] = useState(0);
  const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  const inputRef = useRef<any>(null);

  // Focus input on open
  useEffect(() => {
    if (open) {
      setQuery('');
      setResults([]);
      setActiveIndex(0);
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [open]);

  // Debounced search
  useEffect(() => {
    clearTimeout(timerRef.current);
    if (!query || query.length < 2) {
      setResults([]);
      return;
    }
    timerRef.current = setTimeout(async () => {
      setLoading(true);
      try {
        const { data } = await axios.get<SearchResult[]>('/api/search', {
          params: { q: query, limit: 10 },
        });
        setResults(data);
        setActiveIndex(0);
      } catch {
        setResults([]);
      } finally {
        setLoading(false);
      }
    }, 300);
    return () => clearTimeout(timerRef.current);
  }, [query]);

  const handleSelect = useCallback((result: SearchResult) => {
    onClose();
    navigate(result.link);
  }, [navigate, onClose]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActiveIndex(i => Math.min(i + 1, results.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActiveIndex(i => Math.max(i - 1, 0));
    } else if (e.key === 'Enter' && results[activeIndex]) {
      e.preventDefault();
      handleSelect(results[activeIndex]);
    }
  };

  // Global Ctrl+K handler
  useEffect(() => {
    // Only open from outside — parent manages the `open` state
  }, []);

  // Group results by type
  const grouped = results.reduce((acc, r) => {
    if (!acc[r.type]) acc[r.type] = [];
    acc[r.type]!.push(r);
    return acc;
  }, {} as Record<string, SearchResult[]>);

  let flatIndex = 0;

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      closable={false}
      width={isMobile ? '100%' : 520}
      style={{ top: isMobile ? 0 : 80 }}
      styles={{ body: { padding: 0 } }}
    >
      <div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
        <Input
          ref={inputRef}
          prefix={<SearchOutlined style={{ color: 'rgba(255,255,255,0.4)' }} />}
          placeholder="Search campaigns, shifts, pages..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onKeyDown={handleKeyDown}
          variant="borderless"
          size="large"
          suffix={loading ? <Spin size="small" /> : <Text type="secondary" style={{ fontSize: 11 }}>ESC</Text>}
        />
      </div>

      <div style={{ maxHeight: 400, overflowY: 'auto', padding: '8px 0' }}>
        {query.length >= 2 && !loading && results.length === 0 && (
          <Empty
            description={<Text type="secondary">No results found</Text>}
            style={{ padding: 32 }}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        )}
        {Object.entries(grouped).map(([type, items]) => (
          <div key={type}>
            <div style={{ padding: '8px 16px 4px', fontSize: 11, textTransform: 'uppercase', color: 'rgba(255,255,255,0.35)', letterSpacing: 1 }}>
              {type}s
            </div>
            {items.map((item) => {
              const idx = flatIndex++;
              return (
                <div
                  key={`${item.type}-${item.id}`}
                  onClick={() => handleSelect(item)}
                  onMouseEnter={() => setActiveIndex(idx)}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 10,
                    padding: '10px 16px',
                    cursor: 'pointer',
                    background: idx === activeIndex ? 'rgba(255,255,255,0.06)' : 'transparent',
                    transition: 'background 0.1s',
                  }}
                >
                  <span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 16 }}>
                    {TYPE_ICONS[item.type]}
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {item.title}
                    </div>
                    {item.description && (
                      <Text type="secondary" style={{ fontSize: 12, display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {item.description}
                      </Text>
                    )}
                  </div>
                  <Tag color={TYPE_COLORS[item.type]} style={{ margin: 0, fontSize: 10 }}>
                    {item.type}
                  </Tag>
                </div>
              );
            })}
          </div>
        ))}
      </div>

      {query.length < 2 && (
        <div style={{ padding: '16px', textAlign: 'center' }}>
          <Text type="secondary" style={{ fontSize: 13 }}>
            Type at least 2 characters to search
          </Text>
        </div>
      )}
    </Modal>
  );
}
