import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getTenants, deleteTenant } from '../api/client'
import { Building2, Trash2 } from 'lucide-react'

export default function TenantAdmin() {
  const qc = useQueryClient()
  const { data: tenants = [], isLoading } = useQuery({
    queryKey: ['tenants'],
    queryFn:  () => getTenants(),
  })

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

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

  const role = localStorage.getItem('esn_role')
  if (role !== 'ADMIN') return (
    <div className="text-center py-16">
      <p className="text-gray-400">관리자 전용 메뉴입니다.</p>
    </div>
  )

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-semibold text-white">테넌트 관리</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {(tenants as any[]).map((t: any) => (
          <div key={t.id} className="bg-card border border-edge rounded-lg p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <Building2 size={18} className="text-brand" />
                <span className="font-bold text-brand">{t.tenantCode}</span>
              </div>
              <button onClick={() => { if(confirm('삭제?')) deleteMut.mutate(t.id) }}
                className="text-red-400 hover:text-red-300"><Trash2 size={14} /></button>
            </div>
            <p className="text-sm text-white">{t.tenantName}</p>
            <p className="text-xs text-gray-400 mt-1">{t.description}</p>
            <div className="mt-3">
              <span className={`px-2 py-0.5 rounded text-xs ${t.active ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'}`}>
                {t.active ? '운영중' : '비활성'}
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
