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 setRate = useAdminStore((s) => s.setRate);

  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) => (
          <EmployeeRow key={emp.id} employee={emp} busy={busy} onRemove={removeEmployee} onSetRate={setRate} />
        ))}
      </div>
    </div>
  );
}

function EmployeeRow({
  employee,
  busy,
  onRemove,
  onSetRate,
}: {
  employee: { id: number; email: string; name: string | null; active: 0 | 1; created_at: string; hourly_rate: number };
  busy: boolean;
  onRemove: (id: number) => void;
  onSetRate: (id: number, hourlyRate: number) => void;
}) {
  const [rate, setRate] = useState(String(employee.hourly_rate));
  const dirty = Number(rate) !== employee.hourly_rate;

  return (
    <div className="row">
      <div className="row-main">
        <div className="row-title">{employee.name ?? employee.email}</div>
        <div className="row-meta">
          {employee.email} &middot; od {formatDate(employee.created_at)}
        </div>
      </div>
      <div className="row-action">
        <label style={{ display: 'flex', alignItems: 'center', gap: '0.35rem' }}>
          <span className="row-meta" style={{ margin: 0 }}>
            Kč/h
          </span>
          <input
            type="number"
            min={0}
            value={rate}
            onChange={(e) => setRate(e.target.value)}
            disabled={busy}
            aria-label="Hodinová sazba v Kč"
            style={{ width: '4rem' }}
          />
        </label>
        {dirty && (
          <button className="btn" disabled={busy} onClick={() => onSetRate(employee.id, Number(rate))}>
            Uložit sazbu
          </button>
        )}
        {employee.active ? (
          <button className="btn" disabled={busy} onClick={() => onRemove(employee.id)}>
            Odebrat
          </button>
        ) : (
          <span className="badge badge-dashed" title="Historie docházky zůstává zachována">
            NEAKTIVNÍ
          </span>
        )}
      </div>
    </div>
  );
}
