import { useEffect, useMemo, useState } from 'react';
import { type Category, type Transaction, createTransaction, getCategories, getTransactions } from '../api';
import AccountPage from './AccountPage';
import AppearancePage from './AppearancePage';

function formatAmount(n: number) {
  return new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n);
}

export default function Dashboard({ onLogout }: { onLogout: () => void }) {
  const [current, setCurrent] = useState<'home' | 'account' | 'appearance'>('home');
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // New transaction form state
  const [amount, setAmount] = useState<string>('');
  const [description, setDescription] = useState('');
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | ''>('');

  // Filters
  const [minAmount, setMinAmount] = useState<string>('');
  const [maxAmount, setMaxAmount] = useState<string>('');
  const [filterCategoryId, setFilterCategoryId] = useState<number | ''>('');
  const [searchText, setSearchText] = useState('');

  async function loadAll() {
    setLoading(true);
    setError(null);
    try {
      const [txs, cats] = await Promise.all([getTransactions(), getCategories()]);
      setTransactions(txs);
      setCategories(cats);
    } catch (err: any) {
      setError(err?.message || 'Failed to load data');
    } finally {
      setLoading(false);
    }
  }

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

  const last10 = useMemo(() => {
    const sorted = [...transactions].sort((a, b) => b.id - a.id);
    return sorted.slice(0, 10);
  }, [transactions]);

  const filtered = useMemo(() => {
    let arr = last10;
    const min = minAmount !== '' ? Number(minAmount) : undefined;
    const max = maxAmount !== '' ? Number(maxAmount) : undefined;
    if (min !== undefined) arr = arr.filter(t => t.amount >= min);
    if (max !== undefined) arr = arr.filter(t => t.amount <= max);
    if (filterCategoryId !== '') arr = arr.filter(t => t.category_ids.includes(filterCategoryId as number));
    if (searchText.trim()) arr = arr.filter(t => (t.description || '').toLowerCase().includes(searchText.toLowerCase()));
    return arr;
  }, [last10, minAmount, maxAmount, filterCategoryId, searchText]);

  function categoryNameById(id: number) { return categories.find(c => c.id === id)?.name || `#${id}`; }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!amount) return;
    const payload = {
      amount: Number(amount),
      description: description || undefined,
      category_ids: selectedCategoryId !== '' ? [Number(selectedCategoryId)] : undefined,
    };
    try {
      const created = await createTransaction(payload);
      setTransactions(prev => [created, ...prev]);
      setAmount(''); setDescription(''); setSelectedCategoryId('');
    } catch (err: any) {
      alert(err?.message || 'Failed to create transaction');
    }
  }

  return (
    <div className="app-layout">
      <aside className="sidebar">
        <div className="logo">7Project</div>
        <nav className="nav">
          <button className={current === 'home' ? 'active' : ''} onClick={() => setCurrent('home')}>Home</button>
          <button className={current === 'account' ? 'active' : ''} onClick={() => setCurrent('account')}>Account</button>
          <button className={current === 'appearance' ? 'active' : ''} onClick={() => setCurrent('appearance')}>Appearance</button>
        </nav>
      </aside>
      <div className="content">
        <div className="topbar">
          <h2 style={{ margin: 0 }}>{current === 'home' ? 'Dashboard' : current === 'account' ? 'Account' : 'Appearance'}</h2>
          <div className="actions">
            <span className="user muted">Signed in</span>
            <button className="btn" onClick={onLogout}>Logout</button>
          </div>
        </div>
        <main className="page space-y">
          {current === 'home' && (
            <>
              <section className="card">
                <h3>Add Transaction</h3>
                <form onSubmit={handleCreate} className="form-row">
                  <input className="input" type="number" step="0.01" placeholder="Amount" value={amount} onChange={(e) => setAmount(e.target.value)} required />
                  <input className="input" type="text" placeholder="Description (optional)" value={description} onChange={(e) => setDescription(e.target.value)} />
                  <select className="input" value={selectedCategoryId} onChange={(e) => setSelectedCategoryId(e.target.value ? Number(e.target.value) : '')}>
                    <option value="">No category</option>
                    {categories.map(c => (<option key={c.id} value={c.id}>{c.name}</option>))}
                  </select>
                  <button className="btn primary" type="submit">Add</button>
                </form>
              </section>

              <section className="card">
                <h3>Filters</h3>
                <div className="form-row">
                  <input className="input" type="number" step="0.01" placeholder="Min amount" value={minAmount} onChange={(e) => setMinAmount(e.target.value)} />
                  <input className="input" type="number" step="0.01" placeholder="Max amount" value={maxAmount} onChange={(e) => setMaxAmount(e.target.value)} />
                  <select className="input" value={filterCategoryId} onChange={(e) => setFilterCategoryId(e.target.value ? Number(e.target.value) : '')}>
                    <option value="">All categories</option>
                    {categories.map(c => (<option key={c.id} value={c.id}>{c.name}</option>))}
                  </select>
                  <input className="input" type="text" placeholder="Search in description" value={searchText} onChange={(e) => setSearchText(e.target.value)} />
                </div>
              </section>

              <section className="card">
                <h3>Latest Transactions (last 10)</h3>
                {loading ? (
                  <div>Loading…</div>
                ) : error ? (
                  <div style={{ color: 'crimson' }}>{error}</div>
                ) : filtered.length === 0 ? (
                  <div>No transactions</div>
                ) : (
                  <table className="table">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th style={{ textAlign: 'right' }}>Amount</th>
                        <th>Description</th>
                        <th>Categories</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filtered.map(t => (
                        <tr key={t.id}>
                          <td>{t.id}</td>
                          <td className="amount">{formatAmount(t.amount)}</td>
                          <td>{t.description || ''}</td>
                          <td>{t.category_ids.map(id => categoryNameById(id)).join(', ')}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </section>
            </>
          )}

          {current === 'account' && (
            // lazy import avoided for simplicity
            <AccountPage onDeleted={onLogout} />
          )}

          {current === 'appearance' && (
            <AppearancePage />
          )}
        </main>
      </div>
    </div>
  );
}
