/**
 * 멀티차트 대시보드 - 드래그 가능한 종목 리스트 사이드바
 */
import React, { useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  InputAdornment,
  List,
  ListItem,
  ListItemButton,
  Paper,
} from '@mui/material';
import { 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 DraggableStockProps {
  item: MarketItem;
}

const DraggableStock: React.FC<DraggableStockProps> = ({ item }) => {
  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,
    },
  });

  return (
    <ListItem disablePadding ref={setNodeRef} {...attributes} {...listeners}>
      <ListItemButton
        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 StockSidebarProps {
  onSelectStock?: (stock: StockInfo) => void;
}

export const StockSidebar: React.FC<StockSidebarProps> = ({ onSelectStock }) => {
  const [search, setSearch] = useState('');

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

  return (
    <Paper
      elevation={0}
      sx={{
        width: 240,
        flexShrink: 0,
        bgcolor: 'background.paper',
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
        overflow: 'hidden',
      }}
    >
      <Box sx={{ p: 1.5, borderBottom: '1px solid', borderColor: 'divider' }}>
        <Typography variant="subtitle2" fontWeight="bold" gutterBottom>
          종목 목록
        </Typography>
        <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: 400, overflow: 'auto', py: 0 }}>
        {filtered.map((item) => (
          <DraggableStock key={item.symbol} item={item} />
        ))}
      </List>
      {filtered.length === 0 && (
        <Box sx={{ p: 2, textAlign: 'center' }}>
          <Typography variant="body2" color="text.secondary">
            검색 결과 없음
          </Typography>
        </Box>
      )}
    </Paper>
  );
};
