import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Box,
  InputBase,
  Paper,
  List,
  ListItem,
  ListItemButton,
  ListItemAvatar,
  ListItemText,
  Avatar,
  Typography,
  Chip,
  Divider,
  CircularProgress,
  IconButton,
  Popper,
  ClickAwayListener
} from '@mui/material';
import {
  Search as SearchIcon,
  Tv,
  Radio as RadioIcon,
  Person,
  Settings as SettingsIcon,
  Folder,
  Close,
  PlayArrow
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import Logo from './Logo';
import api from '../utils/api';

// Debounce hook
function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

function GlobalSearch({ onChannelSelect }) {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState('');
  const [results, setResults] = useState(null);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const anchorRef = useRef(null);
  const inputRef = useRef(null);

  const debouncedSearch = useDebounce(searchQuery, 300);

  // Search function
  const performSearch = useCallback(async (query) => {
    if (!query || query.trim().length < 2) {
      setResults(null);
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      const response = await api.get('/search', {
        params: { q: query }
      });
      setResults(response.data);
    } catch (error) {
      console.error('Search error:', error);
      setResults(null);
    } finally {
      setLoading(false);
    }
  }, []);

  // Perform search when debounced value changes
  useEffect(() => {
    if (debouncedSearch) {
      performSearch(debouncedSearch);
    } else {
      setResults(null);
    }
  }, [debouncedSearch, performSearch]);

  const handleInputChange = (e) => {
    const value = e.target.value;
    setSearchQuery(value);
    setOpen(value.length >= 2);
  };

  const handleClear = () => {
    setSearchQuery('');
    setResults(null);
    setOpen(false);
    inputRef.current?.focus();
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleChannelClick = (channel) => {
    setSearchQuery('');
    setOpen(false);
    if (onChannelSelect) {
      onChannelSelect(channel);
    }
    // Navigate to appropriate page
    if (channel.is_radio === 1) {
      navigate('/radio', { state: { autoPlayChannel: channel }, replace: false });
    } else {
      navigate('/live-tv', { state: { autoPlayChannel: channel }, replace: false });
    }
  };

  const handleUserClick = (user) => {
    setSearchQuery('');
    setOpen(false);
    navigate('/settings?tab=users', { state: { selectedUserId: user.id } });
  };

  const handleSettingClick = (setting) => {
    setSearchQuery('');
    setOpen(false);
    navigate(setting.path);
  };

  const handleGroupClick = (group) => {
    setSearchQuery('');
    setOpen(false);
    if (group.is_radio === 1) {
      navigate('/radio', { state: { selectedGroup: group.name } });
    } else {
      navigate('/live', { state: { selectedGroup: group.name } });
    }
  };

  const hasResults = results && (
    results.channels?.length > 0 ||
    results.radio?.length > 0 ||
    results.users?.length > 0 ||
    results.settings?.length > 0 ||
    results.groups?.length > 0
  );

  const getCategoryIcon = (type) => {
    switch (type) {
      case 'channel': return <Tv fontSize="small" />;
      case 'radio': return <RadioIcon fontSize="small" />;
      case 'user': return <Person fontSize="small" />;
      case 'setting': return <SettingsIcon fontSize="small" />;
      case 'group': return <Folder fontSize="small" />;
      default: return <SearchIcon fontSize="small" />;
    }
  };

  return (
    <Box sx={{ flexGrow: 1, maxWidth: 600, position: 'relative' }}>
      <Box
        ref={anchorRef}
        sx={{
          display: 'flex',
          alignItems: 'center',
          bgcolor: 'action.hover',
          borderRadius: 1.5,
          px: 1.5,
          py: 0.5,
          transition: 'all 0.2s',
          border: open ? 2 : 0,
          borderColor: 'primary.main'
        }}
      >
        <SearchIcon sx={{ color: 'text.secondary', mr: 1, fontSize: 20 }} />
        <InputBase
          ref={inputRef}
          placeholder={t('search') || 'Search channels, settings, users...'}
          fullWidth
          value={searchQuery}
          onChange={handleInputChange}
          sx={{ color: 'text.primary', fontSize: '0.875rem' }}
          onFocus={() => searchQuery.length >= 2 && setOpen(true)}
        />
        {(loading || searchQuery) && (
          <Box sx={{ display: 'flex', alignItems: 'center', ml: 1 }}>
            {loading && <CircularProgress size={16} sx={{ mr: 1 }} />}
            {searchQuery && (
              <IconButton size="small" onClick={handleClear}>
                <Close fontSize="small" />
              </IconButton>
            )}
          </Box>
        )}
      </Box>

      <Popper
        open={open && (hasResults || (searchQuery.length >= 2 && !loading))}
        anchorEl={anchorRef.current}
        placement="bottom-start"
        style={{ width: anchorRef.current?.offsetWidth, zIndex: 1300 }}
      >
        <ClickAwayListener onClickAway={handleClose}>
          <Paper
            elevation={8}
            sx={{
              mt: 1,
              maxHeight: '70vh',
              overflow: 'auto',
              bgcolor: 'background.paper'
            }}
          >
            {!hasResults && !loading && searchQuery.length >= 2 && (
              <Box sx={{ p: 3, textAlign: 'center' }}>
                <SearchIcon sx={{ fontSize: 48, color: 'text.secondary', mb: 1 }} />
                <Typography color="text.secondary">
                  No results found for "{searchQuery}"
                </Typography>
              </Box>
            )}

            {/* TV Channels */}
            {results?.channels?.length > 0 && (
              <>
                <Box sx={{ px: 2, py: 1, bgcolor: 'action.hover' }}>
                  <Typography variant="caption" fontWeight="bold" color="primary">
                    TV CHANNELS ({results.channels.length})
                  </Typography>
                </Box>
                <List dense>
                  {results.channels.map((channel) => (
                    <ListItem key={`channel-${channel.id}`} disablePadding>
                      <ListItemButton onClick={() => handleChannelClick(channel)}>
                        <ListItemAvatar>
                          {channel.logo ? (
                            <Avatar
                              src={channel.logo.startsWith('http') ? channel.logo : `/logos/${channel.logo}`}
                              variant="rounded"
                              sx={{ width: 40, height: 40 }}
                            />
                          ) : (
                            <Avatar variant="rounded" sx={{ width: 40, height: 40 }}>
                              <Logo size={24} />
                            </Avatar>
                          )}
                        </ListItemAvatar>
                        <ListItemText
                          primary={
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              {channel.name}
                              <PlayArrow sx={{ fontSize: 16, color: 'primary.main' }} />
                            </Box>
                          }
                          secondary={channel.group_name}
                        />
                        <Chip icon={getCategoryIcon('channel')} label="TV" size="small" />
                      </ListItemButton>
                    </ListItem>
                  ))}
                </List>
                <Divider />
              </>
            )}

            {/* Radio Stations */}
            {results?.radio?.length > 0 && (
              <>
                <Box sx={{ px: 2, py: 1, bgcolor: 'action.hover' }}>
                  <Typography variant="caption" fontWeight="bold" color="primary">
                    RADIO STATIONS ({results.radio.length})
                  </Typography>
                </Box>
                <List dense>
                  {results.radio.map((channel) => (
                    <ListItem key={`radio-${channel.id}`} disablePadding>
                      <ListItemButton onClick={() => handleChannelClick(channel)}>
                        <ListItemAvatar>
                          {channel.logo ? (
                            <Avatar
                              src={channel.logo.startsWith('http') ? channel.logo : `/logos/${channel.logo}`}
                              variant="rounded"
                              sx={{ width: 40, height: 40 }}
                            />
                          ) : (
                            <Avatar variant="rounded" sx={{ width: 40, height: 40 }}>
                              <Logo size={24} />
                            </Avatar>
                          )}
                        </ListItemAvatar>
                        <ListItemText
                          primary={
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              {channel.name}
                              <PlayArrow sx={{ fontSize: 16, color: 'primary.main' }} />
                            </Box>
                          }
                          secondary={channel.group_name}
                        />
                        <Chip icon={getCategoryIcon('radio')} label="Radio" size="small" color="secondary" />
                      </ListItemButton>
                    </ListItem>
                  ))}
                </List>
                <Divider />
              </>
            )}

            {/* Groups */}
            {results?.groups?.length > 0 && (
              <>
                <Box sx={{ px: 2, py: 1, bgcolor: 'action.hover' }}>
                  <Typography variant="caption" fontWeight="bold" color="primary">
                    GROUPS ({results.groups.length})
                  </Typography>
                </Box>
                <List dense>
                  {results.groups.map((group, index) => (
                    <ListItem key={`group-${index}`} disablePadding>
                      <ListItemButton onClick={() => handleGroupClick(group)}>
                        <ListItemAvatar>
                          <Avatar>
                            {getCategoryIcon('group')}
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText
                          primary={group.name}
                          secondary={group.is_radio === 1 ? 'Radio Group' : 'TV Group'}
                        />
                      </ListItemButton>
                    </ListItem>
                  ))}
                </List>
                <Divider />
              </>
            )}

            {/* Settings */}
            {results?.settings?.length > 0 && (
              <>
                <Box sx={{ px: 2, py: 1, bgcolor: 'action.hover' }}>
                  <Typography variant="caption" fontWeight="bold" color="primary">
                    PAGES & SETTINGS ({results.settings.length})
                  </Typography>
                </Box>
                <List dense>
                  {results.settings.map((setting) => (
                    <ListItem key={setting.id} disablePadding>
                      <ListItemButton onClick={() => handleSettingClick(setting)}>
                        <ListItemAvatar>
                          <Avatar>
                            {getCategoryIcon('setting')}
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText primary={setting.name} />
                      </ListItemButton>
                    </ListItem>
                  ))}
                </List>
                <Divider />
              </>
            )}

            {/* Users (Admin only) */}
            {results?.users?.length > 0 && (
              <>
                <Box sx={{ px: 2, py: 1, bgcolor: 'action.hover' }}>
                  <Typography variant="caption" fontWeight="bold" color="primary">
                    USERS ({results.users.length})
                  </Typography>
                </Box>
                <List dense>
                  {results.users.map((user) => (
                    <ListItem key={`user-${user.id}`} disablePadding>
                      <ListItemButton onClick={() => handleUserClick(user)}>
                        <ListItemAvatar>
                          <Avatar>
                            {getCategoryIcon('user')}
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText
                          primary={user.username}
                          secondary={user.email}
                        />
                        <Chip
                          label={user.role}
                          size="small"
                          color={user.role === 'admin' ? 'error' : 'default'}
                        />
                      </ListItemButton>
                    </ListItem>
                  ))}
                </List>
              </>
            )}
          </Paper>
        </ClickAwayListener>
      </Popper>
    </Box>
  );
}

export default GlobalSearch;
