import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PageHeader, Table, Modal, Button, Field, TextInput, Select, Badge, TENANTS } from '../components/ui'
import { Icon } from '../lib/icons'
import { getUsers, createUser, updateUser, setUserActive, deleteUser } from '../api/client'

// 사용자 계정 중앙관리 — 테넌트별 계정. 자격증명(비밀번호 해시) 절대 미표시. 비밀번호는 생성 시에만 입력.
const ROLES = ['ADMIN', 'MANAGER', 'USER']

export default function UserList() {
  const qc = useQueryClient()
  const [modal, setModal] = useState<any | null>(null)
  const { data: users = [], isLoading } = useQuery({ queryKey: ['users'], queryFn: () => getUsers() })

  const saveMut = useMutation({
    mutationFn: (d: any) => d.id ? updateUser(d.id, d) : createUser(d),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['users'] }); setModal(null) },
  })
  const activeMut = useMutation({
    mutationFn: ({ id, active }: { id: number; active: boolean }) => setUserActive(id, active),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['users'] }),
  })
  const delMut = useMutation({ mutationFn: deleteUser, onSuccess: () => qc.invalidateQueries({ queryKey: ['users'] }) })

  return (
    <div>
      <PageHeader title="사용자 계정" subtitle="테넌트/매장 단위 계정 중앙관리 · 자격증명은 화면에 표시되지 않습니다"
        actions={<Button icon="plus" onClick={() => setModal({ tenantCode: 'ZIOINFO', role: 'USER', active: true })}>사용자 추가</Button>} />

      {isLoading ? <div className="p-8 text-center text-gray-400 text-sm">로딩 중...</div> : (
        <Table
          rowKey={(r: any) => r.id}
          rows={users as any[]}
          columns={[
            { key: 'tenantCode', header: '테넌트', render: r => <span className="text-brand text-xs">{r.tenantCode}</span> },
            { key: 'username', header: '아이디', render: r => <span className="font-mono text-xs text-white">{r.username}</span> },
            { key: 'name', header: '이름' },
            { key: 'role', header: '역할', render: r => <Badge tone={r.role === 'ADMIN' ? 'blue' : r.role === 'MANAGER' ? 'yellow' : 'gray'}>{r.role}</Badge> },
            { key: 'email', header: '이메일', render: r => <span className="text-xs text-gray-400">{r.email}</span> },
            { key: 'active', header: '상태', render: r => (
              <button onClick={() => activeMut.mutate({ id: r.id, active: !r.active })}>
                <Badge tone={r.active ? 'green' : 'gray'}>{r.active ? '활성' : '비활성'}</Badge>
              </button>
            ) },
            { key: '__act', header: '', align: 'right', render: (r: any) => (
              <div className="flex gap-2 justify-end">
                <button onClick={() => setModal(r)} className="text-brand hover:text-blue-300"><Icon name="edit" size={15} /></button>
                <button onClick={() => { if (confirm('삭제?')) delMut.mutate(r.id) }} className="text-red-400 hover:text-red-300"><Icon name="trash" size={15} /></button>
              </div>
            ) },
          ]}
        />
      )}

      {modal && (
        <Modal title={modal.id ? '사용자 수정' : '사용자 추가'} onClose={() => setModal(null)}>
          <UserForm initial={modal} onSave={d => saveMut.mutate(d)} saving={saveMut.isPending} />
        </Modal>
      )}
    </div>
  )
}

function UserForm({ initial, onSave, saving }: { initial: any; onSave: (d: any) => void; saving: boolean }) {
  const isNew = !initial.id
  const [f, setF] = useState<any>({
    id: initial.id,
    tenantCode: initial.tenantCode || 'ZIOINFO',
    username: initial.username || '',
    password: '',
    name: initial.name || '',
    role: initial.role || 'USER',
    email: initial.email || '',
    phone: initial.phone || '',
    active: initial.active !== false,
  })
  const set = (k: string, v: any) => setF((p: any) => ({ ...p, [k]: v }))

  return (
    <form onSubmit={e => { e.preventDefault(); onSave(f) }}>
      <Field label="테넌트">
        <Select className="w-full" value={f.tenantCode} onChange={v => set('tenantCode', v)}>
          {TENANTS.map(t => <option key={t} value={t}>{t}</option>)}
        </Select>
      </Field>
      <Field label="아이디">
        <TextInput className="w-full" value={f.username} onChange={v => set('username', v)} />
      </Field>
      {isNew && (
        <Field label="초기 비밀번호">
          <TextInput className="w-full" type="password" value={f.password} onChange={v => set('password', v)} placeholder="생성 시에만 입력" />
        </Field>
      )}
      <Field label="이름"><TextInput className="w-full" value={f.name} onChange={v => set('name', v)} /></Field>
      <Field label="역할">
        <Select className="w-full" value={f.role} onChange={v => set('role', v)}>
          {ROLES.map(r => <option key={r} value={r}>{r}</option>)}
        </Select>
      </Field>
      <Field label="이메일"><TextInput className="w-full" value={f.email} onChange={v => set('email', v)} /></Field>
      <Field label="전화"><TextInput className="w-full" value={f.phone} onChange={v => set('phone', v)} /></Field>
      <label className="flex items-center gap-2 text-sm text-gray-300 mb-3">
        <input type="checkbox" checked={f.active} onChange={e => set('active', e.target.checked)} /> 활성
      </label>
      <button type="submit" disabled={saving}
        className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm font-medium disabled:opacity-50">
        {saving ? '저장 중...' : '저장'}
      </button>
    </form>
  )
}
