import { useEffect } from 'react';
import useClosureStore from '../store/closureStore';
import { MonthNav } from './MonthNav';
import { formatDuration } from '../lib/format';

const STATUS_LABEL: Record<string, string> = {
  waiting_employee: 'čeká na tvé potvrzení',
  confirmed: 'potvrzeno, čeká na zpracování',
  locked: 'uzamčeno',
};

export function ClosureCard() {
  const period = useClosureStore((s) => s.period);
  const closure = useClosureStore((s) => s.closure);
  const summary = useClosureStore((s) => s.summary);
  const busy = useClosureStore((s) => s.busy);
  const error = useClosureStore((s) => s.error);
  const load = useClosureStore((s) => s.load);
  const prevPeriod = useClosureStore((s) => s.prevPeriod);
  const nextPeriod = useClosureStore((s) => s.nextPeriod);
  const confirm = useClosureStore((s) => s.confirm);

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

  return (
    <div className="panel">
      <p className="panel-title">Uzávěrka měsíce</p>
      <MonthNav month={period} onPrev={prevPeriod} onNext={nextPeriod} />
      {error && <div className="login-error">{error}</div>}

      {!closure || !summary ? (
        <div className="empty-line">&gt; načítám…</div>
      ) : (
        <>
          <div className="stat-grid" style={{ marginTop: '1rem' }}>
            <div className="stat-tile">
              <div className="stat-value">{formatDuration(summary.worked_minutes * 60_000)}</div>
              <div className="stat-label">odpracováno</div>
            </div>
            <div className="stat-tile">
              <div className="stat-value">{summary.shift_count}</div>
              <div className="stat-label">směn</div>
            </div>
            <div className="stat-tile">
              <div className="stat-value">{summary.earned_estimate} Kč</div>
              <div className="stat-label">odhad výdělku</div>
            </div>
          </div>

          <div style={{ marginTop: '1rem', display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
            <span className={`badge ${closure.status === 'waiting_employee' ? 'badge-dashed' : 'badge-solid'}`}>
              {STATUS_LABEL[closure.status]}
            </span>
            {closure.status === 'waiting_employee' && (
              <button className="btn" disabled={busy} onClick={confirm}>
                Potvrdit docházku
              </button>
            )}
          </div>
        </>
      )}
    </div>
  );
}
