import { useState, useEffect } from 'react';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { Tag } from 'primereact/tag';
import BaseCrudTable from '@/core/components/BaseCrudTable';
import BasePageHeader from '@/core/components/BasePageHeader';
import UserFormDialog from '../components/UserFormDialog';
import { userService } from '../user.service';
import type { User } from '../user.types';
import { toArray } from '@/core/api/utils';

const ROLE_SEVERITY: Record<string, string> = {
  SA: 'danger', PM: 'warning', PCM: 'info', DL: 'success', PTK: 'secondary', USER: 'contrast',
};

export default function UserListView() {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [editUser, setEditUser] = useState<User | null>(null);

  function load() {
    setLoading(true);
    userService.getAll()
      .then(({ data }) => setUsers(toArray<User>(data)))
      .catch(() => setUsers([]))
      .finally(() => setLoading(false));
  }

  useEffect(() => { load(); }, []);

  function openEdit(u: User) {
    setEditUser(u);
    setDialogVisible(true);
  }

  async function onSave(data: Partial<User>) {
    if (editUser) {
      await userService.update(editUser.id, data);
    }
    setDialogVisible(false);
    load();
  }

  return (
    <div>
      <BasePageHeader title="사용자 관리" />
      <BaseCrudTable value={users} loading={loading} globalFilterFields={['fullName', 'email', 'employeeId', 'department']}>
        <Column field="fullName" header="이름" sortable />
        <Column field="email" header="이메일" sortable />
        <Column field="employeeId" header="사번" sortable />
        <Column field="department" header="부서" sortable />
        <Column field="discipline" header="Discipline" sortable />
        <Column field="roles" header="역할" body={(row) => (
          <div style={{ display: 'flex', gap: '0.25rem', flexWrap: 'wrap' }}>
            {(row.roles as string[]).map((r: string) => (
              <Tag key={r} value={r} severity={(ROLE_SEVERITY[r] ?? 'secondary') as 'danger' | 'warning' | 'info' | 'success' | 'secondary'} />
            ))}
          </div>
        )} />
        <Column field="isActive" header="상태" body={(row) => (
          <Tag value={row.isActive ? '활성' : '비활성'} severity={row.isActive ? 'success' : 'secondary'} />
        )} />
        <Column header="" body={(row) => <Button icon="pi pi-pencil" text size="small" onClick={() => openEdit(row)} />} style={{ width: '4rem' }} />
      </BaseCrudTable>

      <UserFormDialog visible={dialogVisible} onHide={() => setDialogVisible(false)} user={editUser} onSave={onSave} />
    </div>
  );
}
