import React, { useEffect, useState } from 'react';
import { api } from '../lib/api';
import { Role, UserDto, UserStatus } from '../types';
import { useAuth } from '../lib/auth';

const ROLES: Role[] = ['ADMIN', 'MANAGER', 'EMPLOYEE'];
const STATUSES: UserStatus[] = ['ACTIVE', 'DISABLED', 'LOCKED'];

export default function Users() {
  const { role } = useAuth();
  const [list, setList] = useState<UserDto[]>([]);
  const [form, setForm] = useState({
    username: '',
    password: '',
    fullName: '',
    email: '',
    phone: '',
    role: 'EMPLOYEE' as Role,
  });

  const load = () => api.get<UserDto[]>('/users').then(setList);

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

  const create = async (e: React.FormEvent) => {
    e.preventDefault();
    await api.post('/users', form);
    setForm({ username: '', password: '', fullName: '', email: '', phone: '', role: 'EMPLOYEE' });
    load();
  };

  const updateStatus = async (id: number, status: UserStatus) => {
    await api.patch(`/users/${id}/status`, { status });
    load();
  };

  return (
    <div className="page animate-in">
      <div className="page-header">
        <h1>用户管理</h1>
        <p>组织内用户与状态</p>
      </div>

      {role === 'ADMIN' && (
        <div className="card">
          <div className="card-title">创建用户</div>
          <form className="form grid cols-2" onSubmit={create}>
            <label>
              用户名
              <input
                value={form.username}
                onChange={(e) => setForm({ ...form, username: e.target.value })}
              />
            </label>
            <label>
              密码
              <input
                type="password"
                value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })}
              />
            </label>
            <label>
              姓名
              <input
                value={form.fullName}
                onChange={(e) => setForm({ ...form, fullName: e.target.value })}
              />
            </label>
            <label>
              角色
              <select
                value={form.role}
                onChange={(e) => setForm({ ...form, role: e.target.value as Role })}
              >
                {ROLES.map((r) => (
                  <option key={r} value={r}>
                    {r}
                  </option>
                ))}
              </select>
            </label>
            <label>
              邮箱
              <input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
            </label>
            <label>
              电话
              <input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
            </label>
            <div>
              <button className="btn btn-primary">创建</button>
            </div>
          </form>
        </div>
      )}

      <div className="card">
        <div className="card-title">用户列表</div>
        <table className="table">
          <thead>
            <tr>
              <th>姓名</th>
              <th>用户名</th>
              <th>角色</th>
              <th>状态</th>
              <th>邮箱</th>
              <th>电话</th>
              <th>最近登录</th>
            </tr>
          </thead>
          <tbody>
            {list.map((u) => (
              <tr key={u.id}>
                <td>{u.fullName}</td>
                <td>{u.username}</td>
                <td>{u.role}</td>
                <td>
                  {role === 'ADMIN' ? (
                    <select
                      value={u.status}
                      onChange={(e) => updateStatus(u.id, e.target.value as UserStatus)}
                    >
                      {STATUSES.map((s) => (
                        <option key={s} value={s}>
                          {s}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <span className="badge">{u.status}</span>
                  )}
                </td>
                <td>{u.email || '-'}</td>
                <td>{u.phone || '-'}</td>
                <td>{u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
