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

export default function Attendance() {
  const [records, setRecords] = useState<AttendanceDto[]>([]);
  const [location, setLocation] = useState('HQ');
  const [loading, setLoading] = useState(true);
  const [action, setAction] = useState('');

  const load = () =>
    api.get<AttendanceDto[]>('/attendance/me').then((data) => {
      setRecords(data);
      setLoading(false);
    });

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

  const checkIn = async () => {
    setAction('checkin');
    await api.post('/attendance/check-in', { location });
    await load();
    setAction('');
  };

  const checkOut = async () => {
    setAction('checkout');
    await api.post('/attendance/check-out');
    await load();
    setAction('');
  };

  return (
    <div className="page animate-in">
      <div className="page-header">
        <h1>考勤</h1>
        <p>打卡与个人记录</p>
      </div>

      <div className="card">
        <div className="card-title">打卡</div>
        <div className="row">
          <input value={location} onChange={(e) => setLocation(e.target.value)} />
          <button className="btn btn-primary" onClick={checkIn} disabled={action === 'checkin'}>
            上班打卡
          </button>
          <button className="btn btn-outline" onClick={checkOut} disabled={action === 'checkout'}>
            下班签退
          </button>
        </div>
      </div>

      <div className="card">
        <div className="card-title">我的考勤记录</div>
        {loading ? (
          <div className="muted">加载中...</div>
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>日期</th>
                <th>签到</th>
                <th>签退</th>
                <th>工时</th>
                <th>地点</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              {records.map((r) => (
                <tr key={r.id}>
                  <td>{r.date}</td>
                  <td>{r.checkInTime || '-'}</td>
                  <td>{r.checkOutTime || '-'}</td>
                  <td>{r.workHours}</td>
                  <td>{r.location || '-'}</td>
                  <td>
                    <span className="badge">{r.status}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
