import { useCallback, useEffect, useMemo, useState } from "react"
import { Link, useNavigate, useSearchParams } from "react-router-dom"
import { MessageOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, StarOutlined } from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Input,
  Rate,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tabs,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import {
  getAdminTicketStats,
  listAdminTicketDepartments,
  listAdminTicketStaff,
  listAdminTickets,
  type AdminTicketStats,
  type AdminTicketSummary,
} from "../api/tickets"
import type { TicketActor, TicketDepartment, TicketStatus } from "../../api/tickets"
import {
  ADMIN_TICKET_STATUS_GROUP_TABS,
  TICKET_PRIORITY_META,
  TICKET_STATUS_META,
  sumTicketStatuses,
  type AdminTicketStatusGroup,
} 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 AdminTickets() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const userIdFilter = Number(searchParams.get("user_id") || 0) || undefined
  const [departments, setDepartments] = useState<TicketDepartment[]>([])
  const [staff, setStaff] = useState<TicketActor[]>([])
  const [tickets, setTickets] = useState<AdminTicketSummary[]>([])
  const [stats, setStats] = useState<AdminTicketStats>({})
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [keyword, setKeyword] = useState("")
  const [searchKeyword, setSearchKeyword] = useState("")
  const [activeGroup, setActiveGroup] = useState<AdminTicketStatusGroup>("pending_staff")
  const [departmentId, setDepartmentId] = useState<number | undefined>()
  const [assigneeId, setAssigneeId] = useState<number | undefined>()
  const statusGroup = activeGroup === "all" ? undefined : activeGroup

  const loadDepartments = useCallback(async () => {
    try {
      const [departmentRes, staffRes] = await Promise.all([
        listAdminTicketDepartments(),
        listAdminTicketStaff(),
      ])
      setDepartments(departmentRes.data ?? [])
      setStaff(staffRes.data ?? [])
    } catch (error) {
      toast.error(errorDetail(error, "工单部门加载失败"))
    }
  }, [])

  const loadTickets = useCallback(async (silent = false) => {
    if (silent) setRefreshing(true)
    else setLoading(true)
    try {
      const [ticketRes, statsRes] = await Promise.all([
        listAdminTickets({
          keyword: searchKeyword.trim() || undefined,
          status_group: statusGroup,
          department_id: departmentId,
          assignee_id: assigneeId,
          user_id: userIdFilter,
          limit: 200,
        }),
        getAdminTicketStats(),
      ])
      setTickets(ticketRes.data ?? [])
      setStats(statsRes.data ?? {})
    } catch (error) {
      toast.error(errorDetail(error, "工单列表加载失败"))
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [assigneeId, departmentId, searchKeyword, statusGroup, userIdFilter])

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

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

  // Poll with visibility awareness
  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 activeGroupMeta = useMemo(
    () => ADMIN_TICKET_STATUS_GROUP_TABS.find((item) => item.key === activeGroup) ?? ADMIN_TICKET_STATUS_GROUP_TABS[0],
    [activeGroup],
  )

  const groupTabItems = useMemo(
    () => ADMIN_TICKET_STATUS_GROUP_TABS.map((item) => ({
      key: item.key,
      label: (
        <Space size={6}>
          <span>{item.label}</span>
          <Text type="secondary">{sumTicketStatuses(stats, item.statuses)}</Text>
        </Space>
      ),
    })),
    [stats],
  )

  const pendingStaffCount = sumTicketStatuses(stats, ADMIN_TICKET_STATUS_GROUP_TABS[0].statuses)
  const waitingUserCount = sumTicketStatuses(stats, ADMIN_TICKET_STATUS_GROUP_TABS[1].statuses)
  const finishedCount = (stats.resolved ?? 0) + (stats.closed ?? 0)

  const columns = useMemo<TableColumnsType<AdminTicketSummary>>(() => [
    {
      title: "工单",
      dataIndex: "subject",
      render: (_: string, record) => (
        <Space orientation="vertical" size={2}>
          <Link to={`/admin/tickets/${record.id}`}>
            <Text strong>{record.subject}</Text>
          </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>}
            {record.unread_count > 0 && <Tag color="red">{record.unread_count} 新</Tag>}
          </Space>
        </Space>
      ),
    },
    {
      title: "用户",
      dataIndex: "user",
      width: 160,
      render: (_: unknown, record) => record.user ? (
        <Space orientation="vertical" size={0}>
          <Text>{record.user.nickname || record.user.username}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>#{record.user.id}</Text>
        </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: "assignee",
      width: 140,
      render: (_: unknown, record) => record.assignee ? (
        <Text>{record.assignee.nickname || record.assignee.username}</Text>
      ) : <Text type="secondary">未分派</Text>,
    },
    {
      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: "last_message_at",
      width: 180,
      render: formatDate,
    },
    {
      title: "满意度",
      dataIndex: "satisfaction",
      width: 130,
      render: (_: unknown, record) => record.satisfaction ? (
        <Rate disabled value={record.satisfaction.rating} style={{ fontSize: 14 }} />
      ) : <Text type="secondary">未评</Text>,
    },
    {
      title: "操作",
      key: "action",
      width: 100,
      align: "right",
      render: (_: unknown, record) => (
        <Button size="small" onClick={() => navigate(`/admin/tickets/${record.id}`)}>处理</Button>
      ),
    },
  ], [navigate])

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ margin: 0 }}>工单列表</Title>
        <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
          按状态处理用户提交的售前、技术、财务和会员伙伴工单。
        </Paragraph>
      </div>

      <Row gutter={[12, 12]}>
        <Col xs={12} md={6} xl={4}>
          <Card variant="outlined"><Statistic title="待处理" value={pendingStaffCount} /></Card>
        </Col>
        <Col xs={12} md={6} xl={4}>
          <Card variant="outlined"><Statistic title="等待用户" value={waitingUserCount} /></Card>
        </Col>
        <Col xs={12} md={6} xl={4}>
          <Card variant="outlined"><Statistic title="已结束" value={finishedCount} /></Card>
        </Col>
        <Col xs={12} md={6} xl={4}>
          <Card variant="outlined"><Statistic title="后台未读" value={stats.unread ?? 0} /></Card>
        </Col>
        <Col xs={12} md={6} xl={4}>
          <Card variant="outlined">
            <Statistic
              title={<Space size={4}><StarOutlined /> 平均评分</Space>}
              value={stats.average_rating ?? "-"}
              suffix={stats.rated_count ? `(${stats.rated_count})` : undefined}
            />
          </Card>
        </Col>
      </Row>

      <Card
        variant="outlined"
        title={<Space><MessageOutlined /> 工单列表</Space>}
        extra={(
          <Space wrap>
            <Link to="/admin/tickets/departments">
              <Button icon={<SettingOutlined />}>部门配置</Button>
            </Link>
            <Link to="/admin/tickets/templates">
              <Button icon={<StarOutlined />}>回复模板</Button>
            </Link>
            <Button icon={<ReloadOutlined />} loading={refreshing} onClick={() => loadTickets(true)}>刷新</Button>
          </Space>
        )}
      >
        <Space orientation="vertical" size={16} style={{ width: "100%" }}>
          <Tabs
            activeKey={activeGroup}
            onChange={(key) => setActiveGroup(key as AdminTicketStatusGroup)}
            items={groupTabItems}
          />

          <Space wrap>
            {activeGroupMeta.statuses.map((statusKey) => {
              const meta = TICKET_STATUS_META[statusKey]
              return (
                <Tag key={statusKey} color={meta.color}>
                  {meta.label} {stats[statusKey] ?? 0}
                </Tag>
              )
            })}
          </Space>

          <Space wrap>
            <Input
              allowClear
              prefix={<SearchOutlined />}
              placeholder="搜索标题或工单号"
              value={keyword}
              onChange={(event) => setKeyword(event.target.value)}
              onPressEnter={() => {
                setSearchKeyword(keyword.trim())
                void loadTickets(true)
              }}
              style={{ width: 220 }}
            />
            <Select
              allowClear
              placeholder="全部部门"
              value={departmentId}
              onChange={(value) => setDepartmentId(value)}
              style={{ width: 180 }}
              options={departments.map((item) => ({ value: item.id, label: item.name }))}
            />
            <Select
              allowClear
              placeholder="全部负责人"
              value={assigneeId}
              onChange={(value) => setAssigneeId(value)}
              style={{ width: 180 }}
              options={staff.map((item) => ({ value: item.id, label: item.nickname || item.username }))}
            />
            <Button
              icon={<SearchOutlined />}
              onClick={() => {
                setSearchKeyword(keyword.trim())
                void loadTickets(true)
              }}
            >
              查询
            </Button>
          </Space>

          <Table
            rowKey="id"
            loading={loading}
            dataSource={tickets}
            columns={columns}
            pagination={{ pageSize: 10, showSizeChanger: false }}
          />
        </Space>
      </Card>
    </Space>
  )
}
