import { useState, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import type { StudioState, StudioChannel, ContentFormat, AssetSourceType, MusicGenre, NarrationLanguage, NarrationVoice, GenerateOutputType } from '@/features/studio/types/studio';
import { DEFAULT_SOUND } from '@/features/studio/types/studio';
import ChannelFormatStep from './ChannelFormatStep';
import StrategySourceStep from './StrategySourceStep';
import SoundStudioStep from './SoundStudioStep';
import GeneratePreviewStep from './GeneratePreviewStep';
import BlogEditorStep from './BlogEditorStep';
import { Button } from '@/shared/ui/button';
import { PageContainer } from '@/shared/ui/page-container';

interface StepDef {
  key: string;
  label: string;
}

const VIDEO_STEPS: StepDef[] = [
  { key: 'channel', label: '채널 선택' },
  { key: 'strategy', label: '전략 선택' },
  { key: 'sound', label: '사운드' },
  { key: 'generate', label: '생성' },
];

const BLOG_STEPS: StepDef[] = [
  { key: 'channel', label: '채널 선택' },
  { key: 'strategy', label: '전략 선택' },
  { key: 'blog', label: '콘텐츠 생성' },
];

function isBlogChannel(channel: StudioChannel | null): boolean {
  return channel === 'naver_blog';
}

export default function StudioWizard() {
  const [step, setStep] = useState(0);
  const [state, setState] = useState<StudioState>({
    channel: null,
    format: null,
    pillarId: null,
    assetSources: [],
    sound: DEFAULT_SOUND,
    outputType: 'video',
  });

  const steps = useMemo(() => isBlogChannel(state.channel) ? BLOG_STEPS : VIDEO_STEPS, [state.channel]);

  const setChannel = useCallback((channel: StudioChannel | null) => {
    setState(s => ({
      ...s,
      channel,
      format: null,
      outputType: channel === 'naver_blog' ? 'image' : 'video',
    }));
    // blog/video 플로우 전환 시 step 초기화
    setStep(0);
  }, []);

  const setFormat = useCallback((format: ContentFormat | null) => {
    setState(s => ({ ...s, format }));
  }, []);

  const setPillar = useCallback((pillarId: string | null) => {
    setState(s => ({ ...s, pillarId }));
  }, []);

  const toggleAssetSource = useCallback((source: AssetSourceType) => {
    setState(s => ({
      ...s,
      assetSources: s.assetSources.includes(source)
        ? s.assetSources.filter(x => x !== source)
        : [...s.assetSources, source],
    }));
  }, []);

  const setGenre = useCallback((genre: MusicGenre) => {
    setState(s => ({ ...s, sound: { ...s.sound, genre, trackId: null } }));
  }, []);

  const setTrack = useCallback((trackId: string | null) => {
    setState(s => ({ ...s, sound: { ...s.sound, trackId } }));
  }, []);

  const setNarration = useCallback((enabled: boolean) => {
    setState(s => ({ ...s, sound: { ...s.sound, narrationEnabled: enabled } }));
  }, []);

  const setNarrationLang = useCallback((lang: NarrationLanguage) => {
    setState(s => ({ ...s, sound: { ...s.sound, narrationLanguage: lang } }));
  }, []);

  const setNarrationVoice = useCallback((voice: NarrationVoice) => {
    setState(s => ({ ...s, sound: { ...s.sound, narrationVoice: voice } }));
  }, []);

  const setSubtitle = useCallback((enabled: boolean) => {
    setState(s => ({ ...s, sound: { ...s.sound, subtitleEnabled: enabled } }));
  }, []);

  const setOutputType = useCallback((type: GenerateOutputType) => {
    setState(s => ({ ...s, outputType: type }));
  }, []);

  const currentStepKey = steps[step]?.key;

  const canProceed = (): boolean => {
    switch (currentStepKey) {
      case 'channel': return state.channel !== null && state.format !== null;
      case 'strategy': return state.pillarId !== null && state.assetSources.length > 0;
      case 'sound': return true;
      case 'generate': return true;
      case 'blog': return true;
      default: return false;
    }
  };

  return (
    <div className="min-h-screen pt-24 pb-32 px-6">
      <PageContainer className="max-w-5xl px-0">
        {/* Progress Bar */}
        <div className="flex items-center justify-center mb-12">
          {steps.map((s, i) => (
            <div key={s.key} className="flex items-center">
              <Button
                variant="ghost"
                onClick={() => i < step && setStep(i)}
                className={`h-auto p-0 gap-2 transition-all hover:bg-transparent ${i <= step ? 'cursor-pointer' : 'cursor-default'}`}
              >
                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-all ${
                  i < step
                    ? 'bg-gradient-to-r from-brand-purple to-brand-purple-deep text-white'
                    : i === step
                      ? 'border-2 border-brand-purple-vivid text-brand-purple-vivid bg-white'
                      : 'border-2 border-slate-200 text-slate-400 bg-white'
                }`}>
                  {i < step ? (
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                      <path d="M2 7L5.5 10.5L12 3.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  ) : (
                    i + 1
                  )}
                </div>
                <span className={`text-sm font-medium hidden md:inline ${
                  i <= step ? 'text-brand-navy' : 'text-slate-400'
                }`}>
                  {s.label}
                </span>
              </Button>

              {i < steps.length - 1 && (
                <div className={`w-12 md:w-20 h-1 mx-2 transition-colors ${
                  i < step ? 'bg-brand-purple-vivid' : 'bg-slate-200'
                }`} />
              )}
            </div>
          ))}
        </div>

        {/* Step Content */}
        <AnimatePresence mode="wait">
          <motion.div
            key={`${currentStepKey}-${step}`}
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -20 }}
            transition={{ duration: 0.3 }}
          >
            {currentStepKey === 'channel' && (
              <ChannelFormatStep
                selectedChannel={state.channel}
                selectedFormat={state.format}
                onChannelSelect={setChannel}
                onFormatSelect={setFormat}
              />
            )}
            {currentStepKey === 'strategy' && (
              <StrategySourceStep
                selectedPillar={state.pillarId}
                selectedSources={state.assetSources}
                onPillarSelect={setPillar}
                onSourceToggle={toggleAssetSource}
              />
            )}
            {currentStepKey === 'sound' && (
              <SoundStudioStep
                sound={state.sound}
                onGenreChange={setGenre}
                onTrackChange={setTrack}
                onNarrationToggle={setNarration}
                onLanguageChange={setNarrationLang}
                onVoiceChange={setNarrationVoice}
                onSubtitleToggle={setSubtitle}
              />
            )}
            {currentStepKey === 'generate' && (
              <GeneratePreviewStep
                studioState={state}
                outputType={state.outputType}
                onOutputTypeChange={setOutputType}
              />
            )}
            {currentStepKey === 'blog' && (
              <BlogEditorStep studioState={state} />
            )}
          </motion.div>
        </AnimatePresence>

        {/* Bottom Navigation */}
        <div className="flex items-center justify-between mt-12">
          <Button
            variant="outline"
            onClick={() => setStep(s => Math.max(0, s - 1))}
            disabled={step === 0}
            className="h-auto px-5 py-3 rounded-full text-sm font-medium text-slate-600 bg-white border-slate-200 shadow-[3px_4px_12px_rgba(0,0,0,0.06)] hover:bg-slate-50 disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ChevronLeft size={16} />
            이전
          </Button>

          {step < steps.length - 1 ? (
            <Button
              onClick={() => setStep(s => Math.min(steps.length - 1, s + 1))}
              disabled={!canProceed()}
              className="h-auto px-6 py-3 rounded-full text-sm font-medium text-white bg-gradient-to-r from-brand-purple to-brand-purple-deep shadow-md hover:shadow-lg transition-all disabled:opacity-40 disabled:cursor-not-allowed"
            >
              다음
              <ChevronRight size={16} />
            </Button>
          ) : (
            <div />
          )}
        </div>
      </PageContainer>
    </div>
  );
}
