'use client';

import { useFunnel } from '@use-funnel/browser';
import { useRouter } from 'next/navigation';
import ObjectiveStep from './steps/ObjectiveStep';
import LoadingStep from './steps/LoadingStep';
import RecommendationStep from './steps/RecommendationStep';
import ContentPreviewStep from './steps/ContentPreviewStep';
import ContentEditStep from './steps/ContentEditStep';
import ChannelStep from './steps/ChannelStep';
import ApprovalStep from './steps/ApprovalStep';
import type { AiRecommendationResult } from '@/shared/api/eventApi';

// 이벤트 생성 데이터 타입
export type EventObjective = 'new_customer' | 'revisit' | 'sales' | 'awareness';
export type BudgetLevel = 'low' | 'medium' | 'high';
export type EventMethod = 'online' | 'offline';

export interface EventData {
  eventDraftId?: number;
  eventId?: string;
  objective?: EventObjective;
  aiResult?: AiRecommendationResult;
  recommendation?: {
    recommendation: {
      optionNumber: number;
      concept: string;
      title: string;
      description: string;
      targetAudience: string;
      duration: {
        recommendedDays: number;
        recommendedPeriod?: string;
      };
      mechanics: {
        type: 'DISCOUNT' | 'GIFT' | 'STAMP' | 'EXPERIENCE' | 'LOTTERY' | 'COMBO';
        details: string;
      };
      promotionChannels: string[];
      estimatedCost: {
        min: number;
        max: number;
        breakdown?: {
          material?: number;
          promotion?: number;
          discount?: number;
        };
      };
      expectedMetrics: {
        newCustomers: { min: number; max: number };
        repeatVisits?: { min: number; max: number };
        revenueIncrease: { min: number; max: number };
        roi: { min: number; max: number };
        socialEngagement?: {
          estimatedPosts: number;
          estimatedReach: number;
        };
      };
      differentiator: string;
    };
    eventId: string;
  };
  contentPreview?: {
    imageStyle: string;
    images?: any[];
  };
  contentEdit?: {
    title: string;
    prize: string;
    guide: string;
  };
  channels?: string[];
}

export default function EventCreatePage() {
  const router = useRouter();

  const funnel = useFunnel<{
    objective: EventData;
    loading: EventData;
    recommendation: EventData;
    contentPreview: EventData;
    contentEdit: EventData;
    channel: EventData;
    approval: EventData;
  }>({
    id: 'event-creation',
    initial: {
      step: 'objective',
      context: {},
    },
  });

  const handleComplete = () => {
    // 이벤트 생성 완료 후 대시보드로 이동
    router.push('/');
  };

  return (
    <funnel.Render
      objective={({ history }) => (
        <ObjectiveStep
          onNext={({ objective, eventId }) => {
            history.push('loading', { objective, eventId });
          }}
        />
      )}
      loading={({ context, history }) => (
        <LoadingStep
          eventId={context.eventId!}
          onComplete={(aiResult) => {
            history.push('recommendation', { ...context, aiResult });
          }}
          onError={(error) => {
            console.error('❌ AI 추천 생성 실패:', error);
            alert(error);
            history.go(-1); // ObjectiveStep으로 돌아가기
          }}
        />
      )}
      recommendation={({ context, history }) => (
        <RecommendationStep
          eventId={context.eventId}
          aiResult={context.aiResult}
          onNext={(recommendation) => {
            history.push('channel', { ...context, recommendation });
          }}
          onBack={() => {
            history.go(-1);
          }}
        />
      )}
      channel={({ context, history }) => (
        <ChannelStep
          onNext={(channels) => {
            // 우리동네TV, 지니TV, SNS 중 하나라도 포함되어 있으면 contentPreview로
            const needsContent = channels.some((ch) =>
              ['uriTV', 'genieTV', 'sns'].includes(ch)
            );

            if (needsContent) {
              // localStorage에 이벤트 정보 저장
              const baseTrends = context.recommendation?.recommendation.promotionChannels || [];
              const requiredTrends = ['Samgyupsal', '삼겹살', 'Korean Pork BBQ'];
              // 중복 제거하면서 필수 trends 추가
              const allTrends = [...new Set([...requiredTrends, ...baseTrends])];

              const eventData = {
                eventDraftId: context.recommendation?.eventId || String(Date.now()), // eventId 사용
                eventTitle: context.recommendation?.recommendation.title || '',
                eventDescription: context.recommendation?.recommendation.description || '',
                industry: '',
                location: '',
                trends: allTrends,
                prize: '',
              };
              localStorage.setItem('eventCreationData', JSON.stringify(eventData));

              history.push('contentPreview', { ...context, channels });
            } else {
              history.push('approval', { ...context, channels });
            }
          }}
          onBack={() => {
            history.go(-1);
          }}
        />
      )}
      contentPreview={({ context, history }) => (
        <ContentPreviewStep
          eventId={context.recommendation?.eventId}
          eventTitle={context.recommendation?.recommendation.title}
          eventDescription={context.recommendation?.recommendation.description}
          onNext={(imageStyle, images) => {
            history.push('contentEdit', {
              ...context,
              contentPreview: { imageStyle, images },
            });
          }}
          onSkip={() => {
            history.push('approval', context);
          }}
          onBack={() => {
            history.go(-1);
          }}
        />
      )}
      contentEdit={({ context, history }) => (
        <ContentEditStep
          initialTitle={context.recommendation?.recommendation.title || ''}
          initialPrize={''}
          onNext={(contentEdit) => {
            history.push('approval', { ...context, contentEdit });
          }}
          onBack={() => {
            history.go(-1);
          }}
        />
      )}
      approval={({ context, history }) => (
        <ApprovalStep
          eventData={context}
          onApprove={handleComplete}
          onBack={() => {
            history.go(-1);
          }}
        />
      )}
    />
  );
}
