import { useCallback, useEffect, useMemo, useState } from "react"
import { useNavigate } from "react-router-dom"
import {
  CloudServerOutlined,
  DeleteOutlined,
  EyeOutlined,
  MoreOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  PoweroffOutlined,
  ReloadOutlined,
  SearchOutlined,
  SyncOutlined,
} from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Dropdown,
  Empty,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tag,
  Typography,
  type MenuProps,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import { listCloudServers, type CloudServer } from "../api/cloud_server"
import {
  batchOperateAdminInstances,
  listAdminInstances,
  operateAdminInstancePower,
  deleteAdminInstance,
  provisionAdminInstance,
  suspendAdminInstance,
  unsuspendAdminInstance,
  type AdminInstance,
  type AdminInstanceBatchAction,
  type AdminInstanceListResult,
  type AdminInstancePowerAction,
} from "../api/instances"

const { Title, Text } = Typography
type MenuClickInfo = Parameters<NonNullable<MenuProps["onClick"]>>[0]

const STATUS_META: Record<string, { label: string; color: string }> = {
  active: { label: "运行中", color: "success" },
  provisioning: { label: "开通中", color: "processing" },
  provision_failed: { label: "待处理", color: "error" },
  failed: { label: "开通失败", color: "error" },
  suspended: { label: "已暂停", color: "warning" },
  terminated: { label: "已销毁", color: "default" },
}

const POWER_LABEL: Record<AdminInstancePowerAction, string> = {
  "power-on": "开机",
  shutdown: "关机",
  "hard-shutdown": "强制关机",
  reboot: "重启",
}

const ACTION_LABEL: Record<AdminInstanceBatchAction, string> = {
  ...POWER_LABEL,
  suspend: "暂停",
  unsuspend: "解除暂停",
  delete: "删除",
  provision: "重新开通",
}

function yuan(cents: number | null | undefined) {
  return `¥${((cents ?? 0) / 100).toFixed(2)}`
}

function fmtDate(value: string | null | undefined) {
  if (!value) return "-"
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return "-"
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  })
}

function fmtMemory(value: number | null | undefined) {
  if (!value) return "-"
  if (value >= 1024) return `${(value / 1024).toFixed(value % 1024 === 0 ? 0 : 1)} GB`
  return `${value} MB`
}

function statusTag(value: string | null | undefined) {
  const meta = STATUS_META[value || ""] ?? { label: value || "未知", color: "default" }
  return <Tag color={meta.color}>{meta.label}</Tag>
}

function dueTag(value: string | null | undefined) {
  if (!value) return <Tag>无到期</Tag>
  const diff = new Date(value).getTime() - Date.now()
  if (Number.isNaN(diff)) return <Tag>到期异常</Tag>
  if (diff <= 0) return <Tag color="red">已到期</Tag>
  if (diff <= 3 * 86400 * 1000) return <Tag color="volcano">3 天内</Tag>
  if (diff <= 7 * 86400 * 1000) return <Tag color="orange">7 天内</Tag>
  return <Tag color="green">正常</Tag>
}

function userLabel(record: AdminInstance) {
  return record.user.label || record.user.nickname || record.user.username || record.user.email || `用户 #${record.user_id}`
}

function canOperatePower(record: AdminInstance) {
  return !!record.upstream_id && record.status !== "terminated"
}

function canSuspend(record: AdminInstance) {
  return record.status === "active" && !!record.upstream_id
}

function canUnsuspend(record: AdminInstance) {
  return record.status === "suspended" && !!record.upstream_id
}

function canDelete(record: AdminInstance) {
  return record.status !== "terminated"
}

function canProvision(record: AdminInstance) {
  return record.status === "provisioning" || record.status === "provision_failed"
}

export default function AdminInstances() {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)
  const [actionLoading, setActionLoading] = useState<string | null>(null)
  const [data, setData] = useState<AdminInstanceListResult>({ items: [], total: 0, limit: 50, offset: 0, summary: {} })
  const [cloudServers, setCloudServers] = useState<CloudServer[]>([])
  const [selectedIds, setSelectedIds] = useState<number[]>([])

  const [keywordInput, setKeywordInput] = useState("")
  const [keyword, setKeyword] = useState("")
  const [status, setStatus] = useState<string | undefined>()
  const [cloudServerId, setCloudServerId] = useState<number | undefined>()
  const [hasUpstream, setHasUpstream] = useState<boolean | undefined>()
  const [autoRenew, setAutoRenew] = useState<boolean | undefined>()
  const [dueDays, setDueDays] = useState<number | undefined>()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(50)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listAdminInstances({
        keyword,
        status,
        cloud_server_id: cloudServerId,
        has_upstream: hasUpstream,
        auto_renew: autoRenew,
        due_days: dueDays,
        limit: pageSize,
        offset: (page - 1) * pageSize,
      })
      setData(res.data ?? { items: [], total: 0, limit: pageSize, offset: 0, summary: {} })
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载实例列表失败")
    } finally {
      setLoading(false)
    }
  }, [autoRenew, cloudServerId, dueDays, hasUpstream, keyword, page, pageSize, status])

  useEffect(() => {
    void load()
  }, [load])

  useEffect(() => {
    void (async () => {
      try {
        const res = await listCloudServers()
        setCloudServers(res.data ?? [])
      } catch {
        setCloudServers([])
      }
    })()
  }, [])

  const summary = data.summary || {}
  const selectedRows = useMemo(
    () => data.items.filter((item) => selectedIds.includes(item.id)),
    [data.items, selectedIds],
  )

  const runRowAction = async (record: AdminInstance, action: AdminInstanceBatchAction) => {
    const key = `${action}-${record.id}`
    setActionLoading(key)
    try {
      if (action === "suspend") {
        await suspendAdminInstance(record.id)
      } else if (action === "unsuspend") {
        await unsuspendAdminInstance(record.id)
      } else if (action === "delete") {
        await deleteAdminInstance(record.id)
      } else if (action === "provision") {
        await provisionAdminInstance(record.id)
      } else {
        await operateAdminInstancePower(record.id, action)
      }
      toast.success(`${ACTION_LABEL[action]}指令已下发`)
      await load()
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || `${ACTION_LABEL[action]}失败`)
    } finally {
      setActionLoading(null)
    }
  }

  const confirmRowAction = (record: AdminInstance, action: AdminInstanceBatchAction) => {
    const label = ACTION_LABEL[action]
    Modal.confirm({
      title: `确认${label}实例？`,
      okText: label,
      cancelText: "取消",
      okButtonProps: { danger: action === "delete" || action === "hard-shutdown" },
      content: (
        <Space orientation="vertical" size={4}>
          <Text>{record.hostname || record.alias || `实例 #${record.id}`}</Text>
          <Text type="secondary">用户：{userLabel(record)}</Text>
        </Space>
      ),
      onOk: () => runRowAction(record, action),
    })
  }

  const runBatchAction = async (action: AdminInstanceBatchAction) => {
    if (selectedIds.length === 0) {
      toast.error("请先选择实例")
      return
    }
    setActionLoading(`batch-${action}`)
    try {
      const res = await batchOperateAdminInstances(action, { ids: selectedIds })
      const result = res.data
      toast.success(`${ACTION_LABEL[action]}完成：成功 ${result?.success ?? 0} 台，失败 ${result?.failed ?? 0} 台`)
      setSelectedIds([])
      await load()
    } catch (error: unknown) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || `批量${ACTION_LABEL[action]}失败`)
    } finally {
      setActionLoading(null)
    }
  }

  const confirmBatchAction = (action: AdminInstanceBatchAction) => {
    if (selectedIds.length === 0) {
      toast.error("请先选择实例")
      return
    }
    Modal.confirm({
      title: `确认批量${ACTION_LABEL[action]}？`,
      okText: `批量${ACTION_LABEL[action]}`,
      cancelText: "取消",
      okButtonProps: { danger: action === "delete" || action === "hard-shutdown" },
      content: (
        <Space orientation="vertical" size={4}>
          <Text>已选择 {selectedIds.length} 台实例。</Text>
          {selectedRows.slice(0, 5).map((item) => (
            <Text key={item.id} type="secondary">#{item.id} {item.hostname || item.alias || item.product_name}</Text>
          ))}
        </Space>
      ),
      onOk: () => runBatchAction(action),
    })
  }

  const rowActionItems = (record: AdminInstance): MenuProps["items"] => [
    { key: "power-on", label: "开机", icon: <PlayCircleOutlined />, disabled: !canOperatePower(record) },
    { key: "reboot", label: "重启", icon: <ReloadOutlined />, disabled: !canOperatePower(record) },
    { key: "shutdown", label: "关机", icon: <PoweroffOutlined />, disabled: !canOperatePower(record) },
    { key: "hard-shutdown", label: "强制关机", icon: <PoweroffOutlined />, danger: true, disabled: !canOperatePower(record) },
    { type: "divider" },
    { key: "suspend", label: "暂停", icon: <PauseCircleOutlined />, disabled: !canSuspend(record) },
    { key: "unsuspend", label: "解除暂停", icon: <PlayCircleOutlined />, disabled: !canUnsuspend(record) },
    { key: "provision", label: "重新开通", icon: <SyncOutlined />, disabled: !canProvision(record) },
    { type: "divider" },
    { key: "delete", label: "删除实例", icon: <DeleteOutlined />, danger: true, disabled: !canDelete(record) },
  ]

  const columns: TableColumnsType<AdminInstance> = [
    {
      title: "实例",
      dataIndex: "hostname",
      fixed: "left",
      width: 260,
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          <Text strong>{record.hostname || record.alias || `实例 #${record.id}`}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>
            #{record.id} · {record.product_name}
            {record.api_type === "plugin" && (
              <Tag color="purple" style={{ marginLeft: 4, fontSize: 10 }}>{record.provision_plugin?.name || "其他产品"}</Tag>
            )}
          </Text>
        </Space>
      ),
    },
    {
      title: "用户",
      width: 180,
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          <Button type="link" style={{ padding: 0, height: "auto" }} onClick={() => navigate(`/admin/users/${record.user_id}`)}>
            {userLabel(record)}
          </Button>
          <Text type="secondary" style={{ fontSize: 12 }}>#{record.user_id}</Text>
        </Space>
      ),
    },
    {
      title: "状态",
      width: 130,
      render: (_value, record) => (
        <Space orientation="vertical" size={4}>
          {statusTag(record.status)}
          {record.suspend_type ? <Tag>{record.suspend_type}</Tag> : null}
        </Space>
      ),
    },
    {
      title: "节点/上游",
      width: 180,
      render: (_value, record) => {
        if (record.api_type === "plugin") {
          return (
            <Space orientation="vertical" size={2}>
              <Text>{record.provision_plugin?.name || "其他产品"}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>
                ID：{record.upstream_id || record.hostname || "-"}
              </Text>
            </Space>
          )
        }
        return (
          <Space orientation="vertical" size={2}>
            <Text>{record.cloud_server_name || `节点 #${record.cloud_server_id || "-"}`}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              上游 ID：{record.upstream_id || "-"}
            </Text>
          </Space>
        )
      },
    },
    {
      title: "网络",
      width: 160,
      render: (_value, record) => {
        if (record.api_type === "plugin") {
          return (
            <Space orientation="vertical" size={2}>
              <Text>{record.hostname || "-"}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>上游账号</Text>
            </Space>
          )
        }
        return (
          <Space orientation="vertical" size={2}>
            <Text>{record.main_ip || "NAT 网络"}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              {record.in_bw ?? "-"} / {record.out_bw ?? "-"} Mbps
            </Text>
          </Space>
        )
      },
    },
    {
      title: "规格",
      width: 170,
      render: (_value, record) => {
        if (record.api_type === "plugin") {
          return <Text type="secondary">—</Text>
        }
        return (
          <Space orientation="vertical" size={2}>
            <Text>{record.cpu ?? "-"} vCPU / {fmtMemory(record.memory)}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              盘 {record.system_disk_size ?? "-"}G{record.data_disk_size ? ` + ${record.data_disk_size}G` : ""}
            </Text>
          </Space>
        )
      },
    },
    {
      title: "计费",
      width: 170,
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          <Text>{record.cycle} · {yuan(record.next_renew_amount)}</Text>
          <Space size={4}>
            {Number(record.auto_renew || 0) === 1 ? <Tag color="green">自动续费</Tag> : <Tag>手动续费</Tag>}
            {dueTag(record.expires_at)}
          </Space>
        </Space>
      ),
    },
    {
      title: "到期时间",
      dataIndex: "expires_at",
      width: 170,
      render: fmtDate,
    },
    {
      title: "开通",
      width: 150,
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          <Text>{record.provision_attempts ?? 0} 次</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{fmtDate(record.last_provision_at)}</Text>
        </Space>
      ),
    },
    {
      title: "操作",
      fixed: "right",
      align: "right",
      width: 150,
      render: (_value, record) => (
        <Space>
          <Button
            size="small"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/admin/instances/${record.id}`)}
          >
            详情
          </Button>
          <Dropdown
            trigger={["click"]}
            menu={{
              items: rowActionItems(record),
              onClick: (info: MenuClickInfo) => confirmRowAction(record, info.key as AdminInstanceBatchAction),
            }}
          >
            <Button size="small" icon={<MoreOutlined />} loading={actionLoading?.endsWith(`-${record.id}`)} />
          </Dropdown>
        </Space>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={16} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>实例管理</Title>
        </Col>
        <Col>
          <Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>
            刷新
          </Button>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}><Card variant="outlined"><Statistic title="全部实例" value={data.total} prefix={<CloudServerOutlined />} /></Card></Col>
        <Col xs={24} sm={12} xl={6}><Card variant="outlined"><Statistic title="运行中" value={summary.active ?? 0} /></Card></Col>
        <Col xs={24} sm={12} xl={6}><Card variant="outlined"><Statistic title="开通中" value={(summary.provisioning ?? 0) + (summary.provision_failed ?? 0)} /></Card></Col>
        <Col xs={24} sm={12} xl={6}><Card variant="outlined"><Statistic title="已暂停" value={summary.suspended ?? 0} /></Card></Col>
      </Row>

      <Card variant="outlined">
        <Space orientation="vertical" size={12} style={{ width: "100%" }}>
          <Row gutter={[12, 12]}>
            <Col xs={24} md={8} xl={6}>
              <Input
                allowClear
                prefix={<SearchOutlined />}
                value={keywordInput}
                placeholder="实例、IP、用户、产品、上游 ID"
                onChange={(event) => setKeywordInput(event.target.value)}
                onPressEnter={() => {
                  setKeyword(keywordInput.trim())
                  setPage(1)
                }}
              />
            </Col>
            <Col xs={12} md={4} xl={3}>
              <Select
                allowClear
                value={status}
                placeholder="状态"
                style={{ width: "100%" }}
                onChange={(value) => {
                  setStatus(value)
                  setPage(1)
                }}
                options={[
                  { value: "active", label: "运行中" },
                  { value: "provisioning", label: "开通中" },
                  { value: "provision_failed", label: "待处理" },
                  { value: "failed", label: "开通失败" },
                  { value: "suspended", label: "已暂停" },
                  { value: "terminated", label: "已销毁" },
                ]}
              />
            </Col>
            <Col xs={12} md={5} xl={4}>
              <Select
                allowClear
                value={cloudServerId}
                placeholder="节点"
                style={{ width: "100%" }}
                onChange={(value) => {
                  setCloudServerId(value)
                  setPage(1)
                }}
                options={cloudServers.map((item) => ({ value: item.id, label: item.name }))}
              />
            </Col>
            <Col xs={12} md={4} xl={3}>
              <Select
                allowClear
                value={hasUpstream}
                placeholder="上游"
                style={{ width: "100%" }}
                onChange={(value) => {
                  setHasUpstream(value)
                  setPage(1)
                }}
                options={[
                  { value: true, label: "已开通" },
                  { value: false, label: "未开通" },
                ]}
              />
            </Col>
            <Col xs={12} md={4} xl={3}>
              <Select
                allowClear
                value={autoRenew}
                placeholder="续费"
                style={{ width: "100%" }}
                onChange={(value) => {
                  setAutoRenew(value)
                  setPage(1)
                }}
                options={[
                  { value: true, label: "自动续费" },
                  { value: false, label: "手动续费" },
                ]}
              />
            </Col>
            <Col xs={12} md={4} xl={3}>
              <Select
                allowClear
                value={dueDays}
                placeholder="到期"
                style={{ width: "100%" }}
                onChange={(value) => {
                  setDueDays(value)
                  setPage(1)
                }}
                options={[
                  { value: 3, label: "3 天内" },
                  { value: 7, label: "7 天内" },
                  { value: 30, label: "30 天内" },
                ]}
              />
            </Col>
            <Col>
              <Space>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={() => {
                    setKeyword(keywordInput.trim())
                    setPage(1)
                  }}
                >
                  搜索
                </Button>
                <Button
                  onClick={() => {
                    setKeywordInput("")
                    setKeyword("")
                    setStatus(undefined)
                    setCloudServerId(undefined)
                    setHasUpstream(undefined)
                    setAutoRenew(undefined)
                    setDueDays(undefined)
                    setPage(1)
                  }}
                >
                  重置
                </Button>
              </Space>
            </Col>
          </Row>

          <Space wrap>
            <Text type="secondary">已选 {selectedIds.length} 台</Text>
            <Button disabled={!selectedIds.length} loading={actionLoading === "batch-power-on"} onClick={() => confirmBatchAction("power-on")}>批量开机</Button>
            <Button disabled={!selectedIds.length} loading={actionLoading === "batch-reboot"} onClick={() => confirmBatchAction("reboot")}>批量重启</Button>
            <Button disabled={!selectedIds.length} loading={actionLoading === "batch-suspend"} onClick={() => confirmBatchAction("suspend")}>批量暂停</Button>
            <Button disabled={!selectedIds.length} loading={actionLoading === "batch-unsuspend"} onClick={() => confirmBatchAction("unsuspend")}>批量解停</Button>
            <Button disabled={!selectedIds.length} loading={actionLoading === "batch-provision"} onClick={() => confirmBatchAction("provision")}>批量重新开通</Button>
            <Button danger disabled={!selectedIds.length} loading={actionLoading === "batch-delete"} onClick={() => confirmBatchAction("delete")}>批量删除</Button>
          </Space>
        </Space>
      </Card>

      <Card variant="outlined" title="实例列表">
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={data.items}
          rowSelection={{
            selectedRowKeys: selectedIds,
            onChange: (keys) => setSelectedIds(keys.map((key) => Number(key))),
          }}
          pagination={{
            current: page,
            pageSize,
            total: data.total,
            showSizeChanger: true,
            pageSizeOptions: [20, 50, 100, 200],
            showTotal: (total) => `共 ${total} 台`,
          }}
          onChange={(pagination) => {
            setPage(pagination.current || 1)
            setPageSize(pagination.pageSize || pageSize)
          }}
          scroll={{ x: 1660 }}
          locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无实例" /> }}
        />
      </Card>
    </Space>
  )
}
