import { useNavigate } from 'react-router-dom';
import { useBalance, useSummary } from '../api/queries.js';
import { useHouseholdContext } from '../household/HouseholdContext.jsx';
import { useTranslation } from '../i18n/I18nContext.jsx';
import CategoryPieChart from '../components/CategoryPieChart.jsx';
import Icon from '../components/Icon.jsx';

function memberName(members, id) {
  return members.find((m) => m.id === id)?.name || '—';
}

export default function Dashboard() {
  const navigate = useNavigate();
  const { activeHousehold: household } = useHouseholdContext();
  const { data: balance } = useBalance();
  const { data: summary } = useSummary();
  const { t } = useTranslation();

  const members = household?.members || [];
  const currency = household?.currency || 'PLN';

  return (
    <div>
      <h1 className="page-title">Dashboard</h1>

      <div className="card settlement-tile">
        {!balance ? (
          <p>{t('common.loading')}</p>
        ) : balance.settled ? (
          <>
            <p>{t('dashboard.settlementsTitle')}</p>
            <p className="amount settled">
              {t('dashboard.allSettled')} <Icon name="celebration" />
            </p>
          </>
        ) : (
          <>
            <p>{t('dashboard.settlementsTitle')}</p>
            <div className="settlement-transactions">
              {balance.transactions.map((tx, i) => (
                <p key={i} className="amount owed">
                  {memberName(members, tx.from)} → {memberName(members, tx.to)}: {tx.amount.toFixed(2)} {currency}
                </p>
              ))}
            </div>
            <button className="btn-primary btn-center" onClick={() => navigate('/settlements')}>
              {t('dashboard.settleUpButton')}
            </button>
          </>
        )}
      </div>

      <div className="card">
        <h3>{t('dashboard.expensesByCategoryTitle')}</h3>
        {!summary ? <p>{t('common.loading')}</p> : <CategoryPieChart data={summary.byCategory} currency={currency} />}
      </div>

      <div className="card">
        <h3>{t('dashboard.monthSummaryTitle')}</h3>
        {summary && (
          <div className="summary-grid">
            <div>
              <div className="label">{t('dashboard.totalLabel')}</div>
              <div className="value">{summary.total.toFixed(2)} {currency}</div>
            </div>
            {members.map((m) => (
              <div key={m.id}>
                <div className="label">{m.name}</div>
                <div className="value">
                  {(summary.byPayer.find((p) => p.userId === m.id)?.total || 0).toFixed(2)} {currency}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
