/**
 * 账号管理页面 — V21 Design System
 *
 * 展示多平台账号绑定状态（抖音/快手/小红书/微信视频号）
 * 支持绑定/解绑操作
 *
 * 零 antd 直接导入，全部使用 CSS 变量
 */
import React, { useState, useCallback } from "react";
import { useQueries, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui";
import PageHead from "@/components/layout/PageHead";
import {
  PLATFORMS,
  getAccountsByPlatform,
  unbindAccount,
  bindAccount,
  ACCOUNT_STATUS_CONFIG,
  type Platform,
  type Account,
  type PlatformId,
} from "@/api/accounts";
import "./accounts.css";

/* ── Toast 系统 ─────────────────────────────────────────── */

interface Toast {
  id: number;
  message: string;
  type: "success" | "error";
}

let toastIdCounter = 0;

/* ── 平台卡片组件 ───────────────────────────────────────── */

interface PlatformCardProps {
  platform: Platform;
  accounts: Account[];
  isLoading: boolean;
  onBind: (platformId: PlatformId) => void;
  onUnbind: (accountId: string, accountName: string) => void;
}

const PlatformCard: React.FC<PlatformCardProps> = ({
  platform,
  accounts,
  isLoading,
  onBind,
  onUnbind,
}) => {
  return (
    <div className="acc-card">
      {/* 平台头部 */}
      <div className="acc-card-header">
        <div
          className="acc-card-icon"
          style={{ background: platform.gradient }}
        >
          {platform.icon}
        </div>
        <div>
          <h3 className="acc-card-title">{platform.name}</h3>
          <p className="acc-card-subtitle">{platform.subName}</p>
        </div>
      </div>

      {/* 账号列表 */}
      <div className="acc-account-list">
        {isLoading ? (
          <div className="acc-empty">
            <p className="acc-empty-text">加载中…</p>
          </div>
        ) : accounts.length > 0 ? (
          accounts.map((account) => {
            const statusCfg = ACCOUNT_STATUS_CONFIG[account.status];
            return (
              <div key={account.id} className="acc-account-row">
                <div
                  className="acc-account-avatar"
                  style={{ background: platform.gradient }}
                >
                  {account.avatar || platform.icon}
                </div>
                <div className="acc-account-info">
                  <div className="acc-account-name">{account.name}</div>
                  <span className={`acc-status-pill ${statusCfg.className}`}>
                    {statusCfg.label}
                  </span>
                </div>
                <Button
                  buttonType="ghost"
                  buttonSize="sm"
                  onClick={() => onUnbind(account.id, account.name)}
                >
                  解绑
                </Button>
              </div>
            );
          })
        ) : (
          <div className="acc-empty">
            <div className="acc-empty-icon">🔓</div>
            <p className="acc-empty-text">暂未绑定账号</p>
          </div>
        )}
      </div>

      {/* 绑定按钮 */}
      <Button buttonType="ghost" onClick={() => onBind(platform.id)}>
        + 绑定新账号
      </Button>
    </div>
  );
};

/* ── 主页面 ─────────────────────────────────────────────── */

const Accounts: React.FC = () => {
  const queryClient = useQueryClient();
  const [toasts, setToasts] = useState<Toast[]>([]);

  /** 显示 toast */
  const showToast = useCallback((message: string, type: Toast["type"]) => {
    const id = ++toastIdCounter;
    setToasts((prev) => [...prev, { id, message, type }]);
    setTimeout(() => {
      setToasts((prev) => prev.filter((t) => t.id !== id));
    }, 3000);
  }, []);

  /** 查询所有平台的账号 */
  const _queriesResults = useQueries({
    queries: PLATFORMS.map((platform) => ({
      queryKey: ["accounts", platform.id] as const,
      queryFn: () => getAccountsByPlatform(platform.id),
    })),
  });
  const accountQueries = PLATFORMS.map((platform, i) => ({
    platform,
    ..._queriesResults[i],
  }));

  /** 解绑 mutation */
  const unbindMutation = useMutation({
    mutationFn: unbindAccount,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["accounts"] });
      showToast("已解绑账号", "success");
    },
    onError: () => {
      showToast("解绑失败", "error");
    },
  });

  /** 绑定 mutation（mock） */
  const bindMutation = useMutation({
    mutationFn: bindAccount,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["accounts"] });
      showToast("账号绑定成功", "success");
    },
    onError: () => {
      showToast("绑定失败", "error");
    },
  });

  /** 绑定新账号（mock：直接创建） */
  const handleBind = (platformId: PlatformId) => {
    const platform = PLATFORMS.find((p) => p.id === platformId);
    if (!platform) return;

    const name = window.prompt(`请输入要绑定的${platform.name}账号名称：`);
    if (name && name.trim()) {
      bindMutation.mutate({ platform_id: platformId, name: name.trim() });
    }
  };

  /** 解绑账号 */
  const handleUnbind = (accountId: string, accountName: string) => {
    if (window.confirm(`确定解绑账号「${accountName}」吗？`)) {
      unbindMutation.mutate(accountId);
    }
  };

  /** 统计已绑定账号数 */
  const totalBound = accountQueries.reduce(
    (sum, q) => sum + (q.data?.length ?? 0),
    0,
  );
  const totalPlatforms = PLATFORMS.length;

  return (
    <div className="acc-page">
      <PageHead
        title="🔑 账号管理"
        description="绑定您的社交平台账号，用于视频一键发布到各平台"
      />

      {/* 平台卡片网格 */}
      <div className="acc-grid">
        {accountQueries.map(({ platform, data, isLoading }) => (
          <PlatformCard
            key={platform.id}
            platform={platform}
            accounts={data ?? []}
            isLoading={isLoading}
            onBind={handleBind}
            onUnbind={handleUnbind}
          />
        ))}
      </div>

      {/* 底部统计栏 */}
      <div className="acc-stats-bar">
        <span className="acc-stats-icon">📊</span>
        <span className="acc-stats-text">
          已绑定 <span className="acc-stats-highlight">{totalBound}</span>{" "}
          个账号 / 支持{" "}
          <span className="acc-stats-highlight">{totalPlatforms}</span> 个平台
        </span>
      </div>

      {/* Toast 提示 */}
      {toasts.length > 0 && (
        <div className="vc-toast-container">
          {toasts.map((t) => (
            <div key={t.id} className={`vc-toast vc-toast--${t.type}`}>
              {t.type === "success" ? "✅" : "❌"} {t.message}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default Accounts;
