import { useState } from 'react';
import {
  Box,
  Container,
  Typography,
  Card,
  CardContent,
  Button,
  Grid,
  Radio,
  RadioGroup,
  FormControlLabel,
} from '@mui/material';
import { AutoAwesome, TrendingUp, Replay, Store, Campaign } from '@mui/icons-material';
import { EventObjective } from '../page';
import { eventApi } from '@/shared/api/eventApi';
import type { AiRecommendationRequest } from '@/shared/api/eventApi';

// 디자인 시스템 색상
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',
  },
};

interface ObjectiveOption {
  id: EventObjective;
  icon: React.ReactNode;
  title: string;
  description: string;
}

const objectives: ObjectiveOption[] = [
  {
    id: 'new_customer',
    icon: <Store sx={{ fontSize: 40 }} />,
    title: '신규 고객 유치',
    description: '새로운 고객을 확보하여 매장을 성장시키고 싶어요',
  },
  {
    id: 'revisit',
    icon: <Replay sx={{ fontSize: 40 }} />,
    title: '재방문 유도',
    description: '기존 고객의 재방문을 촉진하고 싶어요',
  },
  {
    id: 'sales',
    icon: <TrendingUp sx={{ fontSize: 40 }} />,
    title: '매출 증대',
    description: '단기간에 매출을 높이고 싶어요',
  },
  {
    id: 'awareness',
    icon: <Campaign sx={{ fontSize: 40 }} />,
    title: '인지도 향상',
    description: '브랜드나 매장 인지도를 높이고 싶어요',
  },
];

interface ObjectiveStepProps {
  onNext: (data: { objective: EventObjective; eventId: string }) => void;
}

// eventId 생성 함수
const generateEventId = () => {
  return `evt_${Date.now()}_${Math.random().toString(36).substring(7)}`;
};

// 쿠키 저장 함수
const setCookie = (name: string, value: string, days: number = 1) => {
  const expires = new Date();
  expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
};

// 쿠키 삭제 함수
const deleteCookie = (name: string) => {
  document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;
};

export default function ObjectiveStep({ onNext }: ObjectiveStepProps) {
  const [selected, setSelected] = useState<EventObjective | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  // Objective 한글 매핑
  const getObjectiveKorean = (objective: EventObjective): string => {
    const map: Record<EventObjective, string> = {
      'new_customer': '신규 고객 유치',
      'revisit': '재방문 유도',
      'sales': '매출 증대',
      'awareness': '인지도 향상',
    };
    return map[objective];
  };

  const handleNext = async () => {
    if (selected) {
      setIsLoading(true);

      try {
        // 이전 쿠키 삭제 (깨끗한 상태에서 시작)
        deleteCookie('eventId');
        deleteCookie('jobId');

        // 새로운 eventId 생성
        const eventId = generateEventId();
        console.log('🎉 ========================================');
        console.log('✅ 새로운 이벤트 ID 생성:', eventId);
        console.log('📋 선택된 목적:', selected);
        console.log('🎉 ========================================');

        // 쿠키에 저장
        setCookie('eventId', eventId, 1); // 1일 동안 유지
        console.log('🍪 쿠키에 eventId 저장 완료:', eventId);

        // localStorage에도 저장
        try {
          localStorage.setItem('eventId', eventId);
          console.log('💾 localStorage에 eventId 저장 완료:', eventId);
          console.log('📦 저장된 데이터 확인:', {
            eventId: eventId,
            objective: selected,
            timestamp: new Date().toISOString()
          });
        } catch (error) {
          console.error('❌ localStorage 저장 실패:', error);
        }

        // AI 추천 생성 요청 body 준비
        const aiRequest: AiRecommendationRequest = {
          objective: getObjectiveKorean(selected),
          storeInfo: {
            storeId: 'store_001',
            storeName: '홍길동 삼겹살',
            category: '음식점',
            description: '길동이가 직접 구워주는 삼겹살 맛집!',
          },
          region: '서울특별시 강남구',
          targetAudience: '20-30대 직장인',
          budget: 500000,
        };

        // AI 추천 생성 요청 API 호출 및 200 응답 대기
        console.log('🤖 AI 추천 생성 요청 시작:', eventId);
        console.log('📤 Request Body:', aiRequest);
        await eventApi.requestAiRecommendations(eventId, aiRequest);
        console.log('✅ AI 추천 생성 요청 성공 (200 응답 수신)');

        // 200 응답 받은 후 다음 단계로 이동
        onNext({ objective: selected, eventId });
      } catch (error) {
        console.error('❌ AI 추천 생성 요청 실패:', error);
        alert('AI 추천 생성 요청에 실패했습니다. 다시 시도해 주세요.');
      } finally {
        setIsLoading(false);
      }
    }
  };

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: 'background.default', pb: 20 }}>
      <Container maxWidth="md" sx={{ pt: { xs: 3, sm: 8 }, pb: { xs: 3, sm: 8 }, px: { xs: 1.5, sm: 6, md: 8 } }}>
        {/* Title Section */}
        <Box sx={{ mb: { xs: 3, sm: 10 }, textAlign: 'center' }}>
          <AutoAwesome sx={{ fontSize: { xs: 48, sm: 80 }, color: colors.purple, mb: { xs: 1.5, sm: 4 } }} />
          <Typography variant="h4" sx={{ fontWeight: 700, mb: { xs: 1.5, sm: 4 }, fontSize: { xs: '1.25rem', sm: '2rem' } }}>
            이벤트 목적을 선택해주세요
          </Typography>
          <Typography variant="body1" color="text.secondary" sx={{ fontSize: { xs: '0.8125rem', sm: '1.125rem' } }}>
            AI가 목적에 맞는 최적의 이벤트를 추천해드립니다
          </Typography>
        </Box>

        {/* Purpose Options */}
        <RadioGroup value={selected} onChange={(e) => setSelected(e.target.value as EventObjective)}>
          <Grid container spacing={{ xs: 1.5, sm: 6 }} sx={{ mb: { xs: 3, sm: 10 } }}>
            {objectives.map((objective) => (
              <Grid item xs={12} sm={6} key={objective.id}>
                <Card
                  elevation={0}
                  sx={{
                    cursor: 'pointer',
                    borderRadius: 4,
                    border: selected === objective.id ? 2 : 1,
                    borderColor: selected === objective.id ? colors.purple : 'divider',
                    bgcolor: selected === objective.id ? `${colors.purpleLight}40` : 'background.paper',
                    transition: 'all 0.2s',
                    boxShadow: selected === objective.id ? '0 4px 12px rgba(0, 0, 0, 0.15)' : '0 2px 8px rgba(0, 0, 0, 0.08)',
                    '&:hover': {
                      borderColor: colors.purple,
                      boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                      transform: 'translateY(-2px)',
                    },
                  }}
                  onClick={() => setSelected(objective.id)}
                >
                  <CardContent sx={{ p: { xs: 2, sm: 6 } }}>
                    <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: { xs: 1.5, sm: 3 } }}>
                      <Box sx={{ color: colors.purple }}>{objective.icon}</Box>
                      <Box sx={{ flex: 1 }}>
                        <Typography variant="h6" sx={{ fontWeight: 700, mb: { xs: 0.5, sm: 2 }, fontSize: { xs: '0.9375rem', sm: '1.25rem' } }}>
                          {objective.title}
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ fontSize: { xs: '0.8125rem', sm: '1rem' } }}>
                          {objective.description}
                        </Typography>
                      </Box>
                      <FormControlLabel
                        value={objective.id}
                        control={<Radio sx={{ color: selected === objective.id ? colors.purple : undefined }} />}
                        label=""
                        sx={{ m: 0 }}
                      />
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        </RadioGroup>

        {/* Info Box */}
        <Card
          elevation={0}
          sx={{
            mb: { xs: 3, sm: 10 },
            background: `linear-gradient(135deg, ${colors.purpleLight} 0%, ${colors.blue}20 100%)`,
            borderRadius: 4,
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
          }}
        >
          <CardContent sx={{ display: 'flex', gap: { xs: 1.5, sm: 3 }, p: { xs: 2, sm: 6 } }}>
            <AutoAwesome sx={{ color: colors.purple, fontSize: { xs: 20, sm: 28 } }} />
            <Typography variant="body2" sx={{ fontSize: { xs: '0.8125rem', sm: '1rem' }, lineHeight: 1.8, color: colors.gray[700] }}>
              선택하신 목적에 따라 AI가 업종, 지역, 계절 트렌드를 분석하여 가장 효과적인 이벤트를 추천합니다.
            </Typography>
          </CardContent>
        </Card>

        {/* Action Buttons */}
        <Box>
          <Button
            fullWidth
            variant="contained"
            size="large"
            disabled={!selected || isLoading}
            onClick={handleNext}
            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],
              },
            }}
          >
            {isLoading ? 'AI 추천 요청 중...' : '다음'}
          </Button>
        </Box>
      </Container>
    </Box>
  );
}
