import { useEffect, useState } from 'react';
import useAdminPayrollStore, { type Adjustments } from '../store/adminPayrollStore';
import type { PayrollOverviewRow } from '../api/types';
import { MonthNav } from './MonthNav';
import { formatDuration } from '../lib/format';

const CLOSURE_LABEL: Record<string, string> = {
  waiting_employee: 'čeká na zaměstnance',
  confirmed: 'potvrzeno',
  locked: 'uzamčeno',
};

const PAYROLL_LABEL: Record<string, string> = {
  draft: 'rozpracováno',
  ready: 'připraveno k výplatě',
  paid: 'vyplaceno',
};

export function PayrollManager() {
  const period = useAdminPayrollStore((s) => s.period);
  const rows = useAdminPayrollStore((s) => s.rows);
  const busy = useAdminPayrollStore((s) => s.busy);
  const error = useAdminPayrollStore((s) => s.error);
  const load = useAdminPayrollStore((s) => s.load);
  const prevPeriod = useAdminPayrollStore((s) => s.prevPeriod);
  const nextPeriod = useAdminPayrollStore((s) => s.nextPeriod);
  const saveAdjustments = useAdminPayrollStore((s) => s.saveAdjustments);
  const lock = useAdminPayrollStore((s) => s.lock);
  const reopen = useAdminPayrollStore((s) => s.reopen);
  const markPaid = useAdminPayrollStore((s) => s.markPaid);

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

  return (
    <div className="panel">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <p className="panel-title">Mzdy</p>
        <a className="btn" href={`/api/admin/payroll/export?period=${period}`} download>
          Export CSV
        </a>
      </div>
      <MonthNav month={period} onPrev={prevPeriod} onNext={nextPeriod} />
      {error && <div className="login-error">{error}</div>}

      <div className="list" style={{ marginTop: '1rem' }}>
        {rows === null && <div className="empty-line">&gt; načítám…</div>}
        {rows?.length === 0 && <div className="empty-line">· žádní zaměstnanci</div>}
        {rows?.map((row) => (
          <PayrollRow
            key={row.employee_id}
            row={row}
            busy={busy}
            onSave={(data) => saveAdjustments(row.employee_id, data)}
            onLock={() => lock(row.employee_id)}
            onReopen={() => reopen(row.employee_id)}
            onMarkPaid={() => markPaid(row.employee_id)}
          />
        ))}
      </div>
    </div>
  );
}

function PayrollRow({
  row,
  busy,
  onSave,
  onLock,
  onReopen,
  onMarkPaid,
}: {
  row: PayrollOverviewRow;
  busy: boolean;
  onSave: (data: Adjustments) => void;
  onLock: () => void;
  onReopen: () => void;
  onMarkPaid: () => void;
}) {
  const [tips, setTips] = useState(String(row.tips_amount));
  const [bonus, setBonus] = useState(String(row.bonus_amount));
  const [other, setOther] = useState(String(row.other_amount));

  const editable = row.closure_status !== 'waiting_employee' && row.payroll_status !== 'ready' && row.payroll_status !== 'paid';
  const dirty = Number(tips) !== row.tips_amount || Number(bonus) !== row.bonus_amount || Number(other) !== row.other_amount;

  return (
    <div className="row" style={{ flexWrap: 'wrap' }}>
      <div className="row-main">
        <div className="row-title">
          {row.employee_name} <span className="badge badge-dashed">{CLOSURE_LABEL[row.closure_status]}</span>
          {row.payroll_status && <span className="badge badge-solid">{PAYROLL_LABEL[row.payroll_status]}</span>}
        </div>
        <div className="row-meta">
          {formatDuration(row.worked_minutes * 60_000)} &middot; základ {row.base_amount} Kč &middot; celkem{' '}
          {row.final_amount} Kč
        </div>

        {editable && (
          <div style={{ display: 'flex', gap: '0.75rem', marginTop: '0.4rem', flexWrap: 'wrap', alignItems: 'center' }}>
            <AmountField label="spropitné" value={tips} onChange={setTips} busy={busy} />
            <AmountField label="bonus" value={bonus} onChange={setBonus} busy={busy} />
            <AmountField label="ostatní" value={other} onChange={setOther} busy={busy} />
            {dirty && (
              <button
                className="btn"
                disabled={busy}
                onClick={() => onSave({ tips_amount: Number(tips), bonus_amount: Number(bonus), other_amount: Number(other) })}
              >
                Uložit
              </button>
            )}
            {row.closure_status === 'confirmed' && (
              <button className="btn" disabled={busy} onClick={onLock}>
                Zamknout a předat k výplatě
              </button>
            )}
          </div>
        )}

        {row.payroll_status === 'ready' && (
          <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.4rem' }}>
            <button className="btn" disabled={busy} onClick={onMarkPaid}>
              Označit jako vyplaceno
            </button>
            <button className="btn-ghost" disabled={busy} onClick={onReopen}>
              Odemknout a upravit
            </button>
          </div>
        )}

        {row.payroll_status === 'paid' && (
          <div className="row-meta" style={{ marginTop: '0.2rem' }}>
            vyplaceno {row.payment_date}
          </div>
        )}
      </div>
    </div>
  );
}

function AmountField({
  label,
  value,
  onChange,
  busy,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  busy: boolean;
}) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: '0.35rem' }}>
      <span className="row-meta" style={{ margin: 0 }}>
        {label}
      </span>
      <input
        type="number"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        disabled={busy}
        aria-label={label}
        style={{ width: '5rem' }}
      />
    </label>
  );
}
