"use client";
import React, { useState } from 'react';
import { useTeachers } from '../hooks/useTeachers';
import { useAttendance } from '../hooks/useAttendance';
import ClockButton from './ClockButton';

function roundTo15Minutes(date = new Date()) {
  const ms = 1000 * 60 * 15; // 15 minutes in ms
  return new Date(Math.round(date.getTime() / ms) * ms);
}

function formatTime(ts?: number) {
  if (!ts) return '--:--';
  const date = new Date(ts);
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

export default function TeacherList() {
  const { teachers, addTeacher } = useTeachers();
  const { todayRecords } = useAttendance();
  const [name, setName] = useState('');

  return (
    <div>
      <div className="flex mb-4">
        <input
          type="text"
          value={name}
          onChange={e => setName(e.target.value)}
          placeholder="New teacher name"
          className="flex-grow border p-2 mr-2 rounded"
        />
        <button
          onClick={() => { addTeacher(name); setName(''); }}
          className="px-4 py-2 border rounded"
        >
          Add
        </button>
      </div>
      <ul>
        {teachers.map(t => {
          const records = todayRecords.filter(r => r.teacherId === t.id);
          const lastIn = [...records].reverse().find(r => r.type === 'in');
          const lastOut = [...records].reverse().find(r => r.type === 'out');
          return (
            <li key={t.id} className="flex justify-between items-center mb-2">
              <span>{t.name}</span>
              <span className="mx-2 text-sm text-gray-500">
                In: {formatTime(lastIn?.timestamp)} | Out: {formatTime(lastOut?.timestamp)}
              </span>
              <ClockButton teacherId={t.id} />
            </li>
          );
        })}
      </ul>
    </div>
  );
}
