/**
 * 자동매매 페이지
 * - 업비트 API를 통한 자동 매수/매도 기능
 * - API 키 설정, 전략 설정, 포지션, 주문 내역 통합
 */
import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Typography,
  Paper,
  Grid,
  Card,
  CardContent,
  CardHeader,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  FormControlLabel,
  Chip,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  Tab,
  Alert,
  Divider,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  InputAdornment,
  useTheme,
  alpha,
} from '@mui/material';
import {
  PlayArrow,
  Stop,
  Add,
  Refresh,
  Settings,
  AccountBalance as AccountBalanceIcon,
  TrendingUp,
  TrendingDown,
  Warning,
  CheckCircle,
  Error as ErrorIcon,
  Security,
  History,
  ShowChart,
} from '@mui/icons-material';
import { useUpbitTicker } from '../hooks/useUpbitTicker';
import MarketList from '../components/MarketList';
import {
  getAccountBalances,
  getPositions,
  getOrderHistory,
  getStrategies,
  saveStrategy,
  placeBuyOrder,
  placeSellOrder,
  checkApiKeyStatus,
  type AccountBalance,
  type Position,
  type OrderInfo,
  type AutoTradingStrategy,
  type OrderType,
} from '../services/autoTradingApi';

// ============ 유틸 ============
const formatPrice = (n: number): string =>
  n.toLocaleString('ko-KR', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
const formatVolume = (n: number): string =>
  n.toLocaleString('ko-KR', { minimumFractionDigits: 4, maximumFractionDigits: 4 });

// ============ Mock 데이터 (백엔드 미구현 시) ============
const useMockData = true; // 백엔드 API 준비되면 false로 변경

const mockBalances: AccountBalance[] = [
  { currency: 'KRW', balance: '1500000', locked: '0', avgBuyPrice: '0', avgBuyPriceModified: false, unitCurrency: 'KRW' },
];
const mockPositions: Position[] = [
  { market: 'KRW-BTC', currency: 'BTC', balance: 0.001, avgBuyPrice: 95000000, currentPrice: 98000000, evalAmount: 98000, profitLoss: 3000, profitLossRate: 3.16 },
  { market: 'KRW-ETH', currency: 'ETH', balance: 0.5, avgBuyPrice: 4500000, currentPrice: 4600000, evalAmount: 2300000, profitLoss: 50000, profitLossRate: 2.22 },
];
const mockOrders: OrderInfo[] = [];

// ============ 메인 컴포넌트 ============
const AutoTradingPage: React.FC = () => {
  const theme = useTheme();
  const isDark = theme.palette.mode === 'dark';
  const { tickers, wsStatus: tickerWsStatus } = useUpbitTicker();

  const [selectedMarket, setSelectedMarket] = useState<string>('KRW-BTC');
  const [balances, setBalances] = useState<AccountBalance[]>([]);
  const [positions, setPositions] = useState<Position[]>([]);
  const [orders, setOrders] = useState<OrderInfo[]>([]);
  const [strategies, setStrategies] = useState<AutoTradingStrategy[]>([]);
  const [apiKeyStatus, setApiKeyStatus] = useState<{ configured: boolean; valid: boolean } | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState(0);

  // 전략 설정 다이얼로그
  const [strategyDialogOpen, setStrategyDialogOpen] = useState(false);
  const [strategyForm, setStrategyForm] = useState<Partial<AutoTradingStrategy>>({
    name: '',
    market: 'KRW-BTC',
    enabled: false,
    dryRun: true,
    buyCondition: {
      orderType: 'price',
      amount: 50000,
      trigger: 'manual',
    },
    sellCondition: {
      orderType: 'market',
      volumePercent: 100,
      stopLossPercent: 5,
      takeProfitPercent: 10,
    },
    riskLimit: {
      maxOrderAmount: 100000,
      maxDailyLoss: 50000,
      maxPosition: 5,
    },
  });

  // 수동 주문
  const [manualOrderType, setManualOrderType] = useState<OrderType>('price');
  const [manualAmount, setManualAmount] = useState<string>('50000');
  const [manualVolume, setManualVolume] = useState<string>('');
  const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      if (useMockData) {
        setBalances(mockBalances);
        setPositions(mockPositions);
        setOrders(mockOrders);
        setApiKeyStatus({ configured: false, valid: false });
        return;
      }
      const [status, acc, pos, ords] = await Promise.all([
        checkApiKeyStatus(),
        getAccountBalances(),
        getPositions(),
        getOrderHistory(),
      ]);
      setApiKeyStatus(status);
      setBalances(acc);
      setPositions(pos);
      setOrders(ords);
      const strats = await getStrategies();
      setStrategies(strats);
    } catch (e) {
      setError(e instanceof Error ? e.message : '데이터 로드 실패');
      if (useMockData) {
        setBalances(mockBalances);
        setPositions(mockPositions);
        setOrders(mockOrders);
      }
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 30000);
    return () => clearInterval(interval);
  }, [fetchData]);

  const krwBalance = balances.find((b) => b.currency === 'KRW');
  const krwAmount = krwBalance ? parseFloat(krwBalance.balance) : 0;
  const totalCryptoValue = positions.reduce((sum, p) => sum + p.evalAmount, 0);

  const handleManualBuy = async () => {
    setError(null);
    try {
      if (useMockData) {
        alert('백엔드 API가 준비되면 실제 매수가 진행됩니다. (현재 모의 모드)');
        return;
      }
      await placeBuyOrder({
        market: selectedMarket,
        orderType: manualOrderType,
        amount: manualOrderType === 'price' ? parseFloat(manualAmount) : undefined,
        volume: manualOrderType === 'market' ? parseFloat(manualVolume) : undefined,
        price: manualOrderType === 'limit' ? parseFloat(manualAmount) : undefined,
      });
      fetchData();
    } catch (e) {
      setError(e instanceof Error ? e.message : '매수 실패');
    }
  };

  const handleManualSell = async () => {
    const pos = positions.find((p) => p.market === selectedMarket);
    if (!pos) {
      setError('보유 수량이 없습니다.');
      return;
    }
    setError(null);
    try {
      if (useMockData) {
        alert('백엔드 API가 준비되면 실제 매도가 진행됩니다. (현재 모의 모드)');
        return;
      }
      await placeSellOrder({
        market: selectedMarket,
        orderType: manualOrderType,
        volume: manualVolume ? parseFloat(manualVolume) : pos.balance,
      });
      fetchData();
    } catch (e) {
      setError(e instanceof Error ? e.message : '매도 실패');
    }
  };

  const handleSaveStrategy = async () => {
    if (!strategyForm.name || !strategyForm.market) return;
    try {
      if (useMockData) {
        alert('백엔드 API가 준비되면 전략이 저장됩니다.');
        setStrategyDialogOpen(false);
        return;
      }
      await saveStrategy(strategyForm as AutoTradingStrategy);
      fetchData();
      setStrategyDialogOpen(false);
    } catch (e) {
      setError(e instanceof Error ? e.message : '전략 저장 실패');
    }
  };

  const currentTicker = tickers.get(selectedMarket);
  const currentPrice = currentTicker?.tradePrice ?? 0;

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 헤더 */}
      <Box
        sx={{
          p: 2,
          borderBottom: 1,
          borderColor: 'divider',
          backgroundColor: isDark ? alpha(theme.palette.background.paper, 0.8) : 'background.paper',
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 1 }}>
          <Box>
            <Typography variant="h5" fontWeight={700}>
              자동매매
            </Typography>
            <Typography variant="body2" color="text.secondary">
              업비트 API 연동 · 자동 매수/매도 전략 실행
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
            <Chip
              icon={apiKeyStatus?.configured ? <CheckCircle /> : <Warning />}
              label={apiKeyStatus?.configured ? 'API 연결됨' : 'API 미설정'}
              color={apiKeyStatus?.configured ? 'success' : 'warning'}
              size="small"
            />
            <Tooltip title="새로고침">
              <IconButton onClick={fetchData} disabled={loading}>
                <Refresh />
              </IconButton>
            </Tooltip>
          </Box>
        </Box>
      </Box>

      {error && (
        <Alert severity="error" sx={{ m: 2, mb: 0 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}

      {/* 메인 그리드 */}
      <Box sx={{ flex: 1, overflow: 'auto', p: 2 }}>
        <Grid container spacing={2}>
          {/* 좌측: 종목 목록 + 계정 요약 */}
          <Grid item xs={12} md={4}>
            {/* API 키 설정 안내 */}
            {(!apiKeyStatus?.configured || useMockData) && (
              <Card sx={{ mb: 2, border: '1px dashed', borderColor: 'warning.main', bgcolor: alpha(theme.palette.warning.main, 0.04) }}>
                <CardContent>
                  <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
                    <Security color="warning" />
                    <Box sx={{ flex: 1 }}>
                      <Typography variant="subtitle2" fontWeight={600} color="warning.dark">
                        업비트 API 키 설정
                      </Typography>
                      <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
                        자동매매를 사용하려면 업비트 Open API 키가 필요합니다. 설정에서 API 키를 등록해 주세요.
                      </Typography>
                      <Button
                        size="small"
                        variant="outlined"
                        color="warning"
                        sx={{ mt: 1 }}
                        onClick={() => setApiKeyDialogOpen(true)}
                      >
                        API 키 설정
                      </Button>
                    </Box>
                  </Box>
                </CardContent>
              </Card>
            )}

            <Card sx={{ height: '100%', mb: 2 }}>
              <CardHeader
                avatar={<AccountBalanceIcon color="primary" />}
                title="계정 요약"
                subheader={loading ? '로딩 중...' : undefined}
              />
              <CardContent>
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography color="text.secondary">KRW 잔고</Typography>
                    <Typography variant="h6" fontWeight={700}>
                      {formatPrice(krwAmount)} 원
                    </Typography>
                  </Box>
                  <Divider />
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography color="text.secondary">총 평가금액</Typography>
                    <Typography variant="h6" fontWeight={700} color="primary.main">
                      {formatPrice(totalCryptoValue)} 원
                    </Typography>
                  </Box>
                  <Divider />
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography color="text.secondary">보유 종목</Typography>
                    <Typography variant="body1" fontWeight={600}>
                      {positions.length}개
                    </Typography>
                  </Box>
                </Box>
              </CardContent>
            </Card>

            <Box sx={{ height: 360 }}>
              <MarketList
                tickers={tickers}
                selectedMarket={selectedMarket}
                onSelectMarket={setSelectedMarket}
                wsStatus={tickerWsStatus}
              />
            </Box>
          </Grid>

          {/* 우측: 주문/전략/포지션/내역 */}
          <Grid item xs={12} md={8}>
            <Paper sx={{ mb: 2 }}>
              <Tabs value={activeTab} onChange={(_, v) => setActiveTab(v)}>
                <Tab icon={<ShowChart />} iconPosition="start" label="주문" />
                <Tab icon={<Settings />} iconPosition="start" label="전략" />
                <Tab icon={<AccountBalanceIcon />} iconPosition="start" label="포지션" />
                <Tab icon={<History />} iconPosition="start" label="주문내역" />
              </Tabs>

              {/* 탭 0: 주문 */}
              {activeTab === 0 && (
                <Box sx={{ p: 2 }}>
                  <Typography variant="subtitle1" fontWeight={600} sx={{ mb: 2 }}>
                    {selectedMarket} · 현재가 {formatPrice(currentPrice)} 원
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={12} sm={6}>
                      <Card variant="outlined" sx={{ borderColor: 'success.main', bgcolor: alpha(theme.palette.success.main, 0.04) }}>
                        <CardContent>
                          <Typography variant="subtitle2" color="success.main" fontWeight={600} sx={{ mb: 1 }}>
                            매수
                          </Typography>
                          <FormControl fullWidth size="small" sx={{ mb: 1 }}>
                            <InputLabel>주문 유형</InputLabel>
                            <Select
                              value={manualOrderType}
                              label="주문 유형"
                              onChange={(e) => setManualOrderType(e.target.value as OrderType)}
                            >
                              <MenuItem value="price">시장가 (금액)</MenuItem>
                              <MenuItem value="market">시장가 (수량)</MenuItem>
                              <MenuItem value="limit">지정가</MenuItem>
                            </Select>
                          </FormControl>
                          {(manualOrderType === 'price' || manualOrderType === 'limit') && (
                            <TextField
                              fullWidth
                              size="small"
                              label={manualOrderType === 'price' ? '매수 금액 (원)' : '지정가 (원)'}
                              value={manualAmount}
                              onChange={(e) => setManualAmount(e.target.value)}
                              InputProps={{ endAdornment: <InputAdornment position="end">원</InputAdornment> }}
                              sx={{ mb: 1 }}
                            />
                          )}
                          {manualOrderType === 'market' && (
                            <TextField
                              fullWidth
                              size="small"
                              label="매수 수량"
                              value={manualVolume}
                              onChange={(e) => setManualVolume(e.target.value)}
                              sx={{ mb: 1 }}
                            />
                          )}
                          <Button
                            fullWidth
                            variant="contained"
                            color="success"
                            startIcon={<TrendingUp />}
                            onClick={handleManualBuy}
                            disabled={!apiKeyStatus?.configured && !useMockData}
                          >
                            매수
                          </Button>
                        </CardContent>
                      </Card>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Card variant="outlined" sx={{ borderColor: 'error.main', bgcolor: alpha(theme.palette.error.main, 0.04) }}>
                        <CardContent>
                          <Typography variant="subtitle2" color="error.main" fontWeight={600} sx={{ mb: 1 }}>
                            매도
                          </Typography>
                          <FormControl fullWidth size="small" sx={{ mb: 1 }}>
                            <InputLabel>주문 유형</InputLabel>
                            <Select
                              value={manualOrderType}
                              label="주문 유형"
                              onChange={(e) => setManualOrderType(e.target.value as OrderType)}
                            >
                              <MenuItem value="market">시장가 (수량)</MenuItem>
                              <MenuItem value="limit">지정가</MenuItem>
                            </Select>
                          </FormControl>
                          <TextField
                            fullWidth
                            size="small"
                            label="매도 수량 (비워두면 전량)"
                            value={manualVolume}
                            onChange={(e) => setManualVolume(e.target.value)}
                            placeholder={positions.find((p) => p.market === selectedMarket)?.balance.toString() ?? ''}
                            sx={{ mb: 1 }}
                          />
                          <Button
                            fullWidth
                            variant="contained"
                            color="error"
                            startIcon={<TrendingDown />}
                            onClick={handleManualSell}
                            disabled={!positions.find((p) => p.market === selectedMarket) && !useMockData}
                          >
                            매도
                          </Button>
                        </CardContent>
                      </Card>
                    </Grid>
                  </Grid>
                </Box>
              )}

              {/* 탭 1: 전략 */}
              {activeTab === 1 && (
                <Box sx={{ p: 2 }}>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                    <Typography variant="subtitle1" fontWeight={600}>
                      자동매매 전략
                    </Typography>
                    <Button
                      variant="outlined"
                      size="small"
                      startIcon={<Add />}
                      onClick={() => {
                        setStrategyForm({
                          name: '',
                          market: selectedMarket,
                          enabled: false,
                          dryRun: true,
                          buyCondition: { orderType: 'price', amount: 50000, trigger: 'manual' },
                          sellCondition: { orderType: 'market', volumePercent: 100, stopLossPercent: 5, takeProfitPercent: 10 },
                          riskLimit: { maxOrderAmount: 100000, maxDailyLoss: 50000, maxPosition: 5 },
                        });
                        setStrategyDialogOpen(true);
                      }}
                    >
                      전략 추가
                    </Button>
                  </Box>
                  {strategies.length === 0 && !useMockData ? (
                    <Alert severity="info">등록된 전략이 없습니다. 전략을 추가해 주세요.</Alert>
                  ) : (
                    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
{(useMockData ? [{ id: 'mock-1', name: '샘플 전략', market: 'KRW-BTC', enabled: false, dryRun: true }] : strategies).map((s) => (
                          <Paper key={s.id ?? s.name} variant="outlined" sx={{ p: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <Box>
                            <Typography fontWeight={600}>{s.name}</Typography>
                            <Typography variant="body2" color="text.secondary">
                              {s.market} · {s.dryRun ? '모의' : '실제'} · {s.enabled ? '실행중' : '중지'}
                            </Typography>
                          </Box>
                          <Box sx={{ display: 'flex', gap: 1 }}>
                            <Chip label={s.dryRun ? '모의' : '실제'} size="small" color={s.dryRun ? 'default' : 'warning'} />
                            <Chip label={s.enabled ? 'ON' : 'OFF'} size="small" color={s.enabled ? 'success' : 'default'} />
                          </Box>
                        </Paper>
                      ))}
                    </Box>
                  )}
                </Box>
              )}

              {/* 탭 2: 포지션 */}
              {activeTab === 2 && (
                <Box sx={{ p: 2 }}>
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>종목</TableCell>
                          <TableCell align="right">보유수량</TableCell>
                          <TableCell align="right">평균단가</TableCell>
                          <TableCell align="right">현재가</TableCell>
                          <TableCell align="right">평가금액</TableCell>
                          <TableCell align="right">손익</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {positions.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={6} align="center" sx={{ py: 4 }}>
                              보유 종목이 없습니다.
                            </TableCell>
                          </TableRow>
                        ) : (
                          positions.map((p) => (
                            <TableRow key={p.market} hover onClick={() => setSelectedMarket(p.market)} sx={{ cursor: 'pointer' }}>
                              <TableCell>{p.market}</TableCell>
                              <TableCell align="right">{formatVolume(p.balance)}</TableCell>
                              <TableCell align="right">{formatPrice(p.avgBuyPrice)}</TableCell>
                              <TableCell align="right">{formatPrice(p.currentPrice)}</TableCell>
                              <TableCell align="right">{formatPrice(p.evalAmount)}</TableCell>
                              <TableCell align="right">
                                <Typography color={p.profitLoss >= 0 ? 'success.main' : 'error.main'} fontWeight={600}>
                                  {p.profitLoss >= 0 ? '+' : ''}{formatPrice(p.profitLoss)} ({p.profitLossRate >= 0 ? '+' : ''}{p.profitLossRate.toFixed(2)}%)
                                </Typography>
                              </TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </Box>
              )}

              {/* 탭 3: 주문내역 */}
              {activeTab === 3 && (
                <Box sx={{ p: 2 }}>
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>시간</TableCell>
                          <TableCell>종목</TableCell>
                          <TableCell>구분</TableCell>
                          <TableCell align="right">가격</TableCell>
                          <TableCell align="right">수량</TableCell>
                          <TableCell>상태</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {orders.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={6} align="center" sx={{ py: 4 }}>
                              주문 내역이 없습니다.
                            </TableCell>
                          </TableRow>
                        ) : (
                          orders.map((o) => (
                            <TableRow key={o.uuid}>
                              <TableCell>{new Date(o.created_at).toLocaleString('ko-KR')}</TableCell>
                              <TableCell>{o.market}</TableCell>
                              <TableCell>
                                <Chip label={o.side === 'bid' ? '매수' : '매도'} size="small" color={o.side === 'bid' ? 'success' : 'error'} />
                              </TableCell>
                              <TableCell align="right">{formatPrice(parseFloat(o.price))}</TableCell>
                              <TableCell align="right">{o.volume ?? '-'}</TableCell>
                              <TableCell>
                                <Chip label={o.state} size="small" variant="outlined" />
                              </TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </Box>
              )}
            </Paper>
          </Grid>
        </Grid>
      </Box>

      {/* API 키 설정 다이얼로그 */}
      <Dialog open={apiKeyDialogOpen} onClose={() => setApiKeyDialogOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>업비트 API 키 설정</DialogTitle>
        <DialogContent>
          <Alert severity="info" sx={{ mb: 2 }}>
            API 키는 서버에 암호화되어 저장됩니다. 업비트 마이페이지 → Open API에서 발급받으세요.
          </Alert>
          <TextField fullWidth label="Access Key" type="password" sx={{ mb: 1 }} placeholder="업비트 Access Key" />
          <TextField fullWidth label="Secret Key" type="password" placeholder="업비트 Secret Key" />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setApiKeyDialogOpen(false)}>취소</Button>
          <Button variant="contained" onClick={() => setApiKeyDialogOpen(false)}>
            저장 (백엔드 연동 후 활성화)
          </Button>
        </DialogActions>
      </Dialog>

      {/* 전략 설정 다이얼로그 */}
      <Dialog open={strategyDialogOpen} onClose={() => setStrategyDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>자동매매 전략 설정</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
            <TextField
              label="전략 이름"
              value={strategyForm.name}
              onChange={(e) => setStrategyForm((f) => ({ ...f, name: e.target.value }))}
              fullWidth
              required
            />
            <FormControl fullWidth>
              <InputLabel>종목</InputLabel>
              <Select
                value={strategyForm.market ?? ''}
                label="종목"
                onChange={(e) => setStrategyForm((f) => ({ ...f, market: e.target.value }))}
              >
                {Array.from(tickers.keys()).slice(0, 20).map((m) => (
                  <MenuItem key={m} value={m}>{m}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControlLabel
              control={
                <Switch
                  checked={strategyForm.dryRun ?? true}
                  onChange={(e) => setStrategyForm((f) => ({ ...f, dryRun: e.target.checked }))}
                />
              }
              label="모의 모드 (실제 주문 없이 시뮬레이션)"
            />
            <FormControlLabel
              control={
                <Switch
                  checked={strategyForm.enabled ?? false}
                  onChange={(e) => setStrategyForm((f) => ({ ...f, enabled: e.target.checked }))}
                />
              }
              label="전략 활성화"
            />
            <Divider />
            <Typography variant="subtitle2" color="text.secondary">매수 조건</Typography>
            <TextField
              label="1회 매수 금액 (원)"
              type="number"
              value={strategyForm.buyCondition?.amount ?? ''}
              onChange={(e) =>
                setStrategyForm((f) => ({
                  ...f,
                  buyCondition: { ...f.buyCondition!, amount: parseFloat(e.target.value) || 0 },
                }))
              }
              InputProps={{ endAdornment: <InputAdornment position="end">원</InputAdornment> }}
            />
            <Divider />
            <Typography variant="subtitle2" color="text.secondary">매도 조건</Typography>
            <TextField
              label="손절 (%)"
              type="number"
              value={strategyForm.sellCondition?.stopLossPercent ?? ''}
              onChange={(e) =>
                setStrategyForm((f) => ({
                  ...f,
                  sellCondition: { ...f.sellCondition!, stopLossPercent: parseFloat(e.target.value) || 0 },
                }))
              }
              InputProps={{ endAdornment: <InputAdornment position="end">%</InputAdornment> }}
            />
            <TextField
              label="익절 (%)"
              type="number"
              value={strategyForm.sellCondition?.takeProfitPercent ?? ''}
              onChange={(e) =>
                setStrategyForm((f) => ({
                  ...f,
                  sellCondition: { ...f.sellCondition!, takeProfitPercent: parseFloat(e.target.value) || 0 },
                }))
              }
              InputProps={{ endAdornment: <InputAdornment position="end">%</InputAdornment> }}
            />
            <Divider />
            <Typography variant="subtitle2" color="text.secondary">리스크 제한</Typography>
            <TextField
              label="1회 최대 주문 금액"
              type="number"
              value={strategyForm.riskLimit?.maxOrderAmount ?? ''}
              onChange={(e) =>
                setStrategyForm((f) => ({
                  ...f,
                  riskLimit: { ...f.riskLimit!, maxOrderAmount: parseFloat(e.target.value) || 0 },
                }))
              }
              InputProps={{ endAdornment: <InputAdornment position="end">원</InputAdornment> }}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setStrategyDialogOpen(false)}>취소</Button>
          <Button variant="contained" onClick={handleSaveStrategy} disabled={!strategyForm.name}>
            저장
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AutoTradingPage;
