import { useEffect } from 'react';
import useAdminStore from '../store/adminStore';
import { StatsSummary } from './StatsSummary';
import { SessionList } from './SessionList';
import { MonthNav } from './MonthNav';
import { BarChart } from './BarChart';
import { formatDuration } from '../lib/format';
import { formatMonthLabel } from '../lib/month';
import { aggregateDailyWorkedMs } from '../lib/dailyAggregate';

export function AdminStats() {
  const stats = useAdminStore((s) => s.stats);
  const month = useAdminStore((s) => s.month);
  const selectedEmployeeId = useAdminStore((s) => s.selectedEmployeeId);
  const detail = useAdminStore((s) => s.employeeDetail);
  const detailLoading = useAdminStore((s) => s.detailLoading);
  const loadStats = useAdminStore((s) => s.loadStats);
  const selectEmployee = useAdminStore((s) => s.selectEmployee);
  const prevMonth = useAdminStore((s) => s.prevMonth);
  const nextMonth = useAdminStore((s) => s.nextMonth);

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

  if (!stats) return <div className="empty-line">&gt; načítám…</div>;

  return (
    <>
      <div className="panel">
        <p className="panel-title">Souhrn &middot; {formatMonthLabel(month)}</p>
        <StatsSummary
          totalWorkedMs={stats.totals.totalWorkedMs}
          totalBreakMs={stats.totals.totalBreakMs}
          shiftCount={stats.totals.shiftCount}
        />
      </div>

      <div className="panel">
        <p className="panel-title">Podle zaměstnance &middot; klikni pro detail</p>
        <div className="list">
          {stats.employees.length === 0 && (
            <div className="empty-line">· zatím žádní zaměstnanci</div>
          )}
          {stats.employees.map((e) => (
            <div
              className="row"
              key={e.employee.id}
              onClick={() => selectEmployee(e.employee.id)}
              style={{ cursor: 'pointer' }}
            >
              <div className="row-main">
                <div className="row-title">{e.employee.name ?? e.employee.email}</div>
                <div className="row-meta">
                  {e.shiftCount} směn &middot; pauzy {formatDuration(e.totalBreakMs)}
                </div>
              </div>
              <div className="row-action">
                <span className="badge badge-solid">{formatDuration(e.totalWorkedMs)}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {selectedEmployeeId != null && (
        <div className="panel">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <p className="panel-title">
              Detail &middot;{' '}
              {stats.employees.find((e) => e.employee.id === selectedEmployeeId)?.employee.name ??
                stats.employees.find((e) => e.employee.id === selectedEmployeeId)?.employee.email}
            </p>
            <a
              className="btn"
              href={`/api/admin/stats/${selectedEmployeeId}/export?month=${month}`}
              download
            >
              Export CSV
            </a>
          </div>

          <MonthNav month={month} onPrev={prevMonth} onNext={nextMonth} />

          {detailLoading && !detail && <div className="empty-line">&gt; načítám…</div>}

          {detail && (
            <>
              <BarChart values={aggregateDailyWorkedMs(detail.sessions, month)} month={month} />
              <div style={{ marginTop: '1rem' }}>
                <SessionList sessions={detail.sessions} />
              </div>
            </>
          )}
        </div>
      )}
    </>
  );
}
