import React, { useEffect, useState } from 'react'
import api from '../api/client'

function DeptNode({ dept, level = 0 }: { dept: any; level?: number }) {
  const [open, setOpen] = useState(true)
  return (
    <div style={{ marginLeft: level * 24 }}>
      <div className="flex items-center gap-2 py-2 px-3 hover:bg-slate-50 rounded-lg cursor-pointer"
        onClick={() => setOpen(!open)}>
        {dept.children?.length > 0 && (
          <span className="text-slate-400 text-xs">{open ? '▼' : '▶'}</span>
        )}
        {dept.children?.length === 0 && <span className="w-3" />}
        <span className="w-8 h-8 rounded-lg bg-blue-100 text-blue-700 flex items-center justify-center text-sm font-bold">
          {dept.dept_name?.charAt(0)}
        </span>
        <div>
          <p className="text-sm font-medium text-slate-700">{dept.dept_name}</p>
          <p className="text-xs text-slate-400">{dept.headcount || 0}명 {dept.manager_name ? `| 장: ${dept.manager_name}` : ''}</p>
        </div>
      </div>
      {open && dept.children?.map((child: any) => (
        <DeptNode key={child.id} dept={child} level={level + 1} />
      ))}
    </div>
  )
}

export default function OrganizationPage() {
  const [tree, setTree] = useState<any[]>([])
  const [positions, setPositions] = useState<any[]>([])
  const [grades, setGrades] = useState<any[]>([])
  const [tab, setTab] = useState<'org'|'position'|'grade'>('org')

  useEffect(() => {
    api.get('/departments').then(r => setTree(r.data.data)).catch(() => {})
    api.get('/positions').then(r => setPositions(r.data.data)).catch(() => {})
    api.get('/grades').then(r => setGrades(r.data.data)).catch(() => {})
  }, [])

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold text-slate-800">조직도</h1>
      <div className="flex gap-2 border-b border-slate-200">
        {(['org','position','grade'] as const).map(t => (
          <button key={t} onClick={() => setTab(t)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${tab===t?'border-blue-600 text-blue-600':'border-transparent text-slate-500 hover:text-slate-700'}`}>
            {t === 'org' ? '조직도' : t === 'position' ? '직책' : '직급'}
          </button>
        ))}
      </div>

      {tab === 'org' && (
        <div className="card">
          <h2 className="text-base font-semibold text-slate-700 mb-4">조직 구조</h2>
          {tree.map(d => <DeptNode key={d.id} dept={d} />)}
          {tree.length === 0 && <p className="text-slate-400 text-sm text-center py-8">부서 데이터가 없습니다</p>}
        </div>
      )}

      {tab === 'position' && (
        <div className="card">
          <h2 className="text-base font-semibold text-slate-700 mb-4">직책 목록</h2>
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="table-header">직책코드</th>
                <th className="table-header">직책명</th>
                <th className="table-header">순서</th>
              </tr>
            </thead>
            <tbody>
              {positions.map((p: any) => (
                <tr key={p.id} className="border-b border-slate-50">
                  <td className="table-cell font-mono text-xs">{p.position_code}</td>
                  <td className="table-cell font-medium">{p.position_name}</td>
                  <td className="table-cell">{p.sort_order}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'grade' && (
        <div className="card">
          <h2 className="text-base font-semibold text-slate-700 mb-4">직급 목록</h2>
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="table-header">직급코드</th>
                <th className="table-header">직급명</th>
                <th className="table-header">레벨</th>
              </tr>
            </thead>
            <tbody>
              {grades.map((g: any) => (
                <tr key={g.id} className="border-b border-slate-50">
                  <td className="table-cell font-mono text-xs">{g.grade_code}</td>
                  <td className="table-cell font-medium">{g.grade_name}</td>
                  <td className="table-cell">{g.grade_level}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
