import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import {
  ClockCircleOutlined,
  MessageOutlined,
  PlusOutlined,
  ReloadOutlined,
} from "@ant-design/icons"
import { Badge, Button, Card, Empty, Space, Table, Tabs, Tag, Typography, type TableColumnsType } from "antd"
import { toast } from "../utils/toast"
import { listTickets, type TicketStatus, type TicketSummary } from "../api/tickets"
import { TICKET_PRIORITY_META, TICKET_STATUS_META, TICKET_STATUS_TABS } from "../utils/ticketMeta"

const { Title, Paragraph, Text } = Typography

function formatDate(value?: string | null) {
  if (!value) return "-"
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleString("zh-CN", { hour12: false })
}

function errorDetail(error: unknown, fallback: string) {
  return (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || fallback
}

export default function Tickets() {
  const [tickets, setTickets] = useState<TicketSummary[]>([])
  const [activeStatus, setActiveStatus] = useState<"all" | TicketStatus>("all")
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const status = activeStatus === "all" ? undefined : activeStatus

  const loadTickets = useCallback(async (silent = false) => {
    if (silent) setRefreshing(true)
    else setLoading(true)
    try {
      const res = await listTickets({ status, limit: 100 })
      setTickets(res.data.data ?? [])
    } catch (error) {
      toast.error(errorDetail(error, "工单列表加载失败"))
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [status])

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

  // Poll with visibility awareness — stops polling when tab is hidden
  useEffect(() => {
    let timer: number
    const startPolling = () => {
      timer = window.setInterval(() => {
        void loadTickets(true)
      }, 30000)
    }
    const handleVisibility = () => {
      window.clearInterval(timer)
      if (document.visibilityState === "visible") {
        void loadTickets(true)
        startPolling()
      }
    }
    startPolling()
    document.addEventListener("visibilitychange", handleVisibility)
    return () => {
      window.clearInterval(timer)
      document.removeEventListener("visibilitychange", handleVisibility)
    }
  }, [loadTickets])

  const columns = useMemo<TableColumnsType<TicketSummary>>(() => [
    {
      title: "工单",
      dataIndex: "subject",
      render: (_: string, record) => (
        <Space orientation="vertical" size={2}>
          <Link to={`/tickets/${record.id}`}>
            <Badge dot={record.unread_count > 0}>
              <Text strong>{record.subject}</Text>
            </Badge>
          </Link>
          <Space size={8} wrap>
            <Text code style={{ fontSize: 12 }}>{record.ticket_no}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>{record.department_name || "未分配部门"}</Text>
            {record.instance && <Text type="secondary" style={{ fontSize: 12 }}>实例 #{record.instance.id}</Text>}
          </Space>
        </Space>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 120,
      render: (value: TicketStatus) => {
        const meta = TICKET_STATUS_META[value]
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "优先级",
      dataIndex: "priority",
      width: 110,
      render: (value: keyof typeof TICKET_PRIORITY_META) => {
        const meta = TICKET_PRIORITY_META[value]
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "消息",
      dataIndex: "message_count",
      width: 100,
      align: "right",
      render: (value: number, record) => (
        <Space size={6}>
          <MessageOutlined />
          <Text>{value}</Text>
          {record.unread_count > 0 && <Tag color="red">{record.unread_count} 新</Tag>}
        </Space>
      ),
    },
    {
      title: "最后更新",
      dataIndex: "last_message_at",
      width: 190,
      render: (value: string | null) => (
        <Space size={6}>
          <ClockCircleOutlined />
          <Text type="secondary">{formatDate(value)}</Text>
        </Space>
      ),
    },
    {
      title: "操作",
      key: "action",
      width: 110,
      align: "right",
      render: (_: unknown, record) => (
        <Link to={`/tickets/${record.id}`}>
          <Button size="small">查看详情</Button>
        </Link>
      ),
    },
  ], [])

  return (
    <Space orientation="vertical" size={24} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ margin: 0 }}>工单支持</Title>
        <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
          提交售前、技术、财务和会员伙伴相关问题，并查看处理进度。
        </Paragraph>
      </div>

      <Card
        variant="outlined"
        title={<Space><MessageOutlined /> 我的工单</Space>}
        extra={(
          <Space wrap>
            <Button icon={<ReloadOutlined />} loading={refreshing} onClick={() => loadTickets(true)}>
              刷新
            </Button>
            <Link to="/tickets/new">
              <Button type="primary" icon={<PlusOutlined />}>创建工单</Button>
            </Link>
          </Space>
        )}
      >
        <Tabs
          activeKey={activeStatus}
          onChange={(key) => setActiveStatus(key as "all" | TicketStatus)}
          items={TICKET_STATUS_TABS.map((item) => ({ key: item.key, label: item.label }))}
        />
        {tickets.length === 0 && !loading ? (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无工单">
            <Link to="/tickets/new">
              <Button type="primary" icon={<PlusOutlined />}>创建第一个工单</Button>
            </Link>
          </Empty>
        ) : (
          <Table
            rowKey="id"
            loading={loading}
            dataSource={tickets}
            columns={columns}
            pagination={{ pageSize: 10, showSizeChanger: false }}
          />
        )}
      </Card>
    </Space>
  )
}
