import React, { useState, useEffect, useRef } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Button,
  IconButton,
  Chip,
  Switch,
  FormControlLabel,
  CircularProgress,
  Fab,
  Badge,
  Tooltip,
  Divider,
  TextField,
  InputAdornment,
} from '@mui/material';
import {
  Settings as SettingsIcon,
  Refresh as RefreshIcon,
  DeleteSweep as DeleteSweepIcon,
  FilterList as FilterListIcon,
  Search as SearchIcon,
  PlayArrow as PlayArrowIcon,
  TrendingUp,
  TrendingDown,
  RemoveCircleOutline,
  Info as InfoIcon,
} from '@mui/icons-material';
import {
  getChatbotConfig,
  getChatbotMessages,
  toggleChatbotEnabled,
  triggerManualAnalysis,
  clearAllMessages,
  markMessageAsRead,
  type ChatbotMessage,
  type ChatbotConfig,
  type MessageType,
} from '../services/chatbotApi';

/**
 * AI Chatbot 페이지 - 카카오톡 스타일
 * 투자 전략 분석 결과를 실시간으로 챗봇 형태로 표시
 */
const ChatbotPage: React.FC = () => {
  // 상태 관리
  const [messages, setMessages] = useState<ChatbotMessage[]>([]);
  const [config, setConfig] = useState<ChatbotConfig | null>(null);
  const [loading, setLoading] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  const [filterType, setFilterType] = useState<MessageType | 'ALL'>('ALL');
  const [searchQuery, setSearchQuery] = useState('');
  const [settingsOpen, setSettingsOpen] = useState(false);
  
  // Refs
  const messagesEndRef = useRef<HTMLDivElement>(null);
  
  // 컴포넌트 마운트 시 데이터 로드
  useEffect(() => {
    loadConfig();
    loadMessages();
    
    // 주기적 새로고침 (30초마다)
    const interval = setInterval(() => {
      loadMessages();
    }, 30000);
    
    // WebSocket 연결 (실시간 메시지 수신)
    // TODO: WebSocket 구현 (Phase 4)
    
    return () => {
      clearInterval(interval);
    };
  }, []);
  
  // 메시지 로드
  const loadMessages = async () => {
    setLoading(true);
    try {
      const response = await getChatbotMessages({
        userId: 1,
        page: 0,
        size: 50,
        messageType: filterType === 'ALL' ? undefined : filterType,
      });
      
      setMessages(response.data.content);
      
      // 읽지 않은 메시지 개수 계산
      const unread = response.data.content.filter(m => !m.readStatus).length;
      setUnreadCount(unread);
    } catch (error) {
      console.error('메시지 로드 실패:', error);
      // 에러 시 빈 배열 설정
      setMessages([]);
      setUnreadCount(0);
    } finally {
      setLoading(false);
    }
  };
  
  // 설정 로드
  const loadConfig = async () => {
    try {
      const response = await getChatbotConfig(1);
      setConfig(response.data);
    } catch (error) {
      console.error('설정 로드 실패:', error);
      // 에러 시 기본 설정 사용
      setConfig({
        id: 1,
        userId: 1,
        enabled: false,
        scheduleType: 'INTERVAL',
        intervalMinutes: 5,
        candleInterval: '5m',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      });
    }
  };
  
  // 메시지 자동 스크롤
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };
  
  useEffect(() => {
    scrollToBottom();
  }, [messages]);
  
  // 필터링된 메시지
  const filteredMessages = messages.filter(msg => {
    const matchesType = filterType === 'ALL' || msg.messageType === filterType;
    const matchesSearch = searchQuery === '' || 
      msg.symbol.toLowerCase().includes(searchQuery.toLowerCase()) ||
      msg.symbolName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      msg.content.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesType && matchesSearch;
  });
  
  // 활성화/비활성화 토글
  const handleToggleEnabled = async () => {
    try {
      const response = await toggleChatbotEnabled(1);
      setConfig(response.data);
    } catch (error) {
      console.error('토글 실패:', error);
      alert('설정 변경에 실패했습니다.');
    }
  };
  
  // 수동 실행
  const handleManualRun = async () => {
    try {
      const response = await triggerManualAnalysis();
      alert(response.data.message || '분석이 시작되었습니다. 잠시 후 결과가 표시됩니다.');
      
      // 3초 후 메시지 새로고침
      setTimeout(() => {
        loadMessages();
      }, 3000);
    } catch (error) {
      console.error('수동 실행 실패:', error);
      alert('수동 실행에 실패했습니다.');
    }
  };
  
  // 전체 삭제
  const handleClearAll = async () => {
    if (!window.confirm('모든 메시지를 삭제하시겠습니까?')) return;
    
    try {
      await clearAllMessages(1);
      setMessages([]);
      setUnreadCount(0);
    } catch (error) {
      console.error('삭제 실패:', error);
      alert('메시지 삭제에 실패했습니다.');
    }
  };
  
  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      {/* 헤더 */}
      <Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Box>
          <Typography variant="h4" gutterBottom sx={{ fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: 1 }}>
            🤖 AI 투자 챗봇
            {config && (
              <Chip 
                label={config.enabled ? "활성" : "비활성"} 
                color={config.enabled ? "success" : "default"}
                size="small"
              />
            )}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            AI가 즐겨찾기 종목을 분석하여 매수/매도 신호를 자동으로 알려드립니다
          </Typography>
        </Box>
        
        <Box sx={{ display: 'flex', gap: 1 }}>
          <FormControlLabel
            control={
              <Switch 
                checked={config?.enabled || false} 
                onChange={handleToggleEnabled}
              />
            }
            label={config?.enabled ? "활성" : "비활성"}
          />
          <Tooltip title="설정">
            <IconButton onClick={() => setSettingsOpen(true)}>
              <SettingsIcon />
            </IconButton>
          </Tooltip>
          <Tooltip title="수동 실행">
            <IconButton color="primary" onClick={handleManualRun}>
              <PlayArrowIcon />
            </IconButton>
          </Tooltip>
          <Tooltip title="새로고침">
            <IconButton onClick={loadMessages}>
              <RefreshIcon />
            </IconButton>
          </Tooltip>
          <Tooltip title="전체 삭제">
            <IconButton color="error" onClick={handleClearAll}>
              <DeleteSweepIcon />
            </IconButton>
          </Tooltip>
        </Box>
      </Box>
      
      {/* 필터 및 검색 */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Chip 
              label="전체" 
              onClick={() => setFilterType('ALL')}
              color={filterType === 'ALL' ? 'primary' : 'default'}
            />
            <Chip 
              icon={<TrendingUp />}
              label="매수" 
              onClick={() => setFilterType('BUY')}
              color={filterType === 'BUY' ? 'success' : 'default'}
            />
            <Chip 
              icon={<TrendingDown />}
              label="매도" 
              onClick={() => setFilterType('SELL')}
              color={filterType === 'SELL' ? 'error' : 'default'}
            />
            <Chip 
              icon={<RemoveCircleOutline />}
              label="관망" 
              onClick={() => setFilterType('HOLD')}
              color={filterType === 'HOLD' ? 'default' : 'default'}
            />
          </Box>
          
          <TextField
            size="small"
            placeholder="종목명 또는 내용 검색..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
            }}
            sx={{ flexGrow: 1, maxWidth: 400 }}
          />
          
          {unreadCount > 0 && (
            <Chip 
              label={`읽지 않음: ${unreadCount}`} 
              color="primary" 
              size="small"
            />
          )}
        </Box>
      </Paper>
      
      {/* 메시지 리스트 */}
      <Paper sx={{ 
        height: 'calc(100vh - 350px)', 
        overflowY: 'auto',
        p: 2,
        bgcolor: '#f5f5f5',
      }}>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
            <CircularProgress />
          </Box>
        ) : filteredMessages.length === 0 ? (
          <Box sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '100%', color: 'text.secondary' }}>
            <InfoIcon sx={{ fontSize: 48, mb: 2 }} />
            <Typography>아직 메시지가 없습니다</Typography>
            <Typography variant="body2">AI가 분석 결과를 생성하면 여기에 표시됩니다</Typography>
          </Box>
        ) : (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {filteredMessages.map((message) => (
              <ChatbotMessageCard key={message.id} message={message} />
            ))}
            <div ref={messagesEndRef} />
          </Box>
        )}
      </Paper>
      
      {/* 설정 다이얼로그 */}
      {/* TODO: ChatbotSettingsDialog 컴포넌트 구현 */}
    </Container>
  );
};

/**
 * 챗봇 메시지 카드 컴포넌트
 */
const ChatbotMessageCard: React.FC<{ message: ChatbotMessage }> = ({ message }) => {
  const getMessageColor = () => {
    switch (message.messageType) {
      case 'BUY': return '#22c55e';
      case 'SELL': return '#ef4444';
      case 'HOLD': return '#6366f1';
      default: return '#6b7280';
    }
  };
  
  const getMessageIcon = () => {
    switch (message.messageType) {
      case 'BUY': return '📈';
      case 'SELL': return '📉';
      case 'HOLD': return '⏸';
      default: return 'ℹ️';
    }
  };
  
  return (
    <Paper 
      sx={{ 
        p: 2, 
        borderLeft: `4px solid ${getMessageColor()}`,
        bgcolor: 'white',
        boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
        transition: 'transform 0.2s',
        '&:hover': {
          transform: 'translateY(-2px)',
          boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
        },
        animation: 'slideInRight 0.3s ease',
        '@keyframes slideInRight': {
          from: {
            opacity: 0,
            transform: 'translateX(20px)',
          },
          to: {
            opacity: 1,
            transform: 'translateX(0)',
          },
        },
      }}
    >
      {/* 헤더 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography variant="h6" sx={{ fontWeight: 'bold' }}>
            {getMessageIcon()} {message.symbolName}
          </Typography>
          <Chip 
            label={message.symbol} 
            size="small" 
            variant="outlined"
          />
        </Box>
        <Typography variant="caption" color="text.secondary">
          {new Date(message.createdAt).toLocaleString('ko-KR')}
        </Typography>
      </Box>
      
      {/* 제목 */}
      <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 1, color: getMessageColor() }}>
        {message.title}
      </Typography>
      
      {/* 본문 */}
      <Typography 
        variant="body2" 
        sx={{ 
          whiteSpace: 'pre-line',
          color: 'text.primary',
          lineHeight: 1.6,
        }}
      >
        {message.content}
      </Typography>
      
      {/* 하단 정보 */}
      {message.price && (
        <Box sx={{ mt: 2, pt: 2, borderTop: '1px solid #e0e0e0' }}>
          <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
            <Chip 
              label={`현재가: ${message.price.toLocaleString()}원`} 
              size="small"
              color="primary"
              variant="outlined"
            />
            {message.indicators?.rsi && (
              <Chip 
                label={`RSI: ${message.indicators.rsi.toFixed(1)}`} 
                size="small"
                variant="outlined"
              />
            )}
          </Box>
        </Box>
      )}
    </Paper>
  );
};

export default ChatbotPage;
