import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  CardActions,
  Typography,
  IconButton,
  Chip,
  Stack,
  Dialog,
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  PlayArrow as PlayIcon,
  Pause as PauseIcon,
} from '@mui/icons-material';
import {
  getGlobalConditions,
  deleteCondition,
  toggleCondition,
  AlertConditionDto,
} from '../../services/alertApi';
import GlobalAlertConditionEditor from './GlobalAlertConditionEditor';

/**
 * 전역 알림 조건 패널
 * 모든 활성화된 종목에 적용되는 전역 조건 관리
 */
const GlobalAlertConditionsPanel: React.FC = () => {
  const [conditions, setConditions] = useState<AlertConditionDto[]>([]);
  const [editorOpen, setEditorOpen] = useState(false);
  const [editingCondition, setEditingCondition] = useState<AlertConditionDto | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadConditions();
  }, []);

  const loadConditions = async () => {
    try {
      setLoading(true);
      const data = await getGlobalConditions();
      setConditions(data);
    } catch (error) {
      console.error('전역 조건 목록 로드 실패:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAddCondition = () => {
    setEditingCondition(null);
    setEditorOpen(true);
  };

  const handleEditCondition = (condition: AlertConditionDto) => {
    setEditingCondition(condition);
    setEditorOpen(true);
  };

  const handleDeleteCondition = async (conditionId: number) => {
    if (!window.confirm('이 조건을 삭제하시겠습니까?')) return;
    
    try {
      await deleteCondition(conditionId);
      setConditions(prev => prev.filter(c => c.id !== conditionId));
    } catch (error) {
      console.error('조건 삭제 실패:', error);
      alert('조건 삭제에 실패했습니다.');
    }
  };

  const handleToggleCondition = async (condition: AlertConditionDto) => {
    if (!condition.id) return;
    
    try {
      const updated = await toggleCondition(condition.id, !condition.enabled);
      setConditions(prev => prev.map(c => c.id === updated.id ? updated : c));
    } catch (error) {
      console.error('조건 토글 실패:', error);
      alert('조건 상태 변경에 실패했습니다.');
    }
  };

  const handleSaveCondition = () => {
    setEditorOpen(false);
    setEditingCondition(null);
    loadConditions();
  };

  const handleCloseEditor = () => {
    setEditorOpen(false);
    setEditingCondition(null);
  };

  const getConditionDescription = (condition: AlertConditionDto): string => {
    let desc = `${condition.indicatorType} ${condition.conditionType}`;
    if (condition.targetValue !== undefined) {
      desc += ` ${condition.targetValue}`;
    }
    if (condition.period) {
      desc += ` (${condition.period}기간)`;
    }
    return desc;
  };

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Box>
          <Typography variant="h6">
            전역 알림 조건
          </Typography>
          <Typography variant="caption" color="text.secondary">
            좌측에서 활성화된 모든 종목에 적용됩니다
          </Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={handleAddCondition}
          size="small"
        >
          조건 추가
        </Button>
      </Box>

      {/* Conditions List */}
      <Box sx={{ flexGrow: 1, overflow: 'auto' }}>
        {loading ? (
          <Box sx={{ textAlign: 'center', py: 4 }}>
            <Typography variant="body2" color="text.secondary">
              로딩 중...
            </Typography>
          </Box>
        ) : conditions.length === 0 ? (
          <Box sx={{ textAlign: 'center', py: 4 }}>
            <Typography variant="body2" color="text.secondary">
              등록된 알림 조건이 없습니다.
            </Typography>
            <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
              "조건 추가" 버튼을 클릭하여 알림 조건을 설정하세요.
            </Typography>
          </Box>
        ) : (
          <Stack spacing={2}>
            {conditions.map((condition) => (
              <Card key={condition.id} variant="outlined">
                <CardContent sx={{ pb: 1 }}>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant="body2" fontWeight="medium">
                      {getConditionDescription(condition)}
                    </Typography>
                    <Chip
                      label={condition.enabled ? '활성' : '비활성'}
                      size="small"
                      color={condition.enabled ? 'success' : 'default'}
                    />
                  </Box>
                  {condition.description && (
                    <Typography variant="caption" color="text.secondary">
                      {condition.description}
                    </Typography>
                  )}
                  {condition.logicalOperator && (
                    <Chip
                      label={condition.logicalOperator}
                      size="small"
                      variant="outlined"
                      sx={{ ml: 1, mt: 0.5 }}
                    />
                  )}
                </CardContent>
                <CardActions sx={{ justifyContent: 'flex-end', pt: 0 }}>
                  <IconButton
                    size="small"
                    onClick={() => handleToggleCondition(condition)}
                    color={condition.enabled ? 'primary' : 'default'}
                  >
                    {condition.enabled ? <PauseIcon /> : <PlayIcon />}
                  </IconButton>
                  <IconButton
                    size="small"
                    onClick={() => handleEditCondition(condition)}
                  >
                    <EditIcon fontSize="small" />
                  </IconButton>
                  <IconButton
                    size="small"
                    color="error"
                    onClick={() => condition.id && handleDeleteCondition(condition.id)}
                  >
                    <DeleteIcon fontSize="small" />
                  </IconButton>
                </CardActions>
              </Card>
            ))}
          </Stack>
        )}
      </Box>

      {/* Condition Editor Dialog */}
      <Dialog
        open={editorOpen}
        onClose={handleCloseEditor}
        maxWidth="md"
        fullWidth
      >
        <GlobalAlertConditionEditor
          condition={editingCondition}
          onSave={handleSaveCondition}
          onCancel={handleCloseEditor}
        />
      </Dialog>
    </Box>
  );
};

export default GlobalAlertConditionsPanel;

