"use client";

import { useState, useEffect } from "react";
import useSWR from 'swr';

const fetcher = (url: string) => fetch(url).then((res) => res.json());
import Link from "next/link";

// 动态获取 API 地址：服务端使用 localhost，客户端使用当前域名
const API_BASE = typeof window !== 'undefined'
    ? `http://${window.location.hostname}:8006`
    : 'http://localhost:8006';

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 [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);

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

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

    const fetchVideos = async () => {
        try {
            // 使用持久化的视频列表 API（从文件系统读取）
            const res = await fetch(`${API_BASE}/api/videos/generated`);
            const data = await res.json();

            const videos = (data.videos || []).map((v: any) => ({
                name: new Date(v.created_at * 1000).toLocaleString('zh-CN') + ` (${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 res = await fetch(`${API_BASE}/api/publish/`, {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({
                        video_path: selectedVideo,
                        platform,
                        title,
                        tags: tagList,
                        description: "",
                        publish_time: scheduleMode === "scheduled" && publishTime
                            ? new Date(publishTime).toISOString()
                            : null
                    }),
                });

                const result = await res.json();
                setPublishResults((prev) => [...prev, result]);
            } catch (error) {
                setPublishResults((prev) => [
                    ...prev,
                    { platform, success: false, message: String(error) },
                ]);
            }
        }

        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) => {
        try {
            const res = await fetch(`${API_BASE}/api/publish/login/${platform}`, {
                method: 'POST'
            });
            const result = await res.json();

            if (result.success && result.qr_code) {
                setQrCodeImage(result.qr_code);
                setQrPlatform(platform);
                // SWR hook will automatically start polling since qrPlatform is set
            } else {
                alert(result.message || '登录失败');
            }
        } catch (error) {
            alert(`登录失败: ${error}`);
        }
    };

    const handleLogout = async (platform: string) => {
        if (!confirm('确定要注销登录吗？')) return;
        try {
            const res = await fetch(`${API_BASE}/api/publish/logout/${platform}`, {
                method: 'POST'
            });
            const result = await res.json();
            if (result.success) {
                alert('已注销');
                fetchAccounts();
            } else {
                alert(result.message || '注销失败');
            }
        } catch (error) {
            alert(`注销失败: ${error}`);
        }
    };

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

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-900 via-purple-900 to-gray-900">
            {/* QR码弹窗 */}
            {qrCodeImage && (
                <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">
                        <h2 className="text-2xl font-bold mb-4 text-center">🔐 扫码登录 {qrPlatform}</h2>
                        <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>
                        <button
                            onClick={() => setQrCodeImage(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">
                <div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
                    <Link href="/" className="text-2xl font-bold text-white flex items-center gap-3 hover:opacity-80 transition-opacity">
                        <span className="text-4xl">🎬</span>
                        ViGent
                    </Link>
                    <div className="flex items-center gap-4">
                        <Link
                            href="/"
                            className="px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors"
                        >
                            视频生成
                        </Link>
                        <span className="px-4 py-2 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg font-semibold">
                            发布管理
                        </span>
                    </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"
                                                    >
                                                        ↻ 重新登录
                                                    </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"
                                                    >
                                                        注销
                                                    </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"
                                                >
                                                    🔐 扫码登录
                                                </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>
                            ) : (
                                <select
                                    value={selectedVideo}
                                    onChange={(e) => setSelectedVideo(e.target.value)}
                                    className="w-full p-3 bg-black/30 border border-white/10 rounded-xl text-white custom-select cursor-pointer hover:border-purple-500/50 transition-colors"
                                >
                                    {videos.map((v) => (
                                        <option key={v.path} value={v.path}>
                                            {v.name}
                                        </option>
                                    ))}
                                </select>
                            )}
                        </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>
                                    <label className="block text-gray-400 text-sm mb-2">
                                        发布时间
                                    </label>
                                    <div className="flex gap-3 mb-3">
                                        <button
                                            onClick={() => setScheduleMode("now")}
                                            className={`flex-1 px-4 py-2 rounded-lg font-medium transition-colors ${scheduleMode === "now"
                                                ? "bg-purple-600 text-white"
                                                : "bg-black/30 text-gray-400 hover:bg-black/50"
                                                }`}
                                        >
                                            ⚡ 立即发布
                                        </button>
                                        <button
                                            onClick={() => setScheduleMode("scheduled")}
                                            className={`flex-1 px-4 py-2 rounded-lg font-medium transition-colors ${scheduleMode === "scheduled"
                                                ? "bg-purple-600 text-white"
                                                : "bg-black/30 text-gray-400 hover:bg-black/50"
                                                }`}
                                        >
                                            ⏰ 定时发布
                                        </button>
                                    </div>
                                    {scheduleMode === "scheduled" && (
                                        <input
                                            type="datetime-local"
                                            value={publishTime}
                                            onChange={(e) => setPublishTime(e.target.value)}
                                            min={new Date().toISOString().slice(0, 16)}
                                            className="w-full p-3 bg-black/30 border border-white/10 rounded-xl text-white"
                                        />
                                    )}
                                </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>

                        {/* 发布按钮 */}
                        <button
                            onClick={handlePublish}
                            disabled={isPublishing || selectedPlatforms.length === 0}
                            className={`w-full py-4 rounded-xl font-bold text-lg transition-all ${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 ? "发布中..." : "🚀 一键发布"}
                        </button>

                        {/* 发布结果 */}
                        {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>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </main>
        </div>
    );
}
