import { useState, useMemo } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import api from '@/lib/api'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { UserPlus, Trash2, X, KeyRound, Users, Edit2 } from 'lucide-react'

const ROLE_LABELS: Record<string, string> = {
  hq: '总部管理员',
  regional: '区域经理',
  store: '店长',
  dept: '商品部',
}

interface StoreInfo {
  store_code: string
  store_name: string
  region: string
  business_type: string
  business_area: string | null
}

export function TenantUsersPage() {
  const qc = useQueryClient()
  const [showAdd, setShowAdd] = useState(false)
  const [showEdit, setShowEdit] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const [editUserId, setEditUserId] = useState<number | null>(null)
  const [addForm, setAddForm] = useState({ username: '', password: '', role: 'regional', name: '', store_code: '', region: '', dept: '' })
  const [editForm, setEditForm] = useState({ store_code: '', region: '', dept: '' })
  const [passwordForm, setPasswordForm] = useState('')
  const [storeFilter, setStoreFilter] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['tenant-users'],
    queryFn: () => api.get('/admin/tenant/users'),
  })

  const { data: storesData } = useQuery({
    queryKey: ['tenant-stores'],
    queryFn: () => api.get('/admin/tenant/stores'),
  })

  const stores: StoreInfo[] = (storesData as any)?.data || []

  const storeMap = useMemo(() => {
    const m: Record<string, StoreInfo> = {}
    for (const s of stores) m[s.store_code] = s
    return m
  }, [stores])

  const storeNames = (codes: string) => {
    if (!codes) return ''
    return codes.split(',').map(c => c.trim()).filter(Boolean).map(c => storeMap[c]?.store_name || c).join(', ')
  }

  const addUser = useMutation({
    mutationFn: (data: any) => api.post('/admin/tenant/users', data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tenant-users'] })
      setShowAdd(false)
      setAddForm({ username: '', password: '', role: 'regional', name: '', store_code: '', region: '', dept: '' })
    },
  })

  const deleteUser = useMutation({
    mutationFn: (userId: number) => api.delete(`/admin/tenant/users/${userId}`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['tenant-users'] }),
  })

  const updatePassword = useMutation({
    mutationFn: ({ userId, password }: { userId: number; password: string }) =>
      api.put(`/admin/tenant/users/${userId}/password`, { password }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tenant-users'] })
      setShowPassword(false)
      setPasswordForm('')
      setEditUserId(null)
    },
  })

  const updateUser = useMutation({
    mutationFn: ({ userId, data }: { userId: number; data: any }) =>
      api.put(`/admin/tenant/users/${userId}`, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tenant-users'] })
      setShowEdit(false)
      setEditUserId(null)
    },
  })

  if (isLoading) return <LoadingSpinner text="加载用户列表..." />

  const users = (data as any)?.data || []

  const filteredStores = storeFilter
    ? stores.filter(s => s.store_name.includes(storeFilter) || s.region.includes(storeFilter) || s.store_code.includes(storeFilter))
    : stores

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="flex items-center gap-2 text-xl font-bold">
            <Users size={22} className="text-primary" />
            用户管理
          </h1>
          <p className="mt-0.5 text-xs text-muted-foreground">管理本租户的用户账号与权限</p>
        </div>
        <button
          onClick={() => setShowAdd(true)}
          className="flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground"
        >
          <UserPlus size={16} /> 添加用户
        </button>
      </div>

      <div className="overflow-hidden rounded-lg border bg-card">
        <table className="w-full text-sm">
          <thead className="bg-muted/50">
            <tr>
              <th className="px-4 py-2 text-left text-xs font-medium text-muted-foreground whitespace-nowrap">用户名</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-muted-foreground whitespace-nowrap">姓名</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-muted-foreground whitespace-nowrap">角色</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-muted-foreground">关联信息</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-muted-foreground whitespace-nowrap">状态</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-muted-foreground whitespace-nowrap">创建时间</th>
              <th className="px-4 py-2 text-right text-xs font-medium text-muted-foreground whitespace-nowrap">操作</th>
            </tr>
          </thead>
          <tbody>
            {users.map((u: any) => (
              <tr key={u.id} className="border-t">
                <td className="px-4 py-2 font-medium whitespace-nowrap">{u.username}</td>
                <td className="px-4 py-2 whitespace-nowrap">{u.name}</td>
                <td className="px-4 py-2 whitespace-nowrap">
                  <span className="rounded bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-700">
                    {ROLE_LABELS[u.role] || u.role}
                  </span>
                </td>
                <td className="px-4 py-2 text-xs text-muted-foreground max-w-xs">
                  <div className="space-y-0.5">
                    {u.store_code && <div>门店: {storeNames(u.store_code)}</div>}
                    {u.region && <div>管辖门店: {storeNames(u.region)}</div>}
                    {u.dept && <div>部门: {u.dept}</div>}
                    {!u.store_code && !u.region && !u.dept && '-'}
                  </div>
                </td>
                <td className="px-4 py-2">
                  <span className={u.is_active ? 'text-green-600' : 'text-gray-400'}>
                    {u.is_active ? '启用' : '禁用'}
                  </span>
                </td>
                <td className="px-4 py-2 text-xs text-muted-foreground">
                  {u.created_at ? String(u.created_at).substring(0, 10) : '-'}
                </td>
                <td className="px-4 py-2 text-right">
                  <div className="flex items-center justify-end gap-1">
                    <button
                      onClick={() => {
                        setEditUserId(u.id)
                        setEditForm({ store_code: u.store_code || '', region: u.region || '', dept: u.dept || '' })
                        setShowEdit(true)
                        setStoreFilter('')
                      }}
                      className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-blue-600 hover:bg-blue-50"
                      title="编辑关联门店"
                    >
                      <Edit2 size={12} />
                    </button>
                    <button
                      onClick={() => {
                        setEditUserId(u.id)
                        setShowPassword(true)
                        setPasswordForm('')
                      }}
                      className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-amber-600 hover:bg-amber-50"
                      title="修改密码"
                    >
                      <KeyRound size={12} />
                    </button>
                    <button
                      onClick={() => {
                        if (confirm(`确认删除用户 ${u.username}？`)) deleteUser.mutate(u.id)
                      }}
                      className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-red-600 hover:bg-red-50"
                    >
                      <Trash2 size={12} />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {users.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-8 text-center text-xs text-muted-foreground">暂无用户</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 添加用户弹窗 */}
      {showAdd && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="w-96 rounded-lg border bg-card p-5 shadow-lg">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-sm font-bold">添加用户</h2>
              <button onClick={() => setShowAdd(false)}>
                <X size={16} className="text-muted-foreground" />
              </button>
            </div>
            <div className="space-y-3">
              <div>
                <label className="text-xs text-muted-foreground">用户名</label>
                <input
                  value={addForm.username}
                  onChange={(e) => setAddForm({ ...addForm, username: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">密码</label>
                <input
                  value={addForm.password}
                  onChange={(e) => setAddForm({ ...addForm, password: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">角色</label>
                <select
                  value={addForm.role}
                  onChange={(e) => setAddForm({ ...addForm, role: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                >
                  <option value="regional">区域经理</option>
                  <option value="store">店长</option>
                  <option value="dept">商品部</option>
                </select>
              </div>
              <div>
                <label className="text-xs text-muted-foreground">姓名</label>
                <input
                  value={addForm.name}
                  onChange={(e) => setAddForm({ ...addForm, name: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              {addForm.role === 'store' && (
                <div>
                  <label className="text-xs text-muted-foreground">所属门店（多选）</label>
                  <input
                    value={storeFilter}
                    onChange={(e) => setStoreFilter(e.target.value)}
                    placeholder="搜索门店名称或区域..."
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                  <div className="mt-1 max-h-40 overflow-y-auto rounded-md border p-2 space-y-1">
                    {filteredStores.map(s => {
                      const selected = addForm.store_code.split(',').map(c => c.trim()).includes(s.store_code)
                      return (
                        <label key={s.store_code} className="flex items-center gap-2 text-xs cursor-pointer hover:bg-muted/50 rounded px-1 py-0.5">
                          <input
                            type="checkbox"
                            checked={selected}
                            onChange={(e) => {
                              const codes = addForm.store_code.split(',').map(c => c.trim()).filter(Boolean)
                              if (e.target.checked) {
                                setAddForm({ ...addForm, store_code: [...codes, s.store_code].join(',') })
                              } else {
                                setAddForm({ ...addForm, store_code: codes.filter(c => c !== s.store_code).join(',') })
                              }
                            }}
                          />
                          <span>{s.store_name}</span>
                          <span className="text-muted-foreground">{s.region}</span>
                        </label>
                      )
                    })}
                  </div>
                  {addForm.store_code && (
                    <p className="mt-1 text-xs text-muted-foreground">已选 {addForm.store_code.split(',').filter(Boolean).length} 家门店</p>
                  )}
                </div>
              )}
              {addForm.role === 'regional' && (
                <div>
                  <label className="text-xs text-muted-foreground">管辖门店（多选）</label>
                  <input
                    value={storeFilter}
                    onChange={(e) => setStoreFilter(e.target.value)}
                    placeholder="搜索门店名称或区域..."
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                  <div className="mt-1 max-h-40 overflow-y-auto rounded-md border p-2 space-y-1">
                    {filteredStores.map(s => {
                      const selected = addForm.region.split(',').map(c => c.trim()).includes(s.store_code)
                      return (
                        <label key={s.store_code} className="flex items-center gap-2 text-xs cursor-pointer hover:bg-muted/50 rounded px-1 py-0.5">
                          <input
                            type="checkbox"
                            checked={selected}
                            onChange={(e) => {
                              const codes = addForm.region.split(',').map(c => c.trim()).filter(Boolean)
                              if (e.target.checked) {
                                setAddForm({ ...addForm, region: [...codes, s.store_code].join(',') })
                              } else {
                                setAddForm({ ...addForm, region: codes.filter(c => c !== s.store_code).join(',') })
                              }
                            }}
                          />
                          <span>{s.store_name}</span>
                          <span className="text-muted-foreground">{s.region}</span>
                        </label>
                      )
                    })}
                  </div>
                  {addForm.region && (
                    <p className="mt-1 text-xs text-muted-foreground">已选 {addForm.region.split(',').filter(Boolean).length} 家门店</p>
                  )}
                </div>
              )}
              {addForm.role === 'dept' && (
                <div>
                  <label className="text-xs text-muted-foreground">部门</label>
                  <input
                    value={addForm.dept}
                    onChange={(e) => setAddForm({ ...addForm, dept: e.target.value })}
                    placeholder="如：商品部"
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
              )}
              {addUser.isError && (
                <p className="text-xs text-red-600">{(addUser.error as any)?.data?.error || '添加失败'}</p>
              )}
              <button
                onClick={() => addUser.mutate(addForm)}
                disabled={!addForm.username || !addForm.password}
                className="w-full rounded-md bg-primary py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"
              >
                添加
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 编辑用户弹窗 */}
      {showEdit && editUserId !== null && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="w-96 rounded-lg border bg-card p-5 shadow-lg">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-sm font-bold">编辑关联门店</h2>
              <button onClick={() => { setShowEdit(false); setEditUserId(null) }}>
                <X size={16} className="text-muted-foreground" />
              </button>
            </div>
            <div className="space-y-3">
              {(() => {
                const u = users.find((x: any) => x.id === editUserId)
                if (!u) return null
                return (
                  <>
                    <div className="text-xs text-muted-foreground">
                      用户：<b>{u.username}</b>（{ROLE_LABELS[u.role] || u.role}）
                    </div>
                    {u.role === 'store' && (
                      <div>
                        <label className="text-xs text-muted-foreground">所属门店（多选）</label>
                        <input
                          value={storeFilter}
                          onChange={(e) => setStoreFilter(e.target.value)}
                          placeholder="搜索门店名称或区域..."
                          className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                        />
                        <div className="mt-1 max-h-40 overflow-y-auto rounded-md border p-2 space-y-1">
                          {filteredStores.map(s => {
                            const selected = editForm.store_code.split(',').map(c => c.trim()).includes(s.store_code)
                            return (
                              <label key={s.store_code} className="flex items-center gap-2 text-xs cursor-pointer hover:bg-muted/50 rounded px-1 py-0.5">
                                <input
                                  type="checkbox"
                                  checked={selected}
                                  onChange={(e) => {
                                    const codes = editForm.store_code.split(',').map(c => c.trim()).filter(Boolean)
                                    if (e.target.checked) {
                                      setEditForm({ ...editForm, store_code: [...codes, s.store_code].join(',') })
                                    } else {
                                      setEditForm({ ...editForm, store_code: codes.filter(c => c !== s.store_code).join(',') })
                                    }
                                  }}
                                />
                                <span>{s.store_name}</span>
                                <span className="text-muted-foreground">{s.region}</span>
                              </label>
                            )
                          })}
                        </div>
                        {editForm.store_code && (
                          <p className="mt-1 text-xs text-muted-foreground">已选 {editForm.store_code.split(',').filter(Boolean).length} 家门店</p>
                        )}
                      </div>
                    )}
                    {u.role === 'regional' && (
                      <div>
                        <label className="text-xs text-muted-foreground">管辖门店（多选）</label>
                        <input
                          value={storeFilter}
                          onChange={(e) => setStoreFilter(e.target.value)}
                          placeholder="搜索门店名称或区域..."
                          className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                        />
                        <div className="mt-1 max-h-40 overflow-y-auto rounded-md border p-2 space-y-1">
                          {filteredStores.map(s => {
                            const selected = editForm.region.split(',').map(c => c.trim()).includes(s.store_code)
                            return (
                              <label key={s.store_code} className="flex items-center gap-2 text-xs cursor-pointer hover:bg-muted/50 rounded px-1 py-0.5">
                                <input
                                  type="checkbox"
                                  checked={selected}
                                  onChange={(e) => {
                                    const codes = editForm.region.split(',').map(c => c.trim()).filter(Boolean)
                                    if (e.target.checked) {
                                      setEditForm({ ...editForm, region: [...codes, s.store_code].join(',') })
                                    } else {
                                      setEditForm({ ...editForm, region: codes.filter(c => c !== s.store_code).join(',') })
                                    }
                                  }}
                                />
                                <span>{s.store_name}</span>
                                <span className="text-muted-foreground">{s.region}</span>
                              </label>
                            )
                          })}
                        </div>
                        {editForm.region && (
                          <p className="mt-1 text-xs text-muted-foreground">已选 {editForm.region.split(',').filter(Boolean).length} 家门店</p>
                        )}
                      </div>
                    )}
                    {u.role === 'dept' && (
                      <div>
                        <label className="text-xs text-muted-foreground">部门</label>
                        <input
                          value={editForm.dept}
                          onChange={(e) => setEditForm({ ...editForm, dept: e.target.value })}
                          placeholder="如：商品部"
                          className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                        />
                      </div>
                    )}
                  </>
                )
              })()}
              {updateUser.isError && (
                <p className="text-xs text-red-600">{(updateUser.error as any)?.data?.error || '修改失败'}</p>
              )}
              <button
                onClick={() => updateUser.mutate({ userId: editUserId, data: editForm })}
                className="w-full rounded-md bg-primary py-2 text-sm font-medium text-primary-foreground"
              >
                保存
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 修改密码弹窗 */}
      {showPassword && editUserId !== null && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="w-72 rounded-lg border bg-card p-5 shadow-lg">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-sm font-bold">修改密码</h2>
              <button onClick={() => { setShowPassword(false); setEditUserId(null) }}>
                <X size={16} className="text-muted-foreground" />
              </button>
            </div>
            <div className="space-y-3">
              <div>
                <label className="text-xs text-muted-foreground">新密码</label>
                <input
                  value={passwordForm}
                  onChange={(e) => setPasswordForm(e.target.value)}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              {updatePassword.isError && (
                <p className="text-xs text-red-600">{(updatePassword.error as any)?.data?.error || '修改失败'}</p>
              )}
              <button
                onClick={() => updatePassword.mutate({ userId: editUserId, password: passwordForm })}
                disabled={!passwordForm}
                className="w-full rounded-md bg-primary py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"
              >
                确认修改
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
