"use client";

import Link from "next/link";
import Image from "next/image";
import VideoPreviewModal from "@/components/VideoPreviewModal";
import AccountSettingsDropdown from "@/components/AccountSettingsDropdown";
import { SelectPopover } from "@/shared/ui/SelectPopover";
import { AppModal, AppModalHeader } from "@/shared/ui/AppModal";
import { usePublishController } from "@/features/publish/model/usePublishController";
import {
  ArrowLeft,
  Check,
  ChevronDown,
  RotateCcw,
  LogOut,
  QrCode,
  Search,
  Eye,
  Loader2,
} from "lucide-react";

export function PublishPage() {
  const {
    accounts,
    videos,
    isAccountsLoading,
    isVideosLoading,
    selectedVideo,
    setSelectedVideo,
    videoFilter,
    setVideoFilter,
    previewVideoUrl,
    setPreviewVideoUrl,
    selectedPlatforms,
    title,
    titleInput,
    tags,
    setTags,
    isPublishing,
    publishResults,
    qrCodeImage,
    qrPlatform,
    isLoadingQR,
    faceVerifyQr,
    togglePlatform,
    handlePublish,
    handleLogin,
    handleLogout,
    platformIcons,
    filteredVideos,
    handlePreviewVideo,
    closeQrModal,
  } = usePublishController();

  const selectedVideoItem = videos.find((v) => v.id === selectedVideo) || null;

  return (
    <div className="min-h-dvh">
      <VideoPreviewModal
        onClose={() => setPreviewVideoUrl(null)}
        videoUrl={previewVideoUrl}
        title="发布视频预览"
      />
      {/* QR码弹窗 */}
      {qrPlatform && (
        <AppModal
          isOpen={Boolean(qrPlatform)}
          onClose={closeQrModal}
          panelClassName="w-full max-w-md rounded-2xl border border-white/10 bg-[#171821]/95 shadow-[0_24px_80px_rgba(0,0,0,0.55)] overflow-hidden"
          closeOnOverlay={false}
        >
          <AppModalHeader
            title={`🔐 扫码登录 ${qrPlatform}`}
            subtitle="请使用手机扫码完成登录验证"
            icon={<QrCode className="h-5 w-5 text-purple-300" />}
            onClose={closeQrModal}
          />

          <div className="p-5 space-y-4">
            {isLoadingQR ? (
              <div className="flex flex-col items-center py-8">
                <Loader2 className="h-14 w-14 animate-spin text-purple-400" />
                <p className="text-gray-300 mt-4">正在获取二维码...</p>
              </div>
            ) : faceVerifyQr ? (
              <div className="space-y-3">
                <div className="mx-auto w-fit rounded-xl border border-white/10 bg-white p-2 shadow-[0_10px_30px_rgba(0,0,0,0.35)]">
                  <Image
                    src={`data:image/png;base64,${faceVerifyQr}`}
                    alt="Face Verify QR"
                    width={400}
                    height={300}
                    className="h-auto w-[min(82vw,400px)] border border-black/5"
                    unoptimized
                  />
                </div>
                <p className="text-center text-amber-300 text-sm font-medium">
                  需要身份验证，请用抖音 APP 扫描上方二维码完成刷脸验证
                </p>
              </div>
            ) : qrCodeImage ? (
              <div className="space-y-3">
                <div className="mx-auto w-fit rounded-xl border border-white/10 bg-white p-3 shadow-[0_10px_30px_rgba(0,0,0,0.35)]">
                  <Image
                    src={`data:image/png;base64,${qrCodeImage}`}
                    alt="QR Code"
                    width={300}
                    height={300}
                    className="h-auto w-[min(74vw,300px)] border border-black/5"
                    unoptimized
                  />
                </div>
                <p className="text-center text-gray-300 text-sm">请使用手机扫码登录</p>
              </div>
            ) : (
              <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">
                二维码获取失败，请重试
              </div>
            )}

            <button
              onClick={closeQrModal}
              className="w-full px-4 py-2.5 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors"
            >
              取消
            </button>
          </div>
        </AppModal>
      )}

      {/* 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>

              {isAccountsLoading ? (
                <div className="space-y-3">
                  {Array.from({ length: 3 }).map((_, index) => (
                    <div
                      key={`account-skeleton-${index}`}
                      className="flex items-center justify-between p-4 bg-black/30 rounded-xl animate-pulse"
                    >
                      <div className="flex items-center gap-3">
                        <div className="h-7 w-7 rounded-full bg-white/10" />
                        <div>
                          <div className="h-4 w-24 bg-white/10 rounded" />
                          <div className="h-3 w-16 bg-white/5 rounded mt-2" />
                        </div>
                      </div>
                      <div className="h-8 w-20 bg-white/10 rounded" />
                    </div>
                  ))}
                </div>
              ) : (
                <div className="space-y-2 sm:space-y-3">
                  {accounts.map((account) => (
                    <div
                      key={account.platform}
                      className="flex items-center gap-3 px-3 py-2.5 sm:px-4 sm:py-3.5 bg-black/30 rounded-xl"
                    >
                      {platformIcons[account.platform] ? (
                        <Image
                          src={platformIcons[account.platform].src}
                          alt={platformIcons[account.platform].alt}
                          width={28}
                          height={28}
                          className="h-6 w-6 sm:h-7 sm:w-7 shrink-0"
                        />
                      ) : (
                        <span className="text-xl sm:text-2xl">🌐</span>
                      )}
                      <div className="min-w-0 flex-1">
                        <div className="text-sm sm:text-base text-white font-medium leading-tight">
                          {account.name}
                        </div>
                        <div
                          className={`text-xs sm:text-sm leading-tight ${account.logged_in
                            ? "text-green-400"
                            : "text-gray-500"
                            }`}
                        >
                          {account.logged_in ? "✓ 已登录" : "未登录"}
                        </div>
                      </div>
                      <div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
                        {account.logged_in ? (
                          <>
                            <button
                              onClick={() => handleLogin(account.platform)}
                              className="px-2 py-1 sm:px-3 sm:py-1.5 bg-white/10 hover:bg-white/20 text-white text-xs sm:text-sm rounded-md sm:rounded-lg transition-colors flex items-center gap-1"
                            >
                              <RotateCcw className="h-3 w-3 sm:h-3.5 sm:w-3.5" />
                              重新登录
                            </button>
                            <button
                              onClick={() => handleLogout(account.platform)}
                              className="px-2 py-1 sm:px-3 sm:py-1.5 bg-red-500/80 hover:bg-red-600 text-white text-xs sm:text-sm rounded-md sm:rounded-lg transition-colors flex items-center gap-1"
                            >
                              <LogOut className="h-3 w-3 sm:h-3.5 sm:w-3.5" />
                              注销
                            </button>
                          </>
                        ) : (
                          <button
                            onClick={() => handleLogin(account.platform)}
                            className="px-2 py-1 sm:px-3 sm:py-1.5 bg-purple-500/80 hover:bg-purple-600 text-white text-xs sm:text-sm rounded-md sm:rounded-lg transition-colors flex items-center gap-1"
                          >
                            <QrCode className="h-3 w-3 sm:h-3.5 sm: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>
              <SelectPopover
                sheetTitle="选择发布作品"
                onOpen={() => setVideoFilter("")}
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="w-full rounded-xl border border-white/10 bg-black/25 px-3 py-2.5 text-left transition-colors hover:border-white/30"
                  >
                    <span className="flex items-center justify-between gap-3">
                      <span className="min-w-0">
                        <span className="block text-xs text-gray-400">当前作品</span>
                        <span className="mt-0.5 block truncate text-sm text-white">
                          {selectedVideoItem?.name || (isVideosLoading ? "正在加载作品..." : "请选择发布作品")}
                        </span>
                      </span>
                      <ChevronDown className={`h-4 w-4 text-gray-300 transition-transform ${open ? "rotate-180" : ""}`} />
                    </span>
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-2">
                    <div className="rounded-lg border border-white/10 bg-black/30 px-3 py-2">
                      <div className="flex items-center gap-2">
                        <Search className="h-4 w-4 text-gray-400" />
                        <input
                          type="text"
                          value={videoFilter}
                          onChange={(e) => setVideoFilter(e.target.value)}
                          placeholder="搜索视频名称..."
                          className="w-full bg-transparent text-sm text-white placeholder-gray-500 outline-none"
                        />
                      </div>
                    </div>

                    {isVideosLoading ? (
                      <div className="space-y-2 p-1">
                        {Array.from({ length: 2 }).map((_, index) => (
                          <div
                            key={`video-skeleton-${index}`}
                            className="p-3 rounded-lg border border-white/10 bg-white/5 animate-pulse"
                          >
                            <div className="h-4 w-40 bg-white/10 rounded" />
                          </div>
                        ))}
                      </div>
                    ) : filteredVideos.length === 0 ? (
                      <div className="py-8 text-center text-sm text-gray-400">
                        暂无可发布的视频
                      </div>
                    ) : (
                      <div className="space-y-1 pb-1" style={{ contentVisibility: "auto" }}>
                        {filteredVideos.map((v) => {
                          const isSelected = selectedVideo === v.id;

                          return (
                            <div
                              key={v.id}
                              data-popover-selected={isSelected ? "true" : undefined}
                              className={`flex items-center gap-2 rounded-lg border px-3 py-2 transition-colors ${isSelected
                                ? "border-purple-500 bg-purple-500/20"
                                : "border-white/10 bg-white/5 hover:border-white/30"
                                }`}
                            >
                              <button
                                type="button"
                                onClick={() => {
                                  setSelectedVideo(v.id);
                                  close();
                                }}
                                className="min-w-0 flex-1 text-left"
                              >
                                <span className="block truncate text-sm text-white">{v.name}</span>
                              </button>

                              <button
                                type="button"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handlePreviewVideo(v.id);
                                }}
                                onMouseEnter={() => {
                                  const src = v.path.startsWith("/") ? v.path : `/${v.path}`;
                                  const prefetch = document.createElement("link");
                                  prefetch.rel = "preload";
                                  prefetch.as = "video";
                                  prefetch.href = src;
                                  document.head.appendChild(prefetch);
                                  setTimeout(() => prefetch.remove(), 2000);
                                }}
                                className="p-1 text-gray-400 hover:text-purple-300"
                                title="预览"
                              >
                                <Eye className="h-4 w-4" />
                              </button>

                              {isSelected && <Check className="h-4 w-4 text-purple-300" />}
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                )}
              </SelectPopover>
            </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) => titleInput.handleChange(e.target.value)}
                    onCompositionStart={titleInput.handleCompositionStart}
                    onCompositionEnd={(e) => titleInput.handleCompositionEnd(e.currentTarget.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="block mb-1">
                        {platformIcons[account.platform] ? (
                          <Image
                            src={platformIcons[account.platform].src}
                            alt={platformIcons[account.platform].alt}
                            width={28}
                            height={28}
                            className="h-7 w-7 mx-auto"
                          />
                        ) : (
                          <span className="text-2xl">🌐</span>
                        )}
                      </span>
                      <span className="text-white text-sm">{account.name}</span>
                    </button>
                  ))}
              </div>
            </div>

            {/* 发布按钮 */}
            <button
              onClick={handlePublish}
              disabled={isPublishing || selectedPlatforms.length === 0}
              className="w-full py-4 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-xl font-bold text-lg hover:shadow-lg hover:from-purple-500 hover:to-pink-500 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isPublishing ? (
                <span className="flex items-center justify-center gap-2">
                  <Loader2 className="h-5 w-5 animate-spin" />
                  正在发布...请勿刷新或关闭网页
                </span>
              ) : "立即发布"}
            </button>

            {/* 发布结果 */}
            {publishResults.length > 0 && (
              <div className="space-y-3">
                {publishResults.map((result, index) => (
                  <div
                    key={index}
                    className={`p-4 rounded-xl border ${result.success
                      ? "border-green-500/50 bg-green-500/10"
                      : "border-red-500/50 bg-red-500/10"
                      }`}
                  >
                    <div className="flex items-center gap-2 mb-1">
                      {platformIcons[result.platform] ? (
                        <Image
                          src={platformIcons[result.platform].src}
                          alt={platformIcons[result.platform].alt}
                          width={20}
                          height={20}
                          className="h-5 w-5"
                        />
                      ) : (
                        <span className="text-lg">🌐</span>
                      )}
                      <span className={`font-medium ${result.success ? "text-green-400" : "text-red-400"}`}>
                        {result.success ? "发布成功" : "发布失败"}
                      </span>
                    </div>
                    <p className="text-sm text-gray-300">{result.message}</p>
                    {result.success && result.screenshot_url && (
                      <div className="mt-3 rounded-lg border border-white/10 bg-black/20 p-2">
                        <p className="text-xs text-gray-400 mb-2">发布成功截图</p>
                        <a
                          href={result.screenshot_url}
                          target="_blank"
                          rel="noreferrer"
                          className="block"
                        >
                          <Image
                            src={result.screenshot_url}
                            alt="发布成功截图"
                            width={400}
                            height={300}
                            className="w-full rounded-md border border-white/10"
                            unoptimized
                          />
                        </a>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
