import { useEffect, useState } from 'react';
import useAdminStore from '../store/adminStore';
import { formatDate } from '../lib/format';

export function EmployeeManager() {
  const employees = useAdminStore((s) => s.employees);
  const error = useAdminStore((s) => s.employeesError);
  const busy = useAdminStore((s) => s.employeesBusy);
  const loadEmployees = useAdminStore((s) => s.loadEmployees);
  const addEmployee = useAdminStore((s) => s.addEmployee);
  const removeEmployee = useAdminStore((s) => s.removeEmployee);

  const [email, setEmail] = useState('');

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

  async function handleAdd(e: React.FormEvent) {
    e.preventDefault();
    if (!email.trim()) return;
    await addEmployee(email.trim());
    setEmail('');
  }

  return (
    <div className="panel">
      <p className="panel-title">Zaměstnanci &middot; přístup přes Google účet</p>

      <form className="field-row" onSubmit={handleAdd}>
        <input
          type="email"
          placeholder="&gt; email@example.com"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          disabled={busy}
        />
        <button className="btn" type="submit" disabled={busy}>
          Přidat
        </button>
      </form>

      {error && <div className="login-error" style={{ marginTop: '0.75rem' }}>{error}</div>}

      <div className="list" style={{ marginTop: '1rem' }}>
        {employees === null && <div className="empty-line">&gt; načítám…</div>}
        {employees?.length === 0 && <div className="empty-line">· zatím žádní zaměstnanci</div>}
        {employees?.map((emp) => (
          <div className="row" key={emp.id}>
            <div className="row-main">
              <div className="row-title">{emp.name ?? emp.email}</div>
              <div className="row-meta">
                {emp.email} &middot; od {formatDate(emp.created_at)}
              </div>
            </div>
            <div className="row-action">
              {emp.active ? (
                <button className="btn" disabled={busy} onClick={() => removeEmployee(emp.id)}>
                  Odebrat
                </button>
              ) : (
                <span className="badge badge-dashed" title="Historie docházky zůstává zachována">
                  NEAKTIVNÍ
                </span>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
