import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getTenants, createTenant, updateTenant, deleteTenant } from '../api/client'
import { Building2, Plus, Edit, Trash2, X } from 'lucide-react'

export default function TenantAdmin() {
  const qc = useQueryClient()
  const [modal, setModal] = useState<any>(null)

  const { data: tenants = [], isLoading } = useQuery({
    queryKey: ['tenants'],
    queryFn:  () => getTenants(),
  })

  const saveMut = useMutation({
    mutationFn: (d: any) => d.id ? updateTenant(d.id, d) : createTenant(d),
    onSuccess:  () => { qc.invalidateQueries({ queryKey: ['tenants'] }); setModal(null) },
  })

  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">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold text-white">테넌트 관리</h1>
        <button onClick={() => setModal({})}
          className="flex items-center gap-1.5 bg-brand hover:bg-brand2 text-white px-3 py-1.5 rounded text-sm">
          <Plus size={14} /> 테넌트 추가
        </button>
      </div>
      <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>
              <div className="flex gap-2">
                <button onClick={() => setModal(t)} className="text-brand hover:text-blue-300"><Edit size={14} /></button>
                <button onClick={() => { if(confirm('삭제?')) deleteMut.mutate(t.id) }}
                  className="text-red-400 hover:text-red-300"><Trash2 size={14} /></button>
              </div>
            </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>
        ))}
        {(tenants as any[]).length === 0 && (
          <div className="col-span-full text-center text-gray-500 py-12">테넌트가 없습니다</div>
        )}
      </div>

      {modal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
          <div className="bg-card border border-edge rounded-lg p-6 w-full max-w-md">
            <div className="flex justify-between mb-4">
              <h2 className="font-semibold">{modal.id ? '테넌트 수정' : '테넌트 추가'}</h2>
              <button onClick={() => setModal(null)}><X size={16} /></button>
            </div>
            <TenantForm initial={modal} onSave={(d: any) => saveMut.mutate(d)} />
          </div>
        </div>
      )}
    </div>
  )
}

function TenantForm({ initial, onSave }: { initial: any; onSave: (d: any) => void }) {
  const isEdit = !!initial.id
  const [f, setF] = useState({
    tenantCode:  initial.tenantCode  || '',
    tenantName:  initial.tenantName  || '',
    description: initial.description || '',
    active:      initial.active !== false,
    id:          initial.id,
  })
  const set = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) =>
    setF(p => ({ ...p, [k]: e.target.value }))

  const submit = (e: React.FormEvent) => {
    e.preventDefault()
    onSave({ ...f, active: f.active === true || (f as any).active === 'true' })
  }

  return (
    <form onSubmit={submit} className="space-y-3">
      <div>
        <label className="block text-xs text-gray-400 mb-1">테넌트 코드</label>
        <input value={f.tenantCode} onChange={set('tenantCode')} disabled={isEdit} required
          placeholder="예: EMART"
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white disabled:opacity-50" />
      </div>
      <div>
        <label className="block text-xs text-gray-400 mb-1">테넌트명</label>
        <input value={f.tenantName} onChange={set('tenantName')} required
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white" />
      </div>
      <div>
        <label className="block text-xs text-gray-400 mb-1">설명</label>
        <textarea value={f.description} onChange={set('description')} rows={2}
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white" />
      </div>
      <div>
        <label className="block text-xs text-gray-400 mb-1">상태</label>
        <select value={String(f.active)} onChange={set('active')}
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-white">
          <option value="true">운영중</option>
          <option value="false">비활성</option>
        </select>
      </div>
      <button type="submit" className="w-full bg-brand hover:bg-brand2 text-white py-2 rounded text-sm">
        저장
      </button>
    </form>
  )
}
