'use client';

import { useMemo, useState } from 'react';
import { documents, monthNames, type DocumentType } from './data';

const currency = new Intl.NumberFormat('de-AT', { style: 'currency', currency: 'EUR' });
const dateFormat = new Intl.DateTimeFormat('de-AT', { day: '2-digit', month: '2-digit', year: 'numeric' });
const allTypes: Array<'Alle' | DocumentType> = ['Alle', 'Rechnung', 'Storno', 'Gutschrift'];
const months = ['Alle', '04', '05', '06', '07'];

function formatDate(value: string) {
  return dateFormat.format(new Date(`${value}T00:00:00`));
}

export default function Home() {
  const [query, setQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState<'Alle' | DocumentType>('Alle');
  const [monthFilter, setMonthFilter] = useState('Alle');

  const totals = useMemo(() => {
    const invoiceBalance = documents.filter((item) => item.type !== 'Gutschrift').reduce((sum, item) => sum + item.amount, 0);
    const credits = documents.filter((item) => item.type === 'Gutschrift').reduce((sum, item) => sum + item.amount, 0);
    return { invoiceBalance, credits, balance: invoiceBalance - credits };
  }, []);

  const monthly = useMemo(() => Object.entries(monthNames).map(([month, name]) => {
    const rows = documents.filter((item) => item.date.slice(5, 7) === month);
    const value = rows.reduce((sum, item) => sum + (item.type === 'Gutschrift' ? -item.amount : item.amount), 0);
    return { month, name, value, count: rows.length };
  }), []);
  const maxMonth = Math.max(...monthly.map((item) => Math.abs(item.value)));

  const filtered = useMemo(() => {
    const needle = query.trim().toLocaleLowerCase('de');
    return documents
      .filter((item) => typeFilter === 'Alle' || item.type === typeFilter)
      .filter((item) => monthFilter === 'Alle' || item.date.slice(5, 7) === monthFilter)
      .filter((item) => !needle || [item.number, item.customer, item.reference].some((value) => value.toLocaleLowerCase('de').includes(needle)))
      .sort((a, b) => b.date.localeCompare(a.date) || b.number.localeCompare(a.number));
  }, [query, typeFilter, monthFilter]);

  const filteredSum = filtered.reduce((sum, item) => sum + (item.type === 'Gutschrift' ? -item.amount : item.amount), 0);

  return (
    <main className="shell">
      <header className="topbar">
        <div className="brand-mark" aria-hidden="true">W</div>
        <div>
          <p className="eyebrow">WIKIMONT GmbH</p>
          <p className="brand-title">Belegübersicht</p>
        </div>
        <div className="topbar-meta"><span className="live-dot" />Datenstand Juli 2026</div>
      </header>

      <section className="hero">
        <div>
          <p className="kicker">Ausgangsrechnungen · 2026</p>
          <h1>Finanzen auf einen Blick.</h1>
          <p className="hero-copy">42 Rechnungen, Stornos und Gutschriften aus April bis Juli – direkt aus den Originalbelegen erfasst und in einer klaren Arbeitsübersicht zusammengeführt.</p>
        </div>
        <div className="hero-badge"><span>42</span><small>Belege erfasst</small></div>
      </section>

      <section className="stats" aria-label="Kennzahlen">
        <article className="stat-card accent"><p>Belegsaldo</p><strong>{currency.format(totals.balance)}</strong><span>Rechnungen abzüglich Gutschriften</span></article>
        <article className="stat-card"><p>Rechnungssaldo</p><strong>{currency.format(totals.invoiceBalance)}</strong><span>inklusive 7 Stornos</span></article>
        <article className="stat-card"><p>Gutschriften</p><strong>{currency.format(totals.credits)}</strong><span>5 Dokumente im Juni</span></article>
        <article className="stat-card"><p>Kunden</p><strong>11</strong><span>Österreich & Deutschland</span></article>
      </section>

      <section className="analysis-grid">
        <article className="panel monthly-panel">
          <div className="panel-heading"><div><p className="eyebrow">Entwicklung</p><h2>Saldo nach Monat</h2></div><span>Apr–Jul 2026</span></div>
          <div className="bars">
            {monthly.map((item) => (
              <div className="bar-row" key={item.month}>
                <div className="bar-label"><strong>{item.name}</strong><span>{item.count} Belege</span></div>
                <div className="bar-track"><span className={item.value < 0 ? 'negative' : ''} style={{ width: `${Math.max(12, Math.abs(item.value) / maxMonth * 100)}%` }} /></div>
                <strong className={item.value < 0 ? 'negative-text' : ''}>{currency.format(item.value)}</strong>
              </div>
            ))}
          </div>
          <p className="chart-note">Im Juni reduzieren Stornos und Gutschriften den Monatssaldo.</p>
        </article>

        <article className="panel snapshot-panel">
          <p className="eyebrow">Schnellbild</p>
          <h2>37 Rechnungen</h2>
          <div className="donut" aria-label="37 Rechnungen, davon 7 Stornos"><span>7<small>Stornos</small></span></div>
          <div className="legend"><span><i className="legend-green" />30 regulär</span><span><i className="legend-orange" />7 storniert</span></div>
        </article>
      </section>

      <section className="ledger">
        <div className="section-heading">
          <div><p className="eyebrow">Belegjournal</p><h2>Alle Dokumente</h2></div>
          <div className="result-total"><span>Auswahl</span><strong>{currency.format(filteredSum)}</strong></div>
        </div>

        <div className="filters" aria-label="Belege filtern">
          <label className="search"><span className="sr-only">Belege durchsuchen</span><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Beleg, Kunde oder Referenz suchen …" /></label>
          <div className="segments" aria-label="Belegart">
            {allTypes.map((type) => <button type="button" key={type} aria-pressed={typeFilter === type} onClick={() => setTypeFilter(type)}>{type}</button>)}
          </div>
          <select aria-label="Monat" value={monthFilter} onChange={(event) => setMonthFilter(event.target.value)}>
            {months.map((month) => <option key={month} value={month}>{month === 'Alle' ? 'Alle Monate' : monthNames[month]}</option>)}
          </select>
        </div>

        <div className="table-wrap">
          <table>
            <thead><tr><th>Beleg</th><th>Datum</th><th>Kunde</th><th>Referenz</th><th>Art</th><th>Betrag</th></tr></thead>
            <tbody>
              {filtered.map((row) => (
                <tr key={row.number}>
                  <td><strong>{row.number}</strong></td>
                  <td>{formatDate(row.date)}</td>
                  <td className="customer">{row.customer}</td>
                  <td className="reference">{row.reference}</td>
                  <td><span className={`tag ${row.type.toLowerCase()}`}>{row.type}</span></td>
                  <td className={`amount ${row.amount < 0 ? 'negative-text' : ''}`}>{currency.format(row.amount)}</td>
                </tr>
              ))}
              {filtered.length === 0 && <tr><td className="empty" colSpan={6}>Keine passenden Belege gefunden.</td></tr>}
            </tbody>
          </table>
        </div>
        <p className="table-footer">{filtered.length} von 42 Belegen angezeigt · Beträge laut PDF-Gesamtbetrag brutto</p>
      </section>

      <footer><span>WIKIMONT GmbH · Projektabwicklung & Montage</span><span>Privater Finanzüberblick · 2026</span></footer>
    </main>
  );
}
