import { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Typography,
  Card,
  CardContent,
  Button,
  Checkbox,
  FormControlLabel,
  Chip,
  Grid,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Link,
} from '@mui/material';
import {
  ArrowBack,
  CheckCircle,
  RocketLaunch,
  Save,
  People,
  AttachMoney,
  TrendingUp,
} from '@mui/icons-material';
import { EventData } from '../page';
import { cardStyles, colors, responsiveText } from '@/shared/lib/button-styles';

interface EventCreationData {
  eventDraftId: string;
  eventTitle: string;
  eventDescription: string;
  industry: string;
  location: string;
  trends: string[];
  prize: string;
}

interface ApprovalStepProps {
  eventData: EventData;
  onApprove: () => void;
  onBack: () => void;
}

export default function ApprovalStep({ eventData, onApprove, onBack }: ApprovalStepProps) {
  const [agreeTerms, setAgreeTerms] = useState(false);
  const [termsDialogOpen, setTermsDialogOpen] = useState(false);
  const [successDialogOpen, setSuccessDialogOpen] = useState(false);
  const [isDeploying, setIsDeploying] = useState(false);
  const [localStorageData, setLocalStorageData] = useState<EventCreationData | null>(null);

  useEffect(() => {
    const storedData = localStorage.getItem('eventCreationData');
    if (storedData) {
      setLocalStorageData(JSON.parse(storedData));
    }
  }, []);

  const handleApprove = async () => {
    if (!agreeTerms) return;

    setIsDeploying(true);

    // API 호출 임시 주석처리 - 배포 성공 시뮬레이션
    /*
    try {
      // 1. 이벤트 생성 API 호출
      console.log('📞 Creating event with objective:', eventData.objective);

      // objective 매핑 (Frontend → Backend)
      const objectiveMap: Record<string, EventObjective> = {
        new_customer: 'CUSTOMER_ACQUISITION',
        revisit: 'Customer Retention',
        sales: 'Sales Promotion',
        awareness: 'awareness',
      };

      const backendObjective: EventObjective = (objectiveMap[
        eventData.objective || 'new_customer'
      ] || 'CUSTOMER_ACQUISITION') as EventObjective;

      const createResponse = await eventApi.createEvent({
        objective: backendObjective,
      });

      console.log('✅ Event created:', createResponse);

      if (createResponse.success && createResponse.data) {
        const eventId = createResponse.data.eventId;
        console.log('🎯 Event ID:', eventId);

        // 2. 이벤트 상세 정보 업데이트
        console.log('📞 Updating event details:', eventId);

        // 이벤트명 가져오기 (contentEdit.title 또는 recommendation.title)
        const eventName =
          eventData.contentEdit?.title ||
          eventData.recommendation?.recommendation?.title ||
          '이벤트';

        // 날짜 설정 (오늘부터 30일간)
        const today = new Date();
        const endDate = new Date(today);
        endDate.setDate(endDate.getDate() + 30);

        const startDateStr = today.toISOString().split('T')[0]; // YYYY-MM-DD
        const endDateStr = endDate.toISOString().split('T')[0];

        await eventApi.updateEvent(eventId, {
          eventName: eventName,
          description:
            eventData.contentEdit?.guide ||
            eventData.recommendation?.recommendation?.description ||
            '',
          startDate: startDateStr,
          endDate: endDateStr,
        });
        console.log('✅ Event details updated');

        // 채널명 매핑 (Frontend → Backend)
        const channelMap: Record<string, string[]> = {
          uriTV: ['URIDONGNETV'],
          ringoBiz: ['RINGOBIZ'],
          genieTV: ['GINITV'],
          sns: ['INSTAGRAM', 'NAVER', 'KAKAO'],
        };

        const apiChannels = eventData.channels?.flatMap((ch) => channelMap[ch] || []) || [];

        const distributionRequest = {
          eventId: eventId,
          title: eventName,
          description:
            eventData.contentEdit?.guide ||
            eventData.recommendation?.recommendation?.description ||
            '',
          imageUrl: '', // TODO: 이미지 URL 연동 필요
          channels: apiChannels,
          channelSettings: {},
        };

        console.log('🚀 Distributing event:', distributionRequest);

        const response = await fetch(
          `${DISTRIBUTION_API_BASE_URL}/api/v1/distribution/distribute`,
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(distributionRequest),
          }
        );

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || '배포 중 오류가 발생했습니다');
        }

        const data = await response.json();
        console.log('✅ Distribution completed:', data);

        setIsDeploying(false);
        setSuccessDialogOpen(true);
      } else {
        throw new Error('Event creation failed: No event ID returned');
      }
    } catch (error) {
      console.error('❌ Event deployment failed:', error);
      setIsDeploying(false);
      alert('이벤트 배포에 실패했습니다. 다시 시도해 주세요.');
    }
    */

    // 배포 시뮬레이션 (2초 후 성공)
    setTimeout(() => {
      setIsDeploying(false);
      setSuccessDialogOpen(true);
    }, 2000);
  };

  const handleSaveDraft = () => {
    // TODO: 임시저장 API 연동
    alert('임시저장되었습니다');
  };

  const getChannelNames = (channels?: string[]) => {
    const channelMap: Record<string, string> = {
      uriTV: '우리동네TV',
      ringoBiz: '링고비즈',
      genieTV: '지니TV',
      sns: 'SNS',
    };

    return channels?.map((ch) => channelMap[ch] || ch) || [];
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        bgcolor: colors.gray[50],
        pt: { xs: 5, sm: 8 },
        pb: { xs: 3, sm: 10 },
      }}
    >
      <Container
        maxWidth="lg"
        sx={{ pt: { xs: 4, sm: 8 }, pb: { xs: 3, sm: 6 }, px: { xs: 2, sm: 4, md: 8 } }}
      >
        {/* Header */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: { xs: 1.5, sm: 3 },
            mb: { xs: 3, sm: 8 },
          }}
        >
          <IconButton onClick={onBack} sx={{ width: 40, height: 40 }}>
            <ArrowBack sx={{ fontSize: 20 }} />
          </IconButton>
          <Typography variant="h5" sx={{ ...responsiveText.h3, fontWeight: 700 }}>
            최종 승인
          </Typography>
        </Box>

        {/* Title Section */}
        <Box sx={{ textAlign: 'center', mb: { xs: 4, sm: 10 } }}>
          <CheckCircle sx={{ fontSize: 64, color: colors.purple, mb: 2 }} />
          <Typography variant="h5" sx={{ ...responsiveText.h3, fontWeight: 700, mb: 2 }}>
            이벤트를 확인해주세요
          </Typography>
          <Typography variant="body1" color="text.secondary" sx={{ ...responsiveText.body1 }}>
            모든 정보를 검토한 후 배포하세요
          </Typography>
        </Box>

        {/* Event Summary Statistics */}
        <Grid container spacing={{ xs: 2, sm: 3, md: 4 }} sx={{ mb: { xs: 4, sm: 10 } }}>
          <Grid item xs={12} sm={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.purpleLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 4 }, px: { xs: 2, sm: 3 } }}>
                <CheckCircle
                  sx={{
                    fontSize: 32,
                    color: colors.gray[900],
                    mb: 1,
                    filter: 'drop-shadow(0px 2px 4px rgba(0,0,0,0.2))',
                  }}
                />
                <Typography
                  variant="body2"
                  sx={{
                    color: colors.gray[700],
                    fontSize: '0.875rem',
                    mb: 1,
                    textShadow: '0px 1px 2px rgba(0,0,0,0.1)',
                  }}
                >
                  이벤트 제목
                </Typography>
                <Typography
                  variant="h6"
                  sx={{
                    fontWeight: 700,
                    color: colors.gray[900],
                    fontSize: { xs: '0.875rem', sm: '1rem' },
                    textShadow: '0px 2px 4px rgba(0,0,0,0.15)',
                    wordBreak: 'keep-all',
                  }}
                >
                  {localStorageData?.eventTitle ||
                    eventData.recommendation?.recommendation.title ||
                    '이벤트 제목'}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.blue} 0%, ${colors.blueLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 4 }, px: { xs: 2, sm: 3 } }}>
                <People
                  sx={{
                    fontSize: { xs: 28, sm: 32 },
                    color: colors.gray[900],
                    mb: 1,
                    filter: 'drop-shadow(0px 2px 4px rgba(0,0,0,0.2))',
                  }}
                />
                <Typography
                  variant="body2"
                  sx={{
                    color: colors.gray[700],
                    fontSize: { xs: '0.75rem', sm: '0.875rem' },
                    mb: 1,
                    textShadow: '0px 1px 2px rgba(0,0,0,0.1)',
                  }}
                >
                  목표 참여자
                </Typography>
                <Typography
                  variant="h4"
                  sx={{
                    fontWeight: 700,
                    color: colors.gray[900],
                    fontSize: { xs: '1.25rem', sm: '1.75rem' },
                    textShadow: '0px 2px 4px rgba(0,0,0,0.15)',
                  }}
                >
                  {eventData.recommendation?.recommendation.expectedMetrics.newCustomers.max || 0}
                  <Typography
                    component="span"
                    sx={{
                      fontSize: { xs: '0.875rem', sm: '1rem' },
                      ml: 0.5,
                      color: colors.gray[900],
                      textShadow: '0px 2px 4px rgba(0,0,0,0.15)',
                    }}
                  >
                    명
                  </Typography>
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.orange} 0%, ${colors.orangeLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 4 }, px: { xs: 2, sm: 3 } }}>
                <AttachMoney
                  sx={{
                    fontSize: { xs: 28, sm: 32 },
                    color: colors.gray[900],
                    mb: 1,
                    filter: 'drop-shadow(0px 2px 4px rgba(0,0,0,0.2))',
                  }}
                />
                <Typography
                  variant="body2"
                  sx={{
                    color: colors.gray[700],
                    fontSize: { xs: '0.75rem', sm: '0.875rem' },
                    mb: 1,
                    textShadow: '0px 1px 2px rgba(0,0,0,0.1)',
                  }}
                >
                  예상 비용
                </Typography>
                <Typography
                  variant="h4"
                  sx={{
                    fontWeight: 700,
                    color: colors.gray[900],
                    fontSize: { xs: '1.25rem', sm: '1.75rem' },
                    textShadow: '0px 2px 4px rgba(0,0,0,0.15)',
                  }}
                >
                  {(
                    (eventData.recommendation?.recommendation.estimatedCost.max || 0) / 10000
                  ).toFixed(0)}
                  <Typography
                    component="span"
                    sx={{
                      fontSize: { xs: '0.875rem', sm: '1rem' },
                      ml: 0.5,
                      color: colors.gray[900],
                      textShadow: '0px 2px 4px rgba(0,0,0,0.15)',
                    }}
                  >
                    만원
                  </Typography>
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <Card
              elevation={0}
              sx={{
                ...cardStyles.default,
                background: `linear-gradient(135deg, ${colors.mint} 0%, ${colors.mintLight} 100%)`,
                borderColor: 'transparent',
              }}
            >
              <CardContent sx={{ textAlign: 'center', py: { xs: 3, sm: 4 }, px: { xs: 2, sm: 3 } }}>
                <TrendingUp
                  sx={{
                    fontSize: { xs: 28, sm: 32 },
                    color: colors.gray[900],
                    mb: 1,
                    filter: 'drop-shadow(0px 2px 4px rgba(0,0,0,0.2))',
                  }}
                />
                <Typography
                  variant="body2"
                  sx={{
                    color: colors.gray[700],
                    fontSize: { xs: '0.75rem', sm: '0.875rem' },
                    mb: 1,
                    textShadow: '0px 1px 2px rgba(0,0,0,0.1)',
                  }}
                >
                  예상 ROI
                </Typography>
                <Typography
                  variant="h4"
                  sx={{
                    fontWeight: 700,
                    color: colors.gray[900],
                    fontSize: { xs: '1.25rem', sm: '1.75rem' },
                    textShadow: '0px 2px 4px rgba(0,0,0,0.15)',
                  }}
                >
                  {eventData.recommendation?.recommendation.expectedMetrics.roi.max || 0}%
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* Event Details */}
        <Typography variant="h6" sx={{ ...responsiveText.h4, fontWeight: 700, mb: 6 }}>
          이벤트 상세
        </Typography>

        <Card elevation={0} sx={{ ...cardStyles.default, mb: 4 }}>
          <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
            <Typography
              variant="caption"
              color="text.secondary"
              sx={{ ...responsiveText.body2, fontSize: { xs: '0.75rem', sm: '0.875rem' } }}
            >
              이벤트 제목
            </Typography>
            <Typography
              variant="body1"
              sx={{ ...responsiveText.body1, fontWeight: 600, mt: 1, wordBreak: 'keep-all' }}
            >
              {localStorageData?.eventTitle ||
                eventData.recommendation?.recommendation.title ||
                '이벤트 제목'}
            </Typography>
          </CardContent>
        </Card>

        <Card elevation={0} sx={{ ...cardStyles.default, mb: 4 }}>
          <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
            <Typography
              variant="caption"
              color="text.secondary"
              sx={{ ...responsiveText.body2, fontSize: { xs: '0.75rem', sm: '0.875rem' } }}
            >
              경품
            </Typography>
            <Typography
              variant="body1"
              sx={{ ...responsiveText.body1, fontWeight: 600, mt: 1, wordBreak: 'keep-all' }}
            >
              {localStorageData?.prize ||
                eventData.recommendation?.recommendation.mechanics.details ||
                ''}
            </Typography>
          </CardContent>
        </Card>

        <Card elevation={0} sx={{ ...cardStyles.default, mb: { xs: 4, sm: 10 } }}>
          <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
            <Typography
              variant="caption"
              color="text.secondary"
              sx={{ ...responsiveText.body2, fontSize: { xs: '0.75rem', sm: '0.875rem' } }}
            >
              참여 방법
            </Typography>
            <Typography
              variant="body1"
              sx={{ ...responsiveText.body1, fontWeight: 600, mt: 1, wordBreak: 'keep-all' }}
            >
              {localStorageData?.eventDescription ||
                eventData.recommendation?.recommendation.mechanics.details ||
                ''}
            </Typography>
          </CardContent>
        </Card>

        {/* Distribution Channels */}
        <Typography variant="h6" sx={{ ...responsiveText.h4, fontWeight: 700, mb: 6 }}>
          배포 채널
        </Typography>

        <Card elevation={0} sx={{ ...cardStyles.default, mb: { xs: 4, sm: 10 } }}>
          <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: { xs: 1.5, sm: 2 } }}>
              {getChannelNames(eventData.channels).map((channel) => (
                <Chip
                  key={channel}
                  label={channel}
                  sx={{
                    bgcolor: colors.purple,
                    color: 'white',
                    fontWeight: 600,
                    fontSize: { xs: '0.75rem', sm: '0.875rem' },
                    px: { xs: 1.5, sm: 2 },
                    py: { xs: 2, sm: 2.5 },
                  }}
                />
              ))}
            </Box>
          </CardContent>
        </Card>

        {/* Terms Agreement */}
        <Card
          elevation={0}
          sx={{ ...cardStyles.default, bgcolor: colors.gray[50], mb: { xs: 4, sm: 10 } }}
        >
          <CardContent sx={{ p: { xs: 3, sm: 6 } }}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={agreeTerms}
                  onChange={(e) => setAgreeTerms(e.target.checked)}
                  sx={{
                    color: colors.purple,
                    '&.Mui-checked': {
                      color: colors.purple,
                    },
                  }}
                />
              }
              label={
                <Typography variant="body2" sx={{ ...responsiveText.body1, fontWeight: 400 }}>
                  이벤트 약관 및 개인정보 처리방침에 동의합니다{' '}
                </Typography>
              }
            />
            <Link
              component="button"
              variant="body2"
              onClick={() => setTermsDialogOpen(true)}
              sx={{ ...responsiveText.body2, ml: 4, mt: 2, fontWeight: 600, color: colors.purple }}
            >
              약관 보기
            </Link>
          </CardContent>
        </Card>

        {/* Action Buttons */}
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: { xs: 2, sm: 4 } }}>
          <Button
            fullWidth
            variant="contained"
            size="large"
            disabled={!agreeTerms || isDeploying}
            onClick={handleApprove}
            startIcon={isDeploying ? null : <RocketLaunch fontSize="small" />}
            sx={{
              py: { xs: 1.5, sm: 3 },
              borderRadius: 3,
              fontSize: { xs: '0.875rem', sm: '1rem' },
              fontWeight: 700,
              background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.pink} 100%)`,
              '&:hover': {
                background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.pink} 100%)`,
                opacity: 0.9,
              },
              '&:disabled': {
                background: colors.gray[300],
              },
            }}
          >
            {isDeploying ? '배포 중...' : '배포하기'}
          </Button>
          <Button
            fullWidth
            variant="outlined"
            size="large"
            onClick={handleSaveDraft}
            startIcon={<Save fontSize="small" />}
            sx={{
              py: { xs: 1.5, sm: 3 },
              borderRadius: 3,
              fontSize: { xs: '0.875rem', sm: '1rem' },
              fontWeight: 600,
              borderWidth: 2,
              borderColor: colors.gray[300],
              color: colors.gray[700],
              '&:hover': {
                borderWidth: 2,
                borderColor: colors.gray[400],
                bgcolor: colors.gray[50],
              },
            }}
          >
            임시저장
          </Button>
        </Box>
      </Container>

      {/* Terms Dialog */}
      <Dialog
        open={termsDialogOpen}
        onClose={() => setTermsDialogOpen(false)}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 4,
          },
        }}
      >
        <DialogTitle sx={{ ...responsiveText.h3, fontWeight: 700, p: 6, pb: 4 }}>
          이벤트 약관
        </DialogTitle>
        <DialogContent sx={{ px: 6, pb: 6 }}>
          <Typography variant="h6" sx={{ ...responsiveText.h4, fontWeight: 700, mb: 3 }}>
            제1조 (목적)
          </Typography>
          <Typography
            variant="body2"
            sx={{ ...responsiveText.body1, mb: 6, color: colors.gray[700] }}
          >
            본 약관은 KT AI 이벤트 마케팅 서비스를 통해 진행되는 이벤트의 참여 및 개인정보 처리에
            관한 사항을 규정합니다.
          </Typography>

          <Typography variant="h6" sx={{ ...responsiveText.h4, fontWeight: 700, mb: 3 }}>
            제2조 (개인정보 수집 및 이용)
          </Typography>
          <Typography
            variant="body2"
            sx={{ ...responsiveText.body1, mb: 2, color: colors.gray[700] }}
          >
            수집 항목: 이름, 전화번호, 이메일
          </Typography>
          <Typography
            variant="body2"
            sx={{ ...responsiveText.body1, mb: 2, color: colors.gray[700] }}
          >
            이용 목적: 이벤트 참여 확인 및 경품 제공
          </Typography>
          <Typography
            variant="body2"
            sx={{ ...responsiveText.body1, mb: 6, color: colors.gray[700] }}
          >
            보유 기간: 이벤트 종료 후 6개월
          </Typography>

          <Typography variant="h6" sx={{ ...responsiveText.h4, fontWeight: 700, mb: 3 }}>
            제3조 (당첨자 발표)
          </Typography>
          <Typography variant="body2" sx={{ ...responsiveText.body1, color: colors.gray[700] }}>
            당첨자는 이벤트 종료 후 7일 이내 개별 연락 드립니다.
          </Typography>
        </DialogContent>
        <DialogActions sx={{ p: 6, pt: 4 }}>
          <Button
            fullWidth
            onClick={() => setTermsDialogOpen(false)}
            variant="contained"
            sx={{
              py: 3,
              borderRadius: 3,
              fontSize: '1rem',
              fontWeight: 700,
              background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.pink} 100%)`,
              '&:hover': {
                background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.pink} 100%)`,
                opacity: 0.9,
              },
            }}
          >
            확인
          </Button>
        </DialogActions>
      </Dialog>

      {/* Success Dialog */}
      <Dialog
        open={successDialogOpen}
        onClose={() => {
          setSuccessDialogOpen(false);
          onApprove();
        }}
        PaperProps={{
          sx: {
            borderRadius: 4,
          },
        }}
      >
        <DialogContent sx={{ textAlign: 'center', py: 10, px: 8 }}>
          <CheckCircle sx={{ fontSize: 80, color: colors.purple, mb: 4 }} />
          <Typography variant="h5" sx={{ fontSize: '1.5rem', fontWeight: 700, mb: 3 }}>
            배포 완료!
          </Typography>
          <Typography
            variant="body1"
            color="text.secondary"
            sx={{ fontSize: '1rem', mb: { xs: 3, sm: 8 } }}
          >
            이벤트가 성공적으로 배포되었습니다.
            <br />
            실시간으로 참여자를 확인할 수 있습니다.
          </Typography>
          <Button
            fullWidth
            variant="contained"
            size="large"
            onClick={() => {
              setSuccessDialogOpen(false);
              onApprove();
            }}
            sx={{
              py: 3,
              borderRadius: 3,
              fontSize: '1rem',
              fontWeight: 700,
              background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.pink} 100%)`,
              '&:hover': {
                background: `linear-gradient(135deg, ${colors.purple} 0%, ${colors.pink} 100%)`,
                opacity: 0.9,
              },
            }}
          >
            대시보드로 이동
          </Button>
        </DialogContent>
      </Dialog>
    </Box>
  );
}
