"use client";

import { useState, useEffect, useMemo } from "react";
import useSWR from 'swr';
import Link from "next/link";
import api from "@/lib/axios";
import { getApiBaseUrl, formatDate, resolveMediaUrl, isAbsoluteUrl } from "@/lib/media";
import { useAuth } from "@/contexts/AuthContext";
import AccountSettingsDropdown from "@/components/AccountSettingsDropdown";
import VideoPreviewModal from "@/components/VideoPreviewModal";
import {
    ArrowLeft,
    RotateCcw,
    LogOut,
    QrCode,
    Rocket,
    Clock,
    RefreshCw,
    Search,
    Eye,
} from "lucide-react";

// SWR fetcher 使用 axios（自动处理 401/403）
const fetcher = (url: string) => api.get(url).then((res) => res.data);

// 动态获取 API 地址：服务端使用 localhost，客户端使用当前域名
const API_BASE = getApiBaseUrl();

interface Account {
    platform: string;
    name: string;
    logged_in: boolean;
    enabled: boolean;
}

interface Video {
    name: string;
    path: string;
}

export default function PublishPage() {
    const [accounts, setAccounts] = useState<Account[]>([]);
    const [videos, setVideos] = useState<Video[]>([]);
    const [selectedVideo, setSelectedVideo] = useState<string>("");
    const [videoFilter, setVideoFilter] = useState<string>("");
    const [previewVideoUrl, setPreviewVideoUrl] = useState<string | null>(null);
    const [selectedPlatforms, setSelectedPlatforms] = useState<string[]>([]);
    const [title, setTitle] = useState<string>("");
    const [tags, setTags] = useState<string>("");
    const [isPublishing, setIsPublishing] = useState(false);
    const [publishResults, setPublishResults] = useState<any[]>([]);
    const [scheduleMode, setScheduleMode] = useState<"now" | "scheduled">("now");
    const [publishTime, setPublishTime] = useState<string>("");
    const [qrCodeImage, setQrCodeImage] = useState<string | null>(null);
    const [qrPlatform, setQrPlatform] = useState<string | null>(null);
    const [isLoadingQR, setIsLoadingQR] = useState(false);

    // 使用全局认证状态
    const { userId, isLoading: isAuthLoading } = useAuth();
    // 是否已从 localStorage 恢复完成
    const [isRestored, setIsRestored] = useState(false);

    // 加载账号和视频列表
    useEffect(() => {
        void Promise.allSettled([
            fetchAccounts(),
            fetchVideos(),
        ]);
    }, []);

    useEffect(() => {
        if (typeof window === 'undefined') return;
        if ('scrollRestoration' in window.history) {
            window.history.scrollRestoration = 'manual';
        }
        window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
    }, []);

    // 获取存储 key 的前缀（登录用户使用 userId，未登录使用 guest）
    const storageKey = userId || 'guest';

    // 从 localStorage 恢复用户输入（等待认证完成后）
    useEffect(() => {
        console.log("[Publish] 恢复检查 - isAuthLoading:", isAuthLoading, "userId:", userId);
        if (isAuthLoading) return;

        console.log("[Publish] 开始从 localStorage 恢复数据，storageKey:", storageKey);
        // 从 localStorage 恢复用户输入（带用户隔离，未登录用户使用 guest）
        const savedTitle = localStorage.getItem(`vigent_${storageKey}_publish_title`);
        const savedTags = localStorage.getItem(`vigent_${storageKey}_publish_tags`);

        console.log("[Publish] localStorage 数据:", { savedTitle, savedTags });

        if (savedTitle) setTitle(savedTitle);
        if (savedTags) {
            // 兼容 JSON 数组格式（AI 生成）和字符串格式（手动输入）
            try {
                const parsed = JSON.parse(savedTags);
                if (Array.isArray(parsed)) {
                    setTags(parsed.join(', '));
                } else {
                    setTags(savedTags);
                }
            } catch {
                setTags(savedTags);
            }
        }

        // 恢复完成后才允许保存
        setIsRestored(true);
        console.log("[Publish] 恢复完成，isRestored = true");
    }, [storageKey, isAuthLoading]);

    // 保存用户输入到 localStorage（恢复完成后才保存，未登录用户也可保存）
    useEffect(() => {
        if (!isRestored) return;
        const timeout = setTimeout(() => {
            localStorage.setItem(`vigent_${storageKey}_publish_title`, title);
        }, 300);
        return () => clearTimeout(timeout);
    }, [title, storageKey, isRestored]);

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

    const fetchAccounts = async () => {
        try {
            const { data } = await api.get('/api/publish/accounts');
            setAccounts(data.accounts || []);
        } catch (error) {
            console.error("获取账号失败:", error);
        }
    };

    const fetchVideos = async () => {
        try {
            const { data } = await api.get('/api/videos/generated');

            const videos = (data.videos || []).map((v: any) => ({
                name: formatDate(v.created_at) + ` (${v.size_mb.toFixed(1)}MB)`,
                path: v.path.startsWith('/') ? v.path.slice(1) : v.path,
            }));

            setVideos(videos);
            if (videos.length > 0) {
                setSelectedVideo(videos[0].path);
            }
        } catch (error) {
            console.error("获取视频失败:", error);
        }
    };

    const togglePlatform = (platform: string) => {
        if (selectedPlatforms.includes(platform)) {
            setSelectedPlatforms(selectedPlatforms.filter((p) => p !== platform));
        } else {
            setSelectedPlatforms([...selectedPlatforms, platform]);
        }
    };

    const handlePublish = async () => {
        if (!selectedVideo || !title || selectedPlatforms.length === 0) {
            alert("请选择视频、填写标题并选择至少一个平台");
            return;
        }

        setIsPublishing(true);
        setPublishResults([]);

        const tagList = tags.split(/[,，\s]+/).filter((t) => t.trim());

        for (const platform of selectedPlatforms) {
            try {
                const { data: result } = await api.post('/api/publish', {
                    video_path: selectedVideo,
                    platform,
                    title,
                    tags: tagList,
                    description: "",
                    publish_time: scheduleMode === "scheduled" && publishTime
                        ? new Date(publishTime).toISOString()
                        : null
                });

                setPublishResults((prev) => [...prev, result]);
                // 发布成功后10秒自动清除结果
                if (result.success) {
                    setTimeout(() => {
                        setPublishResults((prev) => prev.filter((r) => r !== result));
                    }, 10000);
                }
            } catch (error: any) {
                const message = error.response?.data?.detail || String(error);
                setPublishResults((prev) => [
                    ...prev,
                    { platform, success: false, message },
                ]);
            }
        }

        setIsPublishing(false);
    };

    // SWR Polling for Login Status
    const { data: loginStatus } = useSWR(
        qrPlatform ? `${API_BASE}/api/publish/login/status/${qrPlatform}` : null,
        fetcher,
        {
            refreshInterval: 2000,
            onSuccess: (data) => {
                if (data.success) {
                    setQrCodeImage(null);
                    setQrPlatform(null);
                    alert('✅ 登录成功！');
                    fetchAccounts();
                }
            }
        }
    );

    // Timeout logic for QR code (business logic: stop after 2 mins)
    useEffect(() => {
        let timer: NodeJS.Timeout;
        if (qrPlatform) {
            timer = setTimeout(() => {
                if (qrPlatform) { // Double check active
                    setQrPlatform(null);
                    setQrCodeImage(null);
                    alert('登录超时，请重试');
                }
            }, 120000);
        }
        return () => clearTimeout(timer);
    }, [qrPlatform]);

    const handleLogin = async (platform: string) => {
        setIsLoadingQR(true);
        setQrPlatform(platform);  // 立即显示加载弹窗
        setQrCodeImage(null);     // 清空旧二维码
        try {
            const { data: result } = await api.post(`/api/publish/login/${platform}`);

            if (result.success && result.qr_code) {
                setQrCodeImage(result.qr_code);
            } else {
                setQrPlatform(null);
                alert(result.message || '登录失败');
            }
        } catch (error: any) {
            setQrPlatform(null);
            alert(`登录失败: ${error.response?.data?.detail || error.message}`);
        } finally {
            setIsLoadingQR(false);
        }
    };

    const handleLogout = async (platform: string) => {
        if (!confirm('确定要注销登录吗？')) return;
        try {
            const { data: result } = await api.post(`/api/publish/logout/${platform}`);
            if (result.success) {
                alert('已注销');
                fetchAccounts();
            } else {
                alert(result.message || '注销失败');
            }
        } catch (error: any) {
            alert(`注销失败: ${error.response?.data?.detail || error.message}`);
        }
    };

    const platformIcons: Record<string, string> = {
        douyin: "🎵",
        xiaohongshu: "📕",
        weixin: "💬",
        kuaishou: "⚡",
        bilibili: "📺",
    };

    const filteredVideos = useMemo(() => {
        const query = videoFilter.trim().toLowerCase();
        if (!query) return videos;
        return videos.filter((v) => v.name.toLowerCase().includes(query));
    }, [videos, videoFilter]);

    return (
            <div className="min-h-dvh">
            <VideoPreviewModal
                onClose={() => setPreviewVideoUrl(null)}
                videoUrl={previewVideoUrl}
                title="发布视频预览"
            />
            {/* QR码弹窗 */}
            {qrPlatform && (
                <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50">
                    <div className="bg-white rounded-2xl p-8 max-w-md min-w-[320px]">
                        <h2 className="text-2xl font-bold mb-4 text-center">🔐 扫码登录 {qrPlatform}</h2>
                        {isLoadingQR ? (
                            <div className="flex flex-col items-center py-8">
                                <div className="animate-spin w-16 h-16 border-4 border-purple-500 border-t-transparent rounded-full" />
                                <p className="text-gray-600 mt-4">正在获取二维码...</p>
                            </div>
                        ) : qrCodeImage ? (
                            <>
                                <img
                                    src={`data:image/png;base64,${qrCodeImage}`}
                                    alt="QR Code"
                                    className="w-full h-auto"
                                />
                                <p className="text-center text-gray-600 mt-4">
                                    请使用手机扫码登录
                                </p>
                            </>
                        ) : null}
                        <button
                            onClick={() => { setQrCodeImage(null); setQrPlatform(null); }}
                            className="w-full mt-4 px-4 py-2 bg-gray-200 rounded-lg hover:bg-gray-300"
                        >
                            取消
                        </button>
                    </div>
                </div>
            )}

            {/* Header - 统一样式 */}
            <header className="border-b border-white/10 bg-black/20 backdrop-blur-sm relative z-[100]">
                <div className="max-w-6xl mx-auto px-4 sm:px-6 py-3 sm:py-4 flex items-center justify-between">
                    <Link href="/" className="text-xl sm:text-2xl font-bold text-white flex items-center gap-2 sm:gap-3 hover:opacity-80 transition-opacity">
                        <span className="text-3xl sm:text-4xl">🎬</span>
                        IPAgent
                    </Link>
                    <div className="flex items-center gap-1 sm:gap-4">
                        <Link
                            href="/"
                            className="px-2 sm:px-4 py-1 sm:py-2 text-sm sm:text-base bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors flex items-center gap-1"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            返回创作
                        </Link>
                        <span className="px-2 sm:px-4 py-1 sm:py-2 text-sm sm:text-base bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg font-semibold">
                            发布管理
                        </span>
                        <AccountSettingsDropdown />
                    </div>
                </div>
            </header>

            <main className="max-w-6xl mx-auto px-6 py-8">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    {/* 左侧: 账号管理 */}
                    <div className="space-y-6">
                        <div className="bg-white/5 rounded-2xl p-6 border border-white/10 backdrop-blur-sm">
                            <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                                👤 平台账号
                            </h2>

                            <div className="space-y-3">
                                {accounts.map((account) => (
                                    <div
                                        key={account.platform}
                                        className="flex items-center justify-between p-4 bg-black/30 rounded-xl"
                                    >
                                        <div className="flex items-center gap-3">
                                            <span className="text-2xl">
                                                {platformIcons[account.platform]}
                                            </span>
                                            <div>
                                                <div className="text-white font-medium">
                                                    {account.name}
                                                </div>
                                                <div
                                                    className={`text-sm ${account.logged_in
                                                        ? "text-green-400"
                                                        : "text-gray-500"
                                                        }`}
                                                >
                                                    {account.logged_in ? "✓ 已登录" : "未登录"}
                                                </div>
                                            </div>
                                        </div>
                                        <div className="flex gap-2">
                                            {account.logged_in ? (
                                                <>
                                                    <button
                                                        onClick={() => handleLogin(account.platform)}
                                                        className="px-3 py-1 bg-white/10 hover:bg-white/20 text-white text-sm rounded-lg transition-colors flex items-center gap-1"
                                                    >
                                                        <RotateCcw className="h-3.5 w-3.5" />
                                                        重新登录
                                                    </button>
                                                    <button
                                                        onClick={() => handleLogout(account.platform)}
                                                        className="px-3 py-1 bg-red-500/80 hover:bg-red-600 text-white text-sm rounded-lg transition-colors flex items-center gap-1"
                                                    >
                                                        <LogOut className="h-3.5 w-3.5" />
                                                        注销
                                                    </button>
                                                </>
                                            ) : (
                                                <button
                                                    onClick={() => handleLogin(account.platform)}
                                                    className="px-3 py-1 bg-purple-600 hover:bg-purple-700 text-white text-sm rounded-lg transition-colors flex items-center gap-1"
                                                >
                                                    <QrCode className="h-3.5 w-3.5" />
                                                    扫码登录
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* 右侧: 发布表单 */}
                    <div className="space-y-6">
                        {/* 选择视频 */}
                        <div className="bg-white/5 rounded-2xl p-6 border border-white/10 backdrop-blur-sm">
                            <h2 className="text-lg font-semibold text-white mb-4">
                                🎥 选择要发布的作品
                            </h2>

                            {videos.length === 0 ? (
                                <p className="text-gray-400">
                                    暂无已生成的视频，请先
                                    <Link href="/" className="text-purple-400 hover:underline">
                                        生成视频
                                    </Link>
                                </p>
                            ) : (
                                <>
                                    <div className="flex items-center gap-2 mb-3">
                                        <div className="relative flex-1">
                                            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500" />
                                            <input
                                                value={videoFilter}
                                                onChange={(e) => setVideoFilter(e.target.value)}
                                                placeholder="搜索视频..."
                                                className="w-full pl-9 pr-3 py-2 bg-black/30 border border-white/10 rounded-lg text-white text-sm placeholder-gray-500 focus:outline-none focus:border-purple-500 transition-colors"
                                            />
                                        </div>
                                        <button
                                            onClick={fetchVideos}
                                            className="px-2 py-2 text-xs bg-white/10 hover:bg-white/20 rounded text-gray-300 flex items-center gap-1"
                                        >
                                            <RefreshCw className="h-3.5 w-3.5" />
                                            刷新
                                        </button>
                                    </div>

                                    {filteredVideos.length === 0 ? (
                                        <div className="text-center py-4 text-gray-500 text-sm">
                                            没有匹配的视频
                                        </div>
                                    ) : (
                                        <div
                                            className="space-y-2 max-h-64 overflow-y-auto hide-scrollbar"
                                            style={{ contentVisibility: 'auto' }}
                                        >
                                            {filteredVideos.map((v) => (
                                                <div
                                                    key={v.path}
                                                    className={`p-3 rounded-lg border transition-all flex items-center justify-between group ${selectedVideo === v.path
                                                        ? "border-purple-500 bg-purple-500/20"
                                                        : "border-white/10 bg-white/5 hover:border-white/30"
                                                        }`}
                                                >
                                                    <button
                                                        onClick={() => setSelectedVideo(v.path)}
                                                        className="flex-1 text-left"
                                                    >
                                                        <div className="text-white text-sm truncate">
                                                            {v.name}
                                                        </div>
                                                    </button>
                                                    <div className="flex items-center gap-2 pl-2">
                                                        <button
                                                            onClick={(e) => {
                                                                e.stopPropagation();
                                                                const previewPath = isAbsoluteUrl(v.path)
                                                                    ? v.path
                                                                    : v.path.startsWith('/')
                                                                        ? v.path
                                                                        : `/${v.path}`;
                                                                setPreviewVideoUrl(resolveMediaUrl(previewPath) || previewPath);
                                                            }}
                                                            className="p-1 text-gray-500 hover:text-purple-400 transition-colors"
                                                            title="预览"
                                                        >
                                                            <Eye className="h-4 w-4" />
                                                        </button>
                                                        {selectedVideo === v.path && (
                                                            <span className="text-xs text-purple-300">已选</span>
                                                        )}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </>
                            )}
                        </div>

                        {/* 填写信息 */}
                        <div className="bg-white/5 rounded-2xl p-6 border border-white/10 backdrop-blur-sm">
                            <h2 className="text-lg font-semibold text-white mb-4">✍️ 发布信息</h2>

                            <div className="space-y-4">
                                <div>
                                    <label className="block text-gray-400 text-sm mb-2">
                                        标题
                                    </label>
                                    <input
                                        type="text"
                                        value={title}
                                        onChange={(e) => setTitle(e.target.value)}
                                        placeholder="输入视频标题..."
                                        className="w-full p-3 bg-black/30 border border-white/10 rounded-xl text-white placeholder-gray-500"
                                    />
                                </div>
                                <div>
                                    <label className="block text-gray-400 text-sm mb-2">
                                        标签 (用逗号分隔)
                                    </label>
                                    <input
                                        type="text"
                                        value={tags}
                                        onChange={(e) => setTags(e.target.value)}
                                        placeholder="AI, 数字人, 口播..."
                                        className="w-full p-3 bg-black/30 border border-white/10 rounded-xl text-white placeholder-gray-500"
                                    />
                                </div>
                            </div>
                        </div>

                        {/* 选择平台 */}
                        <div className="bg-white/5 rounded-2xl p-6 border border-white/10 backdrop-blur-sm">
                            <h2 className="text-lg font-semibold text-white mb-4">📱 选择发布平台</h2>

                            <div className="grid grid-cols-3 gap-3">
                                {accounts
                                    .filter((a) => a.logged_in)
                                    .map((account) => (
                                        <button
                                            key={account.platform}
                                            onClick={() => togglePlatform(account.platform)}
                                            className={`p-3 rounded-xl border-2 transition-all ${selectedPlatforms.includes(account.platform)
                                                ? "border-purple-500 bg-purple-500/20"
                                                : "border-white/10 bg-white/5 hover:border-white/30"
                                                }`}
                                        >
                                            <span className="text-2xl block mb-1">
                                                {platformIcons[account.platform]}
                                            </span>
                                            <span className="text-white text-sm">{account.name}</span>
                                        </button>
                                    ))}
                            </div>

                            {accounts.filter((a) => a.logged_in).length === 0 && (
                                <p className="text-gray-400 text-center py-4">
                                    请先登录至少一个平台账号
                                </p>
                            )}
                        </div>

                        {/* 发布按钮区域 */}
                        <div className="space-y-3">
                            <div className="flex gap-3">
                                {/* 立即发布 - 占 3/4 */}
                                <button
                                    onClick={() => {
                                        setScheduleMode("now");
                                        handlePublish();
                                    }}
                                    disabled={isPublishing || selectedPlatforms.length === 0}
                                    className={`flex-[3] py-4 rounded-xl font-bold text-lg transition-all flex items-center justify-center gap-2 ${isPublishing || selectedPlatforms.length === 0
                                        ? "bg-gray-600 cursor-not-allowed text-gray-400"
                                        : "bg-gradient-to-r from-green-600 to-teal-600 hover:from-green-700 hover:to-teal-700 text-white"
                                        }`}
                                >
                                    {isPublishing && scheduleMode === "now" ? (
                                        "发布中..."
                                    ) : (
                                        <>
                                            <Rocket className="h-5 w-5" />
                                            立即发布
                                        </>
                                    )}
                                </button>
                                {/* 定时发布 - 占 1/4 */}
                                <button
                                    onClick={() => setScheduleMode(scheduleMode === "scheduled" ? "now" : "scheduled")}
                                    disabled={isPublishing || selectedPlatforms.length === 0}
                                    className={`flex-1 py-4 rounded-xl font-bold text-base transition-all flex items-center justify-center gap-2 ${isPublishing || selectedPlatforms.length === 0
                                        ? "bg-gray-600 cursor-not-allowed text-gray-400"
                                        : scheduleMode === "scheduled"
                                            ? "bg-purple-600 text-white"
                                            : "bg-white/10 hover:bg-white/20 text-white"
                                        }`}
                                >
                                    <Clock className="h-5 w-5" />
                                    定时
                                </button>
                            </div>

                            {/* 定时发布时间选择器 */}
                            {scheduleMode === "scheduled" && (
                                <div className="flex gap-3 items-center">
                                    <input
                                        type="datetime-local"
                                        value={publishTime}
                                        onChange={(e) => setPublishTime(e.target.value)}
                                        min={new Date().toISOString().slice(0, 16)}
                                        className="flex-1 p-3 bg-black/30 border border-white/10 rounded-xl text-white"
                                    />
                                    <button
                                        onClick={handlePublish}
                                        disabled={isPublishing || selectedPlatforms.length === 0 || !publishTime}
                                        className={`px-6 py-3 rounded-xl font-bold transition-all ${isPublishing || selectedPlatforms.length === 0 || !publishTime
                                            ? "bg-gray-600 cursor-not-allowed text-gray-400"
                                            : "bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white"
                                            }`}
                                    >
                                        {isPublishing && scheduleMode === "scheduled" ? "设置中..." : "确认定时"}
                                    </button>
                                </div>
                            )}
                        </div>

                        {/* 发布结果 */}
                        {publishResults.length > 0 && (
                            <div className="bg-white/5 rounded-2xl p-6 border border-white/10">
                                <h2 className="text-lg font-semibold text-white mb-4">
                                    发布结果
                                </h2>
                                <div className="space-y-2">
                                    {publishResults.map((result, i) => (
                                        <div
                                            key={i}
                                            className={`p-3 rounded-lg ${result.success ? "bg-green-500/20" : "bg-red-500/20"
                                                }`}
                                        >
                                            <span className="text-white">
                                                {platformIcons[result.platform]} {result.message}
                                            </span>
                                            {result.success && (
                                                <p className="text-green-400/80 text-sm mt-1">
                                                    ⏳ 审核一般需要几分钟，请耐心等待
                                                </p>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </main>
        </div>
    );
}
