'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import {
  Box,
  Container,
  Typography,
  Card,
  CardContent,
  Chip,
  Button,
  IconButton,
  Grid,
  CircularProgress,
  Alert,
  Tooltip as MuiTooltip,
} from '@mui/material';
import {
  Group,
  Visibility,
  TrendingUp,
  ArrowBack,
  Refresh as RefreshIcon,
} from '@mui/icons-material';
import { Line, Bar } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip as ChartTooltip,
  Legend,
  Filler,
} from 'chart.js';
import { analyticsApi } from '@/entities/analytics/api/analyticsApi';

// Chart.js 등록
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  ChartTooltip,
  Legend,
  Filler
);

// 디자인 시스템 색상
const colors = {
  pink: '#F472B6',
  purple: '#C084FC',
  purpleLight: '#E9D5FF',
  blue: '#60A5FA',
  mint: '#34D399',
  orange: '#FB923C',
  yellow: '#FBBF24',
  gray: {
    900: '#1A1A1A',
    700: '#4A4A4A',
    500: '#9E9E9E',
    300: '#D9D9D9',
    100: '#F5F5F5',
  },
};

export default function TestAnalyticsPage() {
  const router = useRouter();
  const params = useParams();
  const eventId = params.eventId as string;

  const [chartPeriod, setChartPeriod] = useState<'7d' | '30d' | 'all'>('7d');
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [analyticsData, setAnalyticsData] = useState<any>(null);

  // Analytics API 호출
  const fetchAnalytics = async (forceRefresh = false) => {
    try {
      if (forceRefresh) {
        console.log('🔄 데이터 새로고침 시작...');
        setRefreshing(true);
      } else {
        console.log('📊 Analytics 데이터 로딩 시작...');
        setLoading(true);
      }
      setError(null);

      // Event Analytics API 병렬 호출
      const [dashboard, timeline, roi, channels] = await Promise.all([
        analyticsApi.getEventAnalytics(eventId, { refresh: forceRefresh }),
        analyticsApi.getEventTimelineAnalytics(eventId, {
          interval: 'daily', // 항상 일별 데이터를 받아서 프론트엔드에서 필터링
          refresh: forceRefresh
        }),
        analyticsApi.getEventRoiAnalytics(eventId, { includeProjection: true, refresh: forceRefresh }),
        analyticsApi.getEventChannelAnalytics(eventId, { refresh: forceRefresh }),
      ]);

      console.log('✅ Dashboard 데이터:', dashboard);
      console.log('✅ Timeline 데이터:', timeline);
      console.log('✅ ROI 데이터:', roi);
      console.log('✅ Channel 데이터:', channels);

      // ROI 상세 데이터 구조 확인
      console.log('💰 === ROI 상세 데이터 확인 ===');
      console.log('💰 investment 전체:', roi?.investment);
      console.log('💰 investment.total:', roi?.investment?.total);
      console.log('💰 investment.prizeCost:', roi?.investment?.prizeCost);
      console.log('💰 investment.distribution:', roi?.investment?.distribution);
      console.log('💰 investment.contentCreation:', roi?.investment?.contentCreation);
      console.log('💰 investment.operation:', roi?.investment?.operation);
      console.log('💰 revenue 전체:', roi?.revenue);
      console.log('💰 revenue.total:', roi?.revenue?.total);
      console.log('💰 revenue.newCustomerRevenue:', roi?.revenue?.newCustomerRevenue);
      console.log('💰 ==============================');

      // Analytics 데이터 저장
      setAnalyticsData({
        dashboard,
        timeline,
        roi,
        channels,
      });

      console.log('✅ Analytics 데이터 로딩 완료');
    } catch (err: any) {
      console.error('❌ Analytics 데이터 로딩 실패:', err);
      setError(err.message || 'Analytics 데이터를 불러오는데 실패했습니다.');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // 초기 데이터 로드
  useEffect(() => {
    fetchAnalytics();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [eventId]);

  const handleRefresh = () => {
    fetchAnalytics(true);
  };

  // 날짜 포맷 함수 (년월일만)
  const formatDate = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // 실제 이벤트 참여 기간 계산 (Timeline 데이터 기반)
  const getActualEventPeriod = () => {
    console.log('📅 === 이벤트 기간 계산 디버그 ===');
    console.log('📅 analyticsData:', analyticsData);
    console.log('📅 analyticsData?.timeline:', analyticsData?.timeline);
    console.log('📅 analyticsData?.timeline?.dataPoints:', analyticsData?.timeline?.dataPoints);

    if (!analyticsData?.timeline?.dataPoints || analyticsData.timeline.dataPoints.length === 0) {
      console.log('❌ dataPoints가 없거나 비어있음');
      return null;
    }

    const dataPoints = analyticsData.timeline.dataPoints;
    console.log('📅 dataPoints 개수:', dataPoints.length);
    console.log('📅 첫번째 dataPoint:', dataPoints[0]);

    const timestamps = dataPoints.map((point: any) => new Date(point.timestamp).getTime());
    console.log('📅 timestamps:', timestamps);

    const firstTimestamp = Math.min(...timestamps);
    const lastTimestamp = Math.max(...timestamps);

    console.log('📅 첫 참여:', new Date(firstTimestamp).toISOString());
    console.log('📅 마지막 참여:', new Date(lastTimestamp).toISOString());
    console.log('📅 ==============================');

    return {
      startDate: new Date(firstTimestamp),
      endDate: new Date(lastTimestamp),
    };
  };

  // 이벤트 종료 여부 확인
  const isEventEnded = () => {
    const period = getActualEventPeriod();
    if (!period) return false;

    const now = new Date();
    const daysSinceLastActivity = (now.getTime() - period.endDate.getTime()) / (1000 * 60 * 60 * 24);

    // 마지막 참여로부터 1일 이상 지났으면 종료로 간주
    return daysSinceLastActivity > 1;
  };

  // 날짜 표시 문자열 생성
  const getDateDisplayString = () => {
    const period = getActualEventPeriod();
    if (!period) return '';

    const startDate = formatDate(period.startDate.toISOString());
    const endDate = formatDate(period.endDate.toISOString());

    if (isEventEnded()) {
      return `${startDate} ~ ${endDate}`;
    } else {
      return `${startDate} ~ 진행중`;
    }
  };

  // 날짜+시간 포맷 함수 (YYYY-MM-DD HH:MM:SS)
  const formatDateTime = (dateString: string) => {
    if (!dateString) return 'Unknown';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  // 차트 데이터 생성 함수
  const generateParticipationTrendData = () => {
    console.log('📊 === 차트 데이터 생성 디버그 ===');
    console.log('📊 chartPeriod:', chartPeriod);
    console.log('📊 analyticsData?.timeline:', analyticsData?.timeline);

    if (!analyticsData?.timeline) {
      console.log('❌ timeline 데이터 없음');
      return {
        labels: [],
        datasets: [{
          label: '일별 참여자',
          data: [],
          borderColor: colors.blue,
          backgroundColor: `${colors.blue}40`,
          fill: true,
          tension: 0.4,
        }],
      };
    }

    const timelineData = analyticsData.timeline;
    const dataPoints = timelineData.dataPoints || [];
    console.log('📊 dataPoints:', dataPoints);
    console.log('📊 dataPoints.length:', dataPoints.length);

    if (dataPoints.length === 0) {
      console.log('❌ dataPoints가 비어있음');
      return {
        labels: [],
        datasets: [{
          label: '일별 참여자',
          data: [],
          borderColor: colors.blue,
          backgroundColor: `${colors.blue}40`,
          fill: true,
          tension: 0.4,
        }],
      };
    }

    // 마지막 참여 시점 찾기 (가장 최근 timestamp)
    const timestamps = dataPoints.map((point: any) => new Date(point.timestamp).getTime());
    const lastTimestamp = Math.max(...timestamps);
    const lastDate = new Date(lastTimestamp);

    console.log(`📅 마지막 참여 시점: ${lastDate.toISOString()}`);

    // 마지막 참여 시점 기준으로 필터링 기간 계산
    let cutoffDate: Date | null = null;

    if (chartPeriod === '7d') {
      cutoffDate = new Date(lastDate);
      cutoffDate.setDate(lastDate.getDate() - 7);
    } else if (chartPeriod === '30d') {
      cutoffDate = new Date(lastDate);
      cutoffDate.setDate(lastDate.getDate() - 30);
    }
    // 'all'인 경우 cutoffDate는 null (필터링 안 함)

    console.log(`📊 필터링 시작일: ${cutoffDate ? cutoffDate.toISOString() : '전체'}`);

    // 기간 필터링된 데이터 포인트
    const filteredPoints = cutoffDate
      ? dataPoints.filter((point: any) => {
          const pointDate = new Date(point.timestamp);
          return pointDate >= cutoffDate && pointDate <= lastDate;
        })
      : dataPoints;

    console.log('📊 필터링된 포인트 개수:', filteredPoints.length);

    // 데이터 포인트를 날짜별로 그룹화
    const dailyData = new Map<string, { date: Date; participants: number }>();
    filteredPoints.forEach((point: any) => {
      const date = new Date(point.timestamp);
      const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;

      if (!dailyData.has(dateKey)) {
        dailyData.set(dateKey, { date, participants: 0 });
      }
      const current = dailyData.get(dateKey)!;
      current.participants += point.participants;
    });

    console.log('📊 일별 그룹화된 데이터:', Array.from(dailyData.entries()));

    // 날짜순으로 정렬
    const sortedEntries = Array.from(dailyData.entries()).sort((a, b) =>
      a[1].date.getTime() - b[1].date.getTime()
    );

    // 라벨과 데이터 생성 (MM/DD 형식)
    const labels = sortedEntries.map(([_, value]) => {
      const date = value.date;
      return `${date.getMonth() + 1}/${date.getDate()}`;
    });
    const data = sortedEntries.map(([_, value]) => value.participants);

    console.log(`📊 차트 기간: ${chartPeriod}, 데이터 포인트: ${data.length}개`);
    console.log('📊 차트 labels:', labels);
    console.log('📊 차트 data:', data);
    console.log('📊 ==============================');

    return {
      labels,
      datasets: [{
        label: '일별 참여자',
        data,
        borderColor: colors.blue,
        backgroundColor: `${colors.blue}40`,
        fill: true,
        tension: 0.4,
      }],
    };
  };

  const generateChannelPerformanceData = () => {
    if (!analyticsData?.channels?.channels) {
      return {
        labels: [],
        datasets: [{
          label: '참여자 수',
          data: [],
          backgroundColor: [],
          borderRadius: 8,
        }],
      };
    }

    const channelColors = [colors.pink, colors.blue, colors.orange, colors.purple, colors.mint, colors.yellow];
    const channels = analyticsData.channels.channels;

    const labels = channels.map((ch: any) => {
      let channelName = ch.channelName || ch.channelType || '알 수 없음';
      // 채널명 디코딩 처리
      if (channelName.includes('%')) {
        try {
          channelName = decodeURIComponent(channelName);
        } catch (e) {
          console.warn('⚠️ 채널명 디코딩 실패:', channelName);
        }
      }
      return channelName;
    });

    const data = channels.map((ch: any) => ch.metrics?.participants || 0);
    const backgroundColor = channels.map((_: any, idx: number) => channelColors[idx % channelColors.length]);

    return {
      labels,
      datasets: [{
        label: '참여자 수',
        data,
        backgroundColor,
        borderRadius: 8,
      }],
    };
  };

  const generateRoiTrendData = () => {
    // ROI는 현재 시점의 값만 있으므로 간단한 추이를 표시
    if (!analyticsData?.roi) {
      return {
        labels: ['현재'],
        datasets: [{
          label: 'ROI (%)',
          data: [0],
          borderColor: colors.mint,
          backgroundColor: `${colors.mint}40`,
          fill: true,
          tension: 0.4,
        }],
      };
    }

    const currentRoi = analyticsData.roi.roi?.roiPercentage || 0;

    // 단순 추정: 초기 0에서 현재 ROI까지의 추이
    const labels = ['시작', '1주차', '2주차', '3주차', '현재'];
    const data = [0, currentRoi * 0.3, currentRoi * 0.5, currentRoi * 0.75, currentRoi];

    return {
      labels,
      datasets: [{
        label: 'ROI (%)',
        data,
        borderColor: colors.mint,
        backgroundColor: `${colors.mint}40`,
        fill: true,
        tension: 0.4,
      }],
    };
  };

  // 로딩 중
  if (loading) {
    return (
      <Box sx={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Box sx={{ textAlign: 'center' }}>
          <CircularProgress size={60} sx={{ mb: 2 }} />
          <Typography variant="body1" color="text.secondary">
            Analytics 데이터 로딩 중...
          </Typography>
        </Box>
      </Box>
    );
  }

  // 에러 발생
  if (error) {
    return (
      <Box sx={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', p: 3 }}>
        <Alert severity="error" sx={{ maxWidth: 600 }}>
          <Typography variant="h6" sx={{ mb: 1 }}>Analytics 데이터 로딩 실패</Typography>
          {error}
          <Box sx={{ mt: 2 }}>
            <Button variant="contained" onClick={() => fetchAnalytics()}>
              다시 시도
            </Button>
          </Box>
        </Alert>
      </Box>
    );
  }

  const dashboard = analyticsData?.dashboard;

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: 'background.default', pb: { xs: 5, sm: 10 } }}>
      <Container maxWidth="lg" sx={{ pt: { xs: 4, sm: 8 }, pb: { xs: 4, sm: 8 }, px: { xs: 3, sm: 6, md: 10 } }}>
        {/* Header */}
        <Box sx={{ mb: { xs: 4, sm: 8 } }}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: { xs: 2, sm: 4 } }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <IconButton onClick={() => router.back()}>
                <ArrowBack />
              </IconButton>
              <Box>
                <Chip
                  label="🧪 TEST"
                  size="small"
                  sx={{ bgcolor: colors.yellow, color: colors.gray[900], fontWeight: 600, mb: 1 }}
                />
                <Typography variant="h4" sx={{ fontWeight: 700, fontSize: { xs: '1.25rem', sm: '2rem' } }}>
                  {dashboard?.eventTitle || 'Analytics 테스트 페이지'}
                </Typography>
              </Box>
            </Box>
            <MuiTooltip title="데이터 새로고침">
              <IconButton onClick={handleRefresh} disabled={refreshing}>
                <RefreshIcon
                  sx={{
                    animation: refreshing ? 'spin 1s linear infinite' : 'none',
                    '@keyframes spin': {
                      '0%': { transform: 'rotate(0deg)' },
                      '100%': { transform: 'rotate(360deg)' },
                    },
                  }}
                />
              </IconButton>
            </MuiTooltip>
          </Box>

          <Typography variant="body1" color="text.secondary" sx={{ fontSize: { xs: '0.875rem', sm: '1rem' } }}>
            📅 {getDateDisplayString()}
          </Typography>
        </Box>

        {/* Real-time KPIs */}
        <Box sx={{ mb: { xs: 4, sm: 10 } }}>
          <Typography variant="h5" sx={{ fontWeight: 700, mb: { xs: 3, sm: 6 }, fontSize: { xs: '1rem', sm: '1.5rem' } }}>
            실시간 현황
          </Typography>

          <Grid container spacing={{ xs: 1.5, sm: 6 }}>
            <Grid item xs={6} md={3}>
              <Card
                elevation={0}
                sx={{
                  borderRadius: { xs: 2, sm: 4 },
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
                  background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.purpleLight} 100%)`,
                  height: '100%',
                }}
              >
                <CardContent sx={{
                  textAlign: 'center',
                  pt: { xs: 1.5, sm: 6 }, pb: { xs: 1.5, sm: 6 },
                  px: { xs: 1, sm: 4 },
                }}>
                  <Group sx={{ fontSize: { xs: 20, sm: 40 }, mb: { xs: 0.5, sm: 2 }, color: 'white' }} />
                  <Typography variant="caption" display="block" sx={{ mb: { xs: 0.5, sm: 2 }, color: 'rgba(255,255,255,0.9)', fontSize: { xs: '0.5625rem', sm: '0.75rem' } }}>
                    참여자
                  </Typography>
                  <Typography variant="h4" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '0.9375rem', sm: '1.75rem' } }}>
                    {dashboard?.summary?.participants?.toLocaleString() || 0}명
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={3}>
              <Card
                elevation={0}
                sx={{
                  borderRadius: { xs: 2, sm: 4 },
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
                  background: `linear-gradient(135deg, ${colors.blue} 0%, #93C5FD 100%)`,
                  height: '100%',
                }}
              >
                <CardContent sx={{
                  textAlign: 'center',
                  pt: { xs: 1.5, sm: 6 }, pb: { xs: 1.5, sm: 6 },
                  px: { xs: 1, sm: 4 },
                }}>
                  <Visibility sx={{ fontSize: { xs: 20, sm: 40 }, mb: { xs: 0.5, sm: 2 }, color: 'white' }} />
                  <Typography variant="caption" display="block" sx={{ mb: { xs: 0.5, sm: 2 }, color: 'rgba(255,255,255,0.9)', fontSize: { xs: '0.5625rem', sm: '0.75rem' } }}>
                    조회수
                  </Typography>
                  <Typography variant="h4" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '0.9375rem', sm: '1.75rem' } }}>
                    {dashboard?.summary?.totalViews?.toLocaleString() || 0}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={3}>
              <Card
                elevation={0}
                sx={{
                  borderRadius: { xs: 2, sm: 4 },
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
                  background: `linear-gradient(135deg, ${colors.mint} 0%, #6EE7B7 100%)`,
                  height: '100%',
                }}
              >
                <CardContent sx={{
                  textAlign: 'center',
                  pt: { xs: 1.5, sm: 6 }, pb: { xs: 1.5, sm: 6 },
                  px: { xs: 1, sm: 4 },
                }}>
                  <TrendingUp sx={{ fontSize: { xs: 20, sm: 40 }, mb: { xs: 0.5, sm: 2 }, color: 'white' }} />
                  <Typography variant="caption" display="block" sx={{ mb: { xs: 0.5, sm: 2 }, color: 'rgba(255,255,255,0.9)', fontSize: { xs: '0.5625rem', sm: '0.75rem' } }}>
                    ROI
                  </Typography>
                  <Typography variant="h4" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '0.9375rem', sm: '1.75rem' } }}>
                    {Math.round(dashboard?.roi?.roi || 0)}%
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={3}>
              <Card
                elevation={0}
                sx={{
                  borderRadius: { xs: 2, sm: 4 },
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
                  background: `linear-gradient(135deg, ${colors.orange} 0%, #FCD34D 100%)`,
                  height: '100%',
                }}
              >
                <CardContent sx={{
                  textAlign: 'center',
                  pt: { xs: 1.5, sm: 6 }, pb: { xs: 1.5, sm: 6 },
                  px: { xs: 1, sm: 4 },
                }}>
                  <TrendingUp sx={{ fontSize: { xs: 20, sm: 40 }, mb: { xs: 0.5, sm: 2 }, color: 'white' }} />
                  <Typography variant="caption" display="block" sx={{ mb: { xs: 0.5, sm: 2 }, color: 'rgba(255,255,255,0.9)', fontSize: { xs: '0.5625rem', sm: '0.75rem' } }}>
                    전환율
                  </Typography>
                  <Typography variant="h4" sx={{ fontWeight: 700, color: 'white', fontSize: { xs: '0.9375rem', sm: '1.75rem' } }}>
                    {Math.round((dashboard?.summary?.conversionRate || 0) * 100)}%
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </Box>

        {/* Chart Section - 참여 추이 */}
        <Box sx={{ mb: { xs: 5, sm: 10 } }}>
          <Typography variant="h5" sx={{ fontWeight: 700, mb: { xs: 3, sm: 6 }, fontSize: { xs: '1.125rem', sm: '1.5rem' } }}>
            📈 참여 추이
          </Typography>
          <Card elevation={0} sx={{ borderRadius: { xs: 3, sm: 4 }, boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)' }}>
            <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
              <Box sx={{ display: 'flex', gap: { xs: 1, sm: 2 }, mb: { xs: 3, sm: 6 } }}>
                <Button
                  size="medium"
                  variant={chartPeriod === '7d' ? 'contained' : 'outlined'}
                  onClick={() => setChartPeriod('7d')}
                  sx={{ borderRadius: 2, fontSize: { xs: '0.75rem', sm: '0.875rem' }, py: { xs: 0.5, sm: 1 }, px: { xs: 1.5, sm: 2 } }}
                >
                  7일
                </Button>
                <Button
                  size="medium"
                  variant={chartPeriod === '30d' ? 'contained' : 'outlined'}
                  onClick={() => setChartPeriod('30d')}
                  sx={{ borderRadius: 2, fontSize: { xs: '0.75rem', sm: '0.875rem' }, py: { xs: 0.5, sm: 1 }, px: { xs: 1.5, sm: 2 } }}
                >
                  30일
                </Button>
                <Button
                  size="medium"
                  variant={chartPeriod === 'all' ? 'contained' : 'outlined'}
                  onClick={() => setChartPeriod('all')}
                  sx={{ borderRadius: 2, fontSize: { xs: '0.75rem', sm: '0.875rem' }, py: { xs: 0.5, sm: 1 }, px: { xs: 1.5, sm: 2 } }}
                >
                  전체
                </Button>
              </Box>

              <Box sx={{ height: { xs: 200, sm: 320 } }}>
                <Line
                  data={generateParticipationTrendData()}
                  options={{
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                      legend: {
                        display: true,
                        position: 'top' as const,
                      },
                      tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        padding: 12,
                        titleFont: { size: 14, weight: 'bold' },
                        bodyFont: { size: 13 },
                      },
                    },
                    scales: {
                      y: {
                        beginAtZero: true,
                        grid: {
                          color: 'rgba(0, 0, 0, 0.05)',
                        },
                      },
                      x: {
                        grid: {
                          display: false,
                        },
                      },
                    },
                  }}
                />
              </Box>
            </CardContent>
          </Card>
        </Box>

        {/* Chart Section - 채널별 성과 & ROI 추이 */}
        <Grid container spacing={{ xs: 2, sm: 6 }} sx={{ mb: { xs: 5, sm: 10 } }}>
          <Grid item xs={12} md={6}>
            <Typography variant="h5" sx={{ fontWeight: 700, mb: { xs: 3, sm: 6 }, fontSize: { xs: '1.125rem', sm: '1.5rem' } }}>
              📊 채널별 참여자
            </Typography>
            <Card elevation={0} sx={{ borderRadius: { xs: 3, sm: 4 }, boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)' }}>
              <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
                <Box sx={{ height: { xs: 200, sm: 320 } }}>
                  <Bar
                    data={generateChannelPerformanceData()}
                    options={{
                      responsive: true,
                      maintainAspectRatio: false,
                      plugins: {
                        legend: {
                          display: false,
                        },
                        tooltip: {
                          backgroundColor: 'rgba(0, 0, 0, 0.8)',
                          padding: 12,
                          titleFont: { size: 14, weight: 'bold' },
                          bodyFont: { size: 13 },
                        },
                      },
                      scales: {
                        y: {
                          beginAtZero: true,
                          grid: {
                            color: 'rgba(0, 0, 0, 0.05)',
                          },
                        },
                        x: {
                          grid: {
                            display: false,
                          },
                        },
                      },
                    }}
                  />
                </Box>
              </CardContent>
            </Card>
          </Grid>

          <Grid item xs={12} md={6}>
            <Typography variant="h5" sx={{ fontWeight: 700, mb: { xs: 3, sm: 6 }, fontSize: { xs: '1.125rem', sm: '1.5rem' } }}>
              💰 ROI 추이
            </Typography>
            <Card elevation={0} sx={{ borderRadius: { xs: 3, sm: 4 }, boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)' }}>
              <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
                <Box sx={{ height: { xs: 200, sm: 320 } }}>
                  <Line
                    data={generateRoiTrendData()}
                    options={{
                      responsive: true,
                      maintainAspectRatio: false,
                      plugins: {
                        legend: {
                          display: true,
                          position: 'top' as const,
                        },
                        tooltip: {
                          backgroundColor: 'rgba(0, 0, 0, 0.8)',
                          padding: 12,
                          titleFont: { size: 14, weight: 'bold' },
                          bodyFont: { size: 13 },
                        },
                      },
                      scales: {
                        y: {
                          beginAtZero: true,
                          grid: {
                            color: 'rgba(0, 0, 0, 0.05)',
                          },
                        },
                        x: {
                          grid: {
                            display: false,
                          },
                        },
                      },
                    }}
                  />
                </Box>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* ROI 상세 정보 */}
        <Box sx={{ mb: { xs: 5, sm: 10 } }}>
          <Typography variant="h5" sx={{ fontWeight: 700, mb: { xs: 3, sm: 6 }, fontSize: { xs: '1.125rem', sm: '1.5rem' } }}>
            💰 ROI 상세 분석
          </Typography>
          <Grid container spacing={{ xs: 2, sm: 4 }}>
            <Grid item xs={12} md={6}>
              <Card elevation={0} sx={{ borderRadius: { xs: 3, sm: 4 }, boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)' }}>
                <CardContent sx={{ p: { xs: 3, sm: 4 } }}>
                  <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>투자 비용</Typography>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant="body2" color="text.secondary">총 비용</Typography>
                    <Typography variant="body2" fontWeight={600}>
                      {analyticsData?.roi?.investment?.total?.toLocaleString() || 0}원
                    </Typography>
                  </Box>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant="body2" color="text.secondary">경품 비용</Typography>
                    <Typography variant="body2">
                      {analyticsData?.roi?.investment?.prizeCost?.toLocaleString() || 0}원
                    </Typography>
                  </Box>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant="body2" color="text.secondary">채널 비용</Typography>
                    <Typography variant="body2">
                      {analyticsData?.roi?.investment?.distribution?.toLocaleString() || 0}원
                    </Typography>
                  </Box>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography variant="body2" color="text.secondary">기타 비용</Typography>
                    <Typography variant="body2">
                      {((analyticsData?.roi?.investment?.contentCreation || 0) +
                        (analyticsData?.roi?.investment?.operation || 0)).toLocaleString()}원
                    </Typography>
                  </Box>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} md={6}>
              <Card elevation={0} sx={{ borderRadius: { xs: 3, sm: 4 }, boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)' }}>
                <CardContent sx={{ p: { xs: 3, sm: 4 } }}>
                  <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>예상 수익</Typography>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant="body2" color="text.secondary">매출 증가</Typography>
                    <Typography variant="body2" fontWeight={600}>
                      {analyticsData?.roi?.revenue?.total?.toLocaleString() || 0}원
                    </Typography>
                  </Box>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography variant="body2" color="text.secondary">신규고객 LTV</Typography>
                    <Typography variant="body2">
                      {analyticsData?.roi?.revenue?.newCustomerRevenue?.toLocaleString() || 0}원
                    </Typography>
                  </Box>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </Box>

        {/* 마지막 업데이트 정보 */}
        <Card elevation={0} sx={{ borderRadius: { xs: 3, sm: 4 }, boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)', bgcolor: colors.purpleLight }}>
          <CardContent sx={{ p: { xs: 3, sm: 4 } }}>
            <Typography variant="body2" color="text.secondary">
              🕐 마지막 업데이트: {formatDateTime(analyticsData?.dashboard?.lastUpdatedAt || '')}
            </Typography>
          </CardContent>
        </Card>
      </Container>
    </Box>
  );
}
