import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Trash2, RefreshCw } from 'lucide-react'
import { getUsers, deleteUser } from '../api/client'
import { adminOtpReset } from '../api/uiws'

export default function UserList() {
  const qc = useQueryClient()
  const { data: users = [], isLoading } = useQuery({
    queryKey: ['users'],
    queryFn:  () => getUsers(),
  })

  const deleteMut = useMutation({
    mutationFn: deleteUser,
    onSuccess:  () => qc.invalidateQueries({ queryKey: ['users'] }),
  })

  // 관리자 OTP 초기화(ADMIN 전용) — zioinfo-esn 은 username 기준. 다음 로그인 시 재등록 유도.
  const otpResetMut = useMutation({
    mutationFn: (username: string) => adminOtpReset(username),
    onSuccess:  () => qc.invalidateQueries({ queryKey: ['users'] }),
  })

  function handleOtpReset(u: any) {
    if (!confirm(`'${u.username}' 사용자의 OTP를 초기화하시겠습니까?\n초기화하면 다음 로그인 시 재등록해야 합니다.`)) return
    otpResetMut.mutate(u.username)
  }

  if (isLoading) return <div className="text-gray-400 p-8">로딩 중...</div>

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-semibold text-white">사용자 관리</h1>
      <div className="bg-card border border-edge rounded-lg overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-panel border-b border-edge">
            <tr>
              {['아이디','테넌트','역할','이메일','전화','상태','마지막 로그인','액션'].map(h => (
                <th key={h} className="px-4 py-3 text-left text-xs text-gray-400 font-medium">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {(users as any[]).map((u: any) => (
              <tr key={u.id} className="border-b border-edge hover:bg-edge/30">
                <td className="px-4 py-3 text-white font-medium">{u.username}</td>
                <td className="px-4 py-3 text-brand text-xs">{u.tenantCode || 'SUPER'}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${
                    u.role === 'ADMIN'   ? 'bg-red-500/20 text-red-400' :
                    u.role === 'MANAGER' ? 'bg-brand/20 text-brand' :
                    'bg-gray-500/20 text-gray-400'
                  }`}>{u.role}</span>
                </td>
                <td className="px-4 py-3 text-gray-400 text-xs">{u.email || '-'}</td>
                <td className="px-4 py-3 text-gray-400 text-xs">{u.phone || '-'}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${u.active ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'}`}>
                    {u.active ? '활성' : '비활성'}
                  </span>
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs">
                  {u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString('ko-KR') : '-'}
                </td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-3">
                    <button onClick={() => handleOtpReset(u)} title="OTP 초기화"
                      className="text-gray-400 hover:text-brand"><RefreshCw size={14} /></button>
                    <button onClick={() => { if(confirm('삭제?')) deleteMut.mutate(u.id) }} title="삭제"
                      className="text-red-400 hover:text-red-300"><Trash2 size={14} /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
