import { useEffect, useState } from "react";
import { clampTitle, clampSecondaryTitle } from "@/shared/lib/title";

interface RefAudio {
  id: string;
  name: string;
  path: string;
  ref_text: string;
  duration_sec: number;
  created_at: number;
}

interface UseHomePersistenceOptions {
  isAuthLoading: boolean;
  storageKey: string;
  text: string;
  setText: React.Dispatch<React.SetStateAction<string>>;
  videoTitle: string;
  setVideoTitle: React.Dispatch<React.SetStateAction<string>>;
  videoSecondaryTitle: string;
  setVideoSecondaryTitle: React.Dispatch<React.SetStateAction<string>>;
  ttsMode: 'edgetts' | 'voiceclone';
  setTtsMode: React.Dispatch<React.SetStateAction<'edgetts' | 'voiceclone'>>;
  voice: string;
  setVoice: React.Dispatch<React.SetStateAction<string>>;
  textLang: string;
  setTextLang: React.Dispatch<React.SetStateAction<string>>;
  selectedMaterials: string[];
  setSelectedMaterials: React.Dispatch<React.SetStateAction<string[]>>;
  selectedSubtitleStyleId: string;
  setSelectedSubtitleStyleId: React.Dispatch<React.SetStateAction<string>>;
  selectedTitleStyleId: string;
  setSelectedTitleStyleId: React.Dispatch<React.SetStateAction<string>>;
  selectedSecondaryTitleStyleId: string;
  setSelectedSecondaryTitleStyleId: React.Dispatch<React.SetStateAction<string>>;
  subtitleFontSize: number;
  setSubtitleFontSize: React.Dispatch<React.SetStateAction<number>>;
  titleFontSize: number;
  setTitleFontSize: React.Dispatch<React.SetStateAction<number>>;
  secondaryTitleFontSize: number;
  setSecondaryTitleFontSize: React.Dispatch<React.SetStateAction<number>>;
  setSubtitleSizeLocked: React.Dispatch<React.SetStateAction<boolean>>;
  setTitleSizeLocked: React.Dispatch<React.SetStateAction<boolean>>;
  setSecondaryTitleSizeLocked: React.Dispatch<React.SetStateAction<boolean>>;
  titleTopMargin: number;
  setTitleTopMargin: React.Dispatch<React.SetStateAction<number>>;
  secondaryTitleTopMargin: number;
  setSecondaryTitleTopMargin: React.Dispatch<React.SetStateAction<number>>;
  titleDisplayMode: 'short' | 'persistent';
  setTitleDisplayMode: React.Dispatch<React.SetStateAction<'short' | 'persistent'>>;
  subtitleBottomMargin: number;
  setSubtitleBottomMargin: React.Dispatch<React.SetStateAction<number>>;
  outputAspectRatio: '9:16' | '16:9';
  setOutputAspectRatio: React.Dispatch<React.SetStateAction<'9:16' | '16:9'>>;
  lipsyncModelMode: 'default' | 'fast' | 'advanced';
  setLipsyncModelMode: React.Dispatch<React.SetStateAction<'default' | 'fast' | 'advanced'>>;
  selectedBgmId: string;
  setSelectedBgmId: React.Dispatch<React.SetStateAction<string>>;
  bgmVolume: number;
  setBgmVolume: React.Dispatch<React.SetStateAction<number>>;
  enableBgm: boolean;
  setEnableBgm: React.Dispatch<React.SetStateAction<boolean>>;
  selectedVideoId: string | null;
  setSelectedVideoId: React.Dispatch<React.SetStateAction<string | null>>;
  selectedRefAudio: RefAudio | null;
  selectedAudioId: string | null;
  setSelectedAudioId: React.Dispatch<React.SetStateAction<string | null>>;
  speed: number;
  setSpeed: React.Dispatch<React.SetStateAction<number>>;
  emotion: string;
  setEmotion: React.Dispatch<React.SetStateAction<string>>;
}

export const useHomePersistence = ({
  isAuthLoading,
  storageKey,
  text,
  setText,
  videoTitle,
  setVideoTitle,
  videoSecondaryTitle,
  setVideoSecondaryTitle,
  ttsMode,
  setTtsMode,
  voice,
  setVoice,
  textLang,
  setTextLang,
  selectedMaterials,
  setSelectedMaterials,
  selectedSubtitleStyleId,
  setSelectedSubtitleStyleId,
  selectedTitleStyleId,
  setSelectedTitleStyleId,
  selectedSecondaryTitleStyleId,
  setSelectedSecondaryTitleStyleId,
  subtitleFontSize,
  setSubtitleFontSize,
  titleFontSize,
  setTitleFontSize,
  secondaryTitleFontSize,
  setSecondaryTitleFontSize,
  setSubtitleSizeLocked,
  setTitleSizeLocked,
  setSecondaryTitleSizeLocked,
  titleTopMargin,
  setTitleTopMargin,
  secondaryTitleTopMargin,
  setSecondaryTitleTopMargin,
  titleDisplayMode,
  setTitleDisplayMode,
  subtitleBottomMargin,
  setSubtitleBottomMargin,
  outputAspectRatio,
  setOutputAspectRatio,
  lipsyncModelMode,
  setLipsyncModelMode,
  selectedBgmId,
  setSelectedBgmId,
  bgmVolume,
  setBgmVolume,
  enableBgm,
  setEnableBgm,
  selectedVideoId,
  setSelectedVideoId,
  selectedRefAudio,
  selectedAudioId,
  setSelectedAudioId,
  speed,
  setSpeed,
  emotion,
  setEmotion,
}: UseHomePersistenceOptions) => {
  const [isRestored, setIsRestored] = useState(false);

  useEffect(() => {
    if (isAuthLoading) return;

    const savedText = localStorage.getItem(`vigent_${storageKey}_text`);
    const savedTitle = localStorage.getItem(`vigent_${storageKey}_title`);
    const savedSecondaryTitle = localStorage.getItem(`vigent_${storageKey}_secondaryTitle`);
    const savedTtsMode = localStorage.getItem(`vigent_${storageKey}_ttsMode`);
    const savedVoice = localStorage.getItem(`vigent_${storageKey}_voice`);
    const savedTextLang = localStorage.getItem(`vigent_${storageKey}_textLang`);
    const savedMaterial = localStorage.getItem(`vigent_${storageKey}_material`);
    const savedSubtitleStyle = localStorage.getItem(`vigent_${storageKey}_subtitleStyle`);
    const savedTitleStyle = localStorage.getItem(`vigent_${storageKey}_titleStyle`);
    const savedSecondaryTitleStyle = localStorage.getItem(`vigent_${storageKey}_secondaryTitleStyle`);
    const savedSubtitleFontSize = localStorage.getItem(`vigent_${storageKey}_subtitleFontSize`);
    const savedTitleFontSize = localStorage.getItem(`vigent_${storageKey}_titleFontSize`);
    const savedSecondaryTitleFontSize = localStorage.getItem(`vigent_${storageKey}_secondaryTitleFontSize`);
    const savedBgmId = localStorage.getItem(`vigent_${storageKey}_bgmId`);
    const savedSelectedVideoId = localStorage.getItem(`vigent_${storageKey}_latestGeneratedVideoId`)
      || localStorage.getItem(`vigent_${storageKey}_selectedVideoId`);
    const savedSelectedAudioId = localStorage.getItem(`vigent_${storageKey}_selectedAudioId`);
    const savedBgmVolume = localStorage.getItem(`vigent_${storageKey}_bgmVolume`);
    const savedEnableBgm = localStorage.getItem(`vigent_${storageKey}_enableBgm`);
    const savedTitleTopMargin = localStorage.getItem(`vigent_${storageKey}_titleTopMargin`);
    const savedSecondaryTitleTopMargin = localStorage.getItem(`vigent_${storageKey}_secondaryTitleTopMargin`);
    const savedTitleDisplayMode = localStorage.getItem(`vigent_${storageKey}_titleDisplayMode`);
    const savedSubtitleBottomMargin = localStorage.getItem(`vigent_${storageKey}_subtitleBottomMargin`);
    const savedOutputAspectRatio = localStorage.getItem(`vigent_${storageKey}_outputAspectRatio`);
    const savedLipsyncModelMode = localStorage.getItem(`vigent_${storageKey}_lipsyncModelMode`);
    const savedSpeed = localStorage.getItem(`vigent_${storageKey}_speed`);
    const savedEmotion = localStorage.getItem(`vigent_${storageKey}_emotion`);

    setText(savedText || "大家好，欢迎来到我的频道，今天给大家分享一些有趣的内容。");
    setVideoTitle(savedTitle ? clampTitle(savedTitle) : "");
    setVideoSecondaryTitle(savedSecondaryTitle ? clampSecondaryTitle(savedSecondaryTitle) : "");
    setTtsMode((savedTtsMode as 'edgetts' | 'voiceclone') || 'edgetts');
    setVoice(savedVoice || "zh-CN-YunxiNeural");
    if (savedTextLang) setTextLang(savedTextLang);

    if (savedMaterial) {
      try {
        const parsed = JSON.parse(savedMaterial);
        if (Array.isArray(parsed)) {
          setSelectedMaterials(parsed);
        } else {
          setSelectedMaterials([savedMaterial]);
        }
      } catch {
        // 旧格式: 单字符串
        setSelectedMaterials([savedMaterial]);
      }
    }
    if (savedSubtitleStyle) setSelectedSubtitleStyleId(savedSubtitleStyle);
    if (savedTitleStyle) setSelectedTitleStyleId(savedTitleStyle);
    if (savedSecondaryTitleStyle) setSelectedSecondaryTitleStyleId(savedSecondaryTitleStyle);

    if (savedSubtitleFontSize) {
      const parsed = parseInt(savedSubtitleFontSize, 10);
      if (!Number.isNaN(parsed)) {
        setSubtitleFontSize(parsed);
        setSubtitleSizeLocked(true);
      }
    }

    if (savedTitleFontSize) {
      const parsed = parseInt(savedTitleFontSize, 10);
      if (!Number.isNaN(parsed)) {
        setTitleFontSize(parsed);
        setTitleSizeLocked(true);
      }
    }

    if (savedSecondaryTitleFontSize) {
      const parsed = parseInt(savedSecondaryTitleFontSize, 10);
      if (!Number.isNaN(parsed)) {
        setSecondaryTitleFontSize(parsed);
        setSecondaryTitleSizeLocked(true);
      }
    }

    if (savedBgmId) setSelectedBgmId(savedBgmId);
    if (savedBgmVolume) setBgmVolume(parseFloat(savedBgmVolume));
    if (savedEnableBgm !== null) setEnableBgm(savedEnableBgm === 'true');
    if (savedSelectedVideoId) setSelectedVideoId(savedSelectedVideoId);
    // 消费后清除跨页面共享标记，避免反复覆盖
    localStorage.removeItem(`vigent_${storageKey}_latestGeneratedVideoId`);
    if (savedSelectedAudioId) setSelectedAudioId(savedSelectedAudioId);

    if (savedTitleTopMargin) {
      const parsed = parseInt(savedTitleTopMargin, 10);
      if (!Number.isNaN(parsed)) setTitleTopMargin(parsed);
    }
    if (savedSecondaryTitleTopMargin) {
      const parsed = parseInt(savedSecondaryTitleTopMargin, 10);
      if (!Number.isNaN(parsed)) setSecondaryTitleTopMargin(parsed);
    }
    if (savedTitleDisplayMode === 'short' || savedTitleDisplayMode === 'persistent') {
      setTitleDisplayMode(savedTitleDisplayMode);
    }
    if (savedSubtitleBottomMargin) {
      const parsed = parseInt(savedSubtitleBottomMargin, 10);
      if (!Number.isNaN(parsed)) setSubtitleBottomMargin(parsed);
    }

    if (savedOutputAspectRatio === '9:16' || savedOutputAspectRatio === '16:9') {
      setOutputAspectRatio(savedOutputAspectRatio);
    }

    if (
      savedLipsyncModelMode === 'default'
      || savedLipsyncModelMode === 'fast'
      || savedLipsyncModelMode === 'advanced'
    ) {
      setLipsyncModelMode(savedLipsyncModelMode);
    }

    if (savedSpeed) {
      const parsed = parseFloat(savedSpeed);
      if (!Number.isNaN(parsed)) setSpeed(parsed);
    }

    if (savedEmotion) setEmotion(savedEmotion);

    // eslint-disable-next-line react-hooks/set-state-in-effect
    setIsRestored(true);
  }, [
    isAuthLoading,
    setBgmVolume,
    setEnableBgm,
    setSelectedBgmId,
    setSelectedMaterials,
    setSelectedSubtitleStyleId,
    setSelectedTitleStyleId,
    setSelectedSecondaryTitleStyleId,
    setSelectedVideoId,
    setSelectedAudioId,
    setSpeed,
    setEmotion,
    setSubtitleFontSize,
    setSubtitleSizeLocked,
    setText,
    setTextLang,
    setTitleFontSize,
    setTitleSizeLocked,
    setSecondaryTitleFontSize,
    setSecondaryTitleSizeLocked,
    setTitleTopMargin,
    setSecondaryTitleTopMargin,
    setTitleDisplayMode,
    setSubtitleBottomMargin,
    setOutputAspectRatio,
    setLipsyncModelMode,
    setTtsMode,
    setVideoTitle,
    setVideoSecondaryTitle,
    setVoice,
    storageKey,
  ]);

  useEffect(() => {
    if (!isRestored) return;
    const timeout = setTimeout(() => {
      localStorage.setItem(`vigent_${storageKey}_text`, text);
    }, 300);
    return () => clearTimeout(timeout);
  }, [text, storageKey, isRestored]);

  useEffect(() => {
    if (!isRestored) return;
    const timeout = setTimeout(() => {
      localStorage.setItem(`vigent_${storageKey}_title`, videoTitle);
    }, 300);
    return () => clearTimeout(timeout);
  }, [videoTitle, storageKey, isRestored]);

  useEffect(() => {
    if (!isRestored) return;
    const timeout = setTimeout(() => {
      localStorage.setItem(`vigent_${storageKey}_secondaryTitle`, videoSecondaryTitle);
    }, 300);
    return () => clearTimeout(timeout);
  }, [videoSecondaryTitle, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) localStorage.setItem(`vigent_${storageKey}_ttsMode`, ttsMode);
  }, [ttsMode, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) localStorage.setItem(`vigent_${storageKey}_voice`, voice);
  }, [voice, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) localStorage.setItem(`vigent_${storageKey}_textLang`, textLang);
  }, [textLang, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored && selectedMaterials.length > 0) {
      localStorage.setItem(`vigent_${storageKey}_material`, JSON.stringify(selectedMaterials));
    }
  }, [selectedMaterials, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored && selectedSubtitleStyleId) {
      localStorage.setItem(`vigent_${storageKey}_subtitleStyle`, selectedSubtitleStyleId);
    }
  }, [selectedSubtitleStyleId, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored && selectedTitleStyleId) {
      localStorage.setItem(`vigent_${storageKey}_titleStyle`, selectedTitleStyleId);
    }
  }, [selectedTitleStyleId, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored && selectedSecondaryTitleStyleId) {
      localStorage.setItem(`vigent_${storageKey}_secondaryTitleStyle`, selectedSecondaryTitleStyleId);
    }
  }, [selectedSecondaryTitleStyleId, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_subtitleFontSize`, String(subtitleFontSize));
    }
  }, [subtitleFontSize, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_titleFontSize`, String(titleFontSize));
    }
  }, [titleFontSize, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_secondaryTitleFontSize`, String(secondaryTitleFontSize));
    }
  }, [secondaryTitleFontSize, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_titleTopMargin`, String(titleTopMargin));
    }
  }, [titleTopMargin, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_secondaryTitleTopMargin`, String(secondaryTitleTopMargin));
    }
  }, [secondaryTitleTopMargin, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_titleDisplayMode`, titleDisplayMode);
    }
  }, [titleDisplayMode, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_subtitleBottomMargin`, String(subtitleBottomMargin));
    }
  }, [subtitleBottomMargin, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_outputAspectRatio`, outputAspectRatio);
    }
  }, [outputAspectRatio, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_lipsyncModelMode`, lipsyncModelMode);
    }
  }, [lipsyncModelMode, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_bgmId`, selectedBgmId);
    }
  }, [selectedBgmId, storageKey, isRestored]);

  useEffect(() => {
    if (!isRestored) return;
    const timeout = setTimeout(() => {
      localStorage.setItem(`vigent_${storageKey}_bgmVolume`, String(bgmVolume));
    }, 300);
    return () => clearTimeout(timeout);
  }, [bgmVolume, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_enableBgm`, String(enableBgm));
    }
  }, [enableBgm, storageKey, isRestored]);

  useEffect(() => {
    if (!isRestored) return;
    if (selectedVideoId) {
      localStorage.setItem(`vigent_${storageKey}_selectedVideoId`, selectedVideoId);
    } else {
      localStorage.removeItem(`vigent_${storageKey}_selectedVideoId`);
    }
  }, [selectedVideoId, storageKey, isRestored]);

  useEffect(() => {
    if (!isRestored) return;
    if (selectedAudioId) {
      localStorage.setItem(`vigent_${storageKey}_selectedAudioId`, selectedAudioId);
    } else {
      localStorage.removeItem(`vigent_${storageKey}_selectedAudioId`);
    }
  }, [selectedAudioId, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored && selectedRefAudio) {
      localStorage.setItem(`vigent_${storageKey}_refAudioId`, selectedRefAudio.id);
    }
  }, [selectedRefAudio, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_speed`, String(speed));
    }
  }, [speed, storageKey, isRestored]);

  useEffect(() => {
    if (isRestored) {
      localStorage.setItem(`vigent_${storageKey}_emotion`, emotion);
    }
  }, [emotion, storageKey, isRestored]);

  return { isRestored };
};
