/**
 * 종목 선택 다이얼로그
 */
import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  TextField,
  InputAdornment,
  List,
  ListItemButton,
  ListItemText,
} from '@mui/material';
import { Search as SearchIcon } from '@mui/icons-material';
import { MARKET_LIST } from '../../constants/marketList';
import type { StockInfo } from '../../stores/useDashboardStore';

interface StockSelectDialogProps {
  open: boolean;
  onClose: () => void;
  onSelect: (stock: StockInfo) => void;
}

export const StockSelectDialog: React.FC<StockSelectDialogProps> = ({ open, onClose, onSelect }) => {
  const [search, setSearch] = useState('');

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

  const handleSelect = (item: (typeof MARKET_LIST)[0]) => {
    onSelect({
      symbol: item.symbol,
      koreanName: item.koreanName,
      englishName: item.englishName,
    });
    onClose();
    setSearch('');
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>종목 추가</DialogTitle>
      <DialogContent>
        <TextField
          size="small"
          placeholder="검색..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          fullWidth
          sx={{ mb: 1 }}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon fontSize="small" />
              </InputAdornment>
            ),
          }}
        />
        <List sx={{ maxHeight: 320, overflow: 'auto' }}>
          {filtered.map((item) => (
            <ListItemButton key={item.symbol} onClick={() => handleSelect(item)}>
              <ListItemText
                primary={item.koreanName}
                secondary={item.symbol}
              />
            </ListItemButton>
          ))}
        </List>
      </DialogContent>
    </Dialog>
  );
};
