import React, { useEffect, useState } from 'react';
import { api } from '../lib/api';
import { LeaveDto } from '../types';

export default function Approvals() {
  const [list, setList] = useState<LeaveDto[]>([]);
  const [notes, setNotes] = useState<Record<number, string>>({});

  const load = () => api.get<LeaveDto[]>('/leave-requests/pending').then(setList);

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

  const act = async (id: number, action: 'approve' | 'reject') => {
    await api.post(`/leave-requests/${id}/${action}`, {
      note: notes[id] || '',
    });
    load();
  };

  return (
    <div className="page animate-in">
      <div className="page-header">
        <h1>审批</h1>
        <p>待审批的请假请求</p>
      </div>

      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th>申请人</th>
              <th>类型</th>
              <th>时间</th>
              <th>原因</th>
              <th>备注</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {list.map((l) => (
              <tr key={l.id}>
                <td>{l.requester.fullName}</td>
                <td>{l.type}</td>
                <td>
                  {new Date(l.startTime).toLocaleString()} → {new Date(l.endTime).toLocaleString()}
                </td>
                <td>{l.reason}</td>
                <td>
                  <input
                    className="inline-input"
                    value={notes[l.id] || ''}
                    onChange={(e) => setNotes({ ...notes, [l.id]: e.target.value })}
                  />
                </td>
                <td className="row">
                  <button className="btn btn-primary" onClick={() => act(l.id, 'approve')}>
                    通过
                  </button>
                  <button className="btn btn-danger" onClick={() => act(l.id, 'reject')}>
                    拒绝
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {!list.length && <div className="muted">暂无待审批记录</div>}
      </div>
    </div>
  );
}
