import { useMemo, useState } from "react"
import DOMPurify from "dompurify"
import {
  Alert,
  Button,
  Card,
  Descriptions,
  Popconfirm,
  Space,
  Tag,
  Typography,
} from "antd"
import {
  CopyOutlined,
  LinkOutlined,
} from "@ant-design/icons"
import {
  runPluginAction,
  type ServerDetail,
} from "../../api/servers"
import { toast } from "../../utils/toast"
import { copyText, formatDate } from "./helpers"

const { Text } = Typography

const ACTIONABLE_STATUSES = new Set(["active", "suspended", "provision_failed"])

function SafeHtml({ html }: { html: string }) {
  return (
    <div
      style={{ minHeight: 120, overflow: "auto" }}
      dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }}
    />
  )
}

type PluginManageTabProps = {
  server: ServerDetail
  actionLoading: string | null
  onActionLoading: (key: string | null) => void
  onServerRefresh: () => void
}

export default function PluginManageTab({
  server,
  actionLoading,
  onActionLoading,
  onServerRefresh,
}: PluginManageTabProps) {
  const actions = server.plugin_manage_actions ?? []
  const links = server.plugin_links ?? []
  const manageTabs = useMemo(() => {
    const page = server.provision_plugin?.manage_page
    const tabs = page?.tabs?.filter((tab) => tab.key && tab.label) ?? []
    const result = [...tabs]
    if (page?.summary_html) {
      result.unshift({ key: "summary", label: "概览", html: page.summary_html })
    }
    if (result.length === 0 && page?.empty_state_html) {
      result.push({ key: "empty", label: "说明", html: page.empty_state_html })
    }
    return result
  }, [server.provision_plugin?.manage_page])
  const [activeTab, setActiveTab] = useState("")
  const actionsDisabled = !ACTIONABLE_STATUSES.has(server.status)

  const handlePluginAction = async (action: string, label: string) => {
    onActionLoading(`plugin:${action}`)
    try {
      const res = await runPluginAction(server.id, action)
      const data = res.data.data
      const message = typeof data?.message === "string" ? data.message : `${label}执行成功`
      toast.success(message)

      // 打开面板：从响应中提取 URL 并跳转
      const payload = data?.payload
      const url = typeof payload === "object" && payload !== null && "url" in payload
        ? (payload as { url?: unknown }).url
        : undefined
      if (url && typeof url === "string") {
        window.open(url, "_blank", "noopener,noreferrer")
      }

      onServerRefresh()
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || `${label}执行失败`)
    } finally {
      onActionLoading(null)
    }
  }

  return (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      {/* 失败状态提示 */}
      {server.status === "failed" && (
        <Alert
          type="error"
          showIcon
          message="开通失败"
          description="该产品开通时遇到错误，请联系管理员重新开通。开通成功后密码和面板入口才会显示。"
        />
      )}
      {server.status === "provisioning" && (
        <Alert
          type="info"
          showIcon
          message="正在开通中"
          description="产品正在自动开通，请稍后刷新页面查看。"
        />
      )}

      {/* 管理页 Tab */}
      {manageTabs.length > 0 && (
        <Card
          variant="outlined"
          styles={{ body: { padding: 0 } }}
          title={
            <div style={{ display: "flex", gap: 1, overflowX: "auto" }}>
              {manageTabs.map((tab) => (
                <button
                  key={tab.key}
                  type="button"
                  onClick={() => setActiveTab(tab.key)}
                  style={{
                    height: 40,
                    border: "none",
                    borderBottom: (activeTab || manageTabs[0]?.key) === tab.key ? "2px solid #1677ff" : "2px solid transparent",
                    background: "transparent",
                    padding: "0 16px",
                    fontSize: 14,
                    fontWeight: (activeTab || manageTabs[0]?.key) === tab.key ? 600 : 400,
                    color: (activeTab || manageTabs[0]?.key) === tab.key ? "#1677ff" : "#666",
                    cursor: "pointer",
                  }}
                >
                  {tab.label}
                </button>
              ))}
            </div>
          }
        >
          <div style={{ padding: 20, minHeight: 200 }}>
            {(manageTabs.find((t) => t.key === activeTab) ?? manageTabs[0])?.html
              ? <SafeHtml html={(manageTabs.find((t) => t.key === activeTab) ?? manageTabs[0])!.html} />
              : <Text type="secondary">暂无内容</Text>}
          </div>
        </Card>
      )}

      {/* 管理操作 */}
      {actions.length > 0 && (
        <Card variant="outlined" title="管理操作" styles={{ body: { padding: 20 } }}>
          <Space wrap>
            {actions.map((action) => {
              const button = (
                <Button
                  key={action.key}
                  danger={action.style === "danger"}
                  type={action.style === "primary" ? "primary" : "default"}
                  loading={actionLoading === `plugin:${action.key}`}
                  disabled={actionsDisabled}
                  onClick={action.confirm ? undefined : () => handlePluginAction(action.key, action.label)}
                >
                  {action.label}
                </Button>
              )
              return action.confirm ? (
                <Popconfirm
                  key={action.key}
                  title={`确认执行 ${action.label}？`}
                  okText="确认"
                  cancelText="取消"
                  onConfirm={() => handlePluginAction(action.key, action.label)}
                >
                  {button}
                </Popconfirm>
              ) : button
            })}
          </Space>
        </Card>
      )}

      {/* 基本信息 */}
      <Card variant="outlined" title="基本信息" styles={{ body: { padding: 20 } }}>
        <Descriptions column={1} labelStyle={{ width: 120 }}>
          <Descriptions.Item label="用户名">
            {server.hostname || "-"}
          </Descriptions.Item>
          <Descriptions.Item label="密码">
            {server.root_password ? (
              <Space>
                <Text code>********</Text>
                <Button size="small" icon={<CopyOutlined />} onClick={() => copyText(server.root_password!, "密码")}>复制</Button>
              </Space>
            ) : (
              <Text type="secondary">开通成功后设置</Text>
            )}
          </Descriptions.Item>
          <Descriptions.Item label="到期时间">
            <Tag color="blue" style={{ marginInlineEnd: 0 }}>{formatDate(server.expires_at)}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="产品">{server.product_name}</Descriptions.Item>
          {server.product_group_name && (
            <Descriptions.Item label="线路">{server.product_group_name}</Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      {/* 快捷入口 */}
      {links.length > 0 && (
        <Card variant="outlined" title="快捷入口" styles={{ body: { padding: 20 } }}>
          <Space wrap>
            {links.map((link) => {
              const isExternal = link.url.startsWith("http")
              return (
                <Button
                  key={link.label}
                  type="primary"
                  ghost
                  icon={<LinkOutlined />}
                  disabled={actionsDisabled}
                  onClick={() => {
                    if (isExternal) {
                      window.open(link.url, "_blank", "noopener,noreferrer")
                    } else {
                      window.location.href = link.url
                    }
                  }}
                >
                  {link.label}
                </Button>
              )
            })}
          </Space>
        </Card>
      )}
    </Space>
  )
}
