import { useState, useEffect } from 'react';
import { useSearchParams, useLocation, useNavigate } from 'react-router-dom';
import { Input, Select, Button, theme, Grid } from 'antd';
import { SearchOutlined, SendOutlined } from '@ant-design/icons';
import { useSettingsStore } from '@/stores/settings.store';

const { useBreakpoint } = Grid;

export default function MediaBottomNav() {
  const { token } = theme.useToken();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const location = useLocation();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const { settings } = useSettingsStore();

  // Initialize from URL params
  const [searchInput, setSearchInput] = useState(searchParams.get('search') || '');
  const sort = (searchParams.get('sort') as 'recent' | 'popular' | 'most_viewed') || 'recent';

  const isShorts = location.pathname === '/gallery/shorts';

  // Debounce search → URL param (skip on shorts — search navigates to gallery on Enter)
  useEffect(() => {
    if (isShorts) return;

    const timer = setTimeout(() => {
      const params = new URLSearchParams(searchParams);
      if (searchInput) {
        params.set('search', searchInput);
      } else {
        params.delete('search');
      }
      setSearchParams(params, { replace: true });
    }, 300);
    return () => clearTimeout(timer);
  }, [searchInput, isShorts]);

  const handleSortChange = (value: 'recent' | 'popular' | 'most_viewed') => {
    if (isShorts) {
      // Navigate to gallery with sort param
      navigate(`/gallery?sort=${value}`);
      return;
    }
    const params = new URLSearchParams(searchParams);
    if (value !== 'recent') {
      params.set('sort', value);
    } else {
      params.delete('sort');
    }
    setSearchParams(params, { replace: true });
  };

  // On shorts page, Enter in search navigates to gallery with the search term
  const handleSearchSubmit = () => {
    if (isShorts && searchInput.trim()) {
      navigate(`/gallery?search=${encodeURIComponent(searchInput.trim())}`);
    }
  };

  return (
    <div
      style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        height: `calc(48px + env(safe-area-inset-bottom, 0px))`,
        paddingBottom: 'env(safe-area-inset-bottom, 0px)',
        background: isShorts ? 'rgba(0, 0, 0, 0.75)' : token.colorBgContainer,
        backdropFilter: isShorts ? 'blur(12px)' : undefined,
        borderTop: isShorts ? '1px solid rgba(255,255,255,0.08)' : `1px solid ${token.colorBorderSecondary}`,
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        padding: isMobile ? '0 8px' : '0 16px',
        zIndex: 1000,
      }}
    >
      {isMobile && settings?.enableInfluence !== false && (
        <Button
          type="text"
          size="small"
          icon={<SendOutlined />}
          onClick={() => navigate('/campaigns')}
          style={{ color: token.colorTextSecondary, flexShrink: 0 }}
        >
          {!isShorts && 'Action'}
        </Button>
      )}
      <Input
        placeholder="Search videos..."
        prefix={<SearchOutlined style={{ color: token.colorTextTertiary }} />}
        value={searchInput}
        onChange={(e) => setSearchInput(e.target.value)}
        onPressEnter={handleSearchSubmit}
        allowClear
        size="small"
        style={{ flex: 1 }}
      />
      <Select
        value={sort}
        onChange={handleSortChange}
        size="small"
        style={{ width: isMobile ? 110 : 140, flexShrink: 0 }}
        options={[
          { value: 'recent', label: 'Recent' },
          { value: 'popular', label: 'Popular' },
          { value: 'most_viewed', label: 'Most Viewed' },
        ]}
      />
    </div>
  );
}
