'use client'

import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Header } from '@/components/layout/header'
import { WxUserDetailDialog } from '@/components/wx-users/wx-user-detail-dialog'
import { Spinner } from '@/components/ui/spinner'
import { WxUser, WxUserWithProgress } from '@/types'
import { apiFetch } from '@/lib/api'
import { Search } from 'lucide-react'

interface UsersResponse {
  users: WxUser[]
  meta: { total: number; page: number; limit: number; totalPages: number }
}

export default function WxUsersPage() {
  const [search, setSearch] = useState('')
  const [selectedUser, setSelectedUser] = useState<WxUser | null>(null)
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const queryClient = useQueryClient()

  const { data, isLoading, error } = useQuery<UsersResponse>({
    queryKey: ['wx-users', search],
    queryFn: async () => {
      const res = await apiFetch(`/api/wx-users?search=${encodeURIComponent(search)}`)
      if (!res.ok) throw new Error('Failed to fetch wx users')
      return res.json()
    },
  })

  const { data: userDetails } = useQuery<WxUserWithProgress>({
    queryKey: ['wx-users', selectedUser?.id],
    queryFn: async () => {
      const res = await apiFetch(`/api/wx-users/${selectedUser?.id}`)
      if (!res.ok) throw new Error('Failed to fetch wx user details')
      return res.json()
    },
    enabled: !!selectedUser && isDialogOpen,
  })

  const handleUserClick = (user: WxUser) => {
    setSelectedUser(user)
    setIsDialogOpen(true)
  }

  const handleDialogOpenChange = (open: boolean) => {
    setIsDialogOpen(open)
    if (!open) {
      setSelectedUser(null)
    }
  }

  const handleDeleted = () => {
    queryClient.invalidateQueries({ queryKey: ['wx-users'] })
  }

  const formatDate = (date: Date | string) => {
    return new Date(date).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  if (isLoading) {
    return (
      <div className="h-screen flex flex-col">
        <Header />
        <div className="flex-1 flex items-center justify-center">
          <Spinner size="lg" />
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="h-screen flex flex-col">
        <Header />
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <p className="text-red-600">加载失败</p>
            <Button className="mt-4" onClick={() => window.location.reload()}>
              重试
            </Button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="h-screen flex flex-col">
      <Header />
      <div className="flex-1 overflow-auto p-6">
        <div className="max-w-6xl mx-auto">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h1 className="text-2xl font-bold">小程序账户</h1>
              <p className="text-gray-500 mt-1">
                共 {data?.meta?.total || 0} 个账户
              </p>
            </div>
          </div>

          <div className="relative mb-6 max-w-sm">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              type="text"
              placeholder="搜索昵称或 OpenID..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-10"
            />
          </div>

          <div className="bg-white rounded-lg shadow overflow-hidden">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    用户
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    OpenID
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    积分
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    注册时间
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {data?.users?.map((user) => (
                  <tr
                    key={user.id}
                    className="hover:bg-gray-50 cursor-pointer"
                    onClick={() => handleUserClick(user)}
                  >
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        {user.avatarUrl ? (
                          <img
                            src={user.avatarUrl}
                            alt={user.nickname || 'User'}
                            className="h-10 w-10 rounded-full object-cover mr-3"
                          />
                        ) : (
                          <div className="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center mr-3 text-gray-600 font-medium">
                            {user.nickname?.[0]?.toUpperCase() || 'U'}
                          </div>
                        )}
                        <span className="text-sm font-medium text-gray-900">
                          {user.nickname || '匿名用户'}
                        </span>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="text-sm text-gray-500 font-mono text-xs">
                        {user.openid}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                        {user.points}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {formatDate(user.createdAt)}
                    </td>
                  </tr>
                ))}
                {data?.users?.length === 0 && (
                  <tr>
                    <td colSpan={4} className="px-6 py-12 text-center text-gray-500">
                      暂无账户数据
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <WxUserDetailDialog
        open={isDialogOpen}
        onOpenChange={handleDialogOpenChange}
        user={userDetails}
        onDeleted={handleDeleted}
      />
    </div>
  )
}
