/**
 * 멀티차트 대시보드 - 종목 선택 드롭다운 (펼친 상태에서 드래그 가능)
 */
import React, { useState, useEffect } from 'react';
import {
  Button,
  Menu,
  MenuItem,
  TextField,
  InputAdornment,
  List,
  ListItem,
  ListItemButton,
  Box,
  Typography,
} from '@mui/material';
import { Add as AddIcon, Search as SearchIcon, DragIndicator } from '@mui/icons-material';
import { useDraggable } from '@dnd-kit/core';
import { MARKET_LIST, type MarketItem } from '../../constants/marketList';
import type { StockInfo } from '../../stores/useDashboardStore';

interface DraggableStockItemProps {
  item: MarketItem;
  onClick?: (item: MarketItem) => void;
}

const DraggableStockItem: React.FC<DraggableStockItemProps> = ({ item, onClick }) => {
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
    id: `stock-${item.symbol}`,
    data: {
      type: 'stock',
      stock: {
        symbol: item.symbol,
        koreanName: item.koreanName,
        englishName: item.englishName,
      } as StockInfo,
    },
  });

  const handleClick = (e: React.MouseEvent) => {
    // 드래그 중이 아닐 때만 클릭 이벤트 처리
    if (!isDragging && onClick) {
      e.stopPropagation();
      onClick(item);
    }
  };

  return (
    <ListItem disablePadding ref={setNodeRef} {...attributes} {...listeners}>
      <ListItemButton
        onClick={handleClick}
        sx={{
          py: 0.75,
          opacity: isDragging ? 0.5 : 1,
          borderRadius: 1,
          '&:hover': { bgcolor: 'action.hover' },
        }}
      >
        <DragIndicator fontSize="small" sx={{ mr: 1, color: 'text.disabled' }} />
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <Typography variant="body2" noWrap>
            {item.koreanName}
          </Typography>
          <Typography variant="caption" color="text.secondary">
            {item.symbol}
          </Typography>
        </Box>
      </ListItemButton>
    </ListItem>
  );
};

interface StockSelectDropdownProps {
  open: boolean;
  onOpen: () => void;
  onClose: () => void;
  /** 종목 선택 시 콜백 (클릭으로 선택) */
  onSelect?: (stock: StockInfo) => void;
  /** 드래그 중에는 메뉴 닫지 않음 */
  isDraggingFromMenu?: boolean;
}

export const StockSelectDropdown: React.FC<StockSelectDropdownProps> = ({
  open,
  onOpen,
  onClose,
  onSelect,
  isDraggingFromMenu = false,
}) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [search, setSearch] = useState('');

  const handleOpen = (e: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(e.currentTarget);
    onOpen();
  };

  const menuOpen = open && Boolean(anchorEl);

  const handleClose = () => {
    if (!isDraggingFromMenu) {
      setAnchorEl(null);
      setSearch('');
      onClose();
    }
  };

  const handleItemClick = (item: MarketItem) => {
    if (onSelect) {
      onSelect({
        symbol: item.symbol,
        koreanName: item.koreanName,
        englishName: item.englishName,
      });
      handleClose();
    }
  };

  useEffect(() => {
    if (!open) {
      setAnchorEl(null);
      setSearch('');
    }
  }, [open]);

  const filtered = MARKET_LIST.filter(
    (m) =>
      m.koreanName.toLowerCase().includes(search.toLowerCase()) ||
      m.symbol.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <>
      <Button
        variant="outlined"
        size="small"
        startIcon={<AddIcon />}
        onClick={handleOpen}
        sx={{ minWidth: 140, justifyContent: 'flex-start' }}
      >
        종목 선택
      </Button>
      <Menu
        anchorEl={anchorEl}
        open={menuOpen}
        onClose={handleClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
        transformOrigin={{ vertical: 'top', horizontal: 'left' }}
        PaperProps={{
          sx: {
            maxHeight: 400,
            width: 280,
            mt: 1.5,
          },
        }}
        disableAutoFocusItem
        disableScrollLock
      >
        <Box sx={{ px: 1.5, pt: 1, pb: 0.5 }}>
          <TextField
            size="small"
            placeholder="검색..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            fullWidth
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon fontSize="small" />
                </InputAdornment>
              ),
            }}
            sx={{ '& .MuiOutlinedInput-root': { bgcolor: 'action.hover' } }}
          />
        </Box>
        <List sx={{ maxHeight: 320, overflow: 'auto', py: 0 }}>
          {filtered.map((item) => (
            <DraggableStockItem key={item.symbol} item={item} onClick={handleItemClick} />
          ))}
        </List>
        {filtered.length === 0 && (
          <Box sx={{ p: 2, textAlign: 'center' }}>
            <Typography variant="body2" color="text.secondary">
              검색 결과 없음
            </Typography>
          </Box>
        )}
      </Menu>
    </>
  );
};
