import { useState } from 'react';
import { type Category, type Transaction, createTransaction, createCategory } from '../api';

export default function ManualManagement({
  categories,
  onTransactionAdded,
  onCategoryCreated,
}: {
  categories: Category[];
  onTransactionAdded: (t: Transaction) => void;
  onCategoryCreated: (c: Category) => void;
}) {
  // New transaction form state
  const [amount, setAmount] = useState<string>('');
  const [description, setDescription] = useState('');
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | ''>('');
  const [txDate, setTxDate] = useState<string>('');

  // Category creation form
  const [newCatName, setNewCatName] = useState('');
  const [newCatDesc, setNewCatDesc] = useState('');

  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,
      date: txDate || undefined,
    };
    try {
      const created = await createTransaction(payload);
      onTransactionAdded(created);
      setAmount(''); setDescription(''); setSelectedCategoryId(''); setTxDate('');
    } catch (err: any) {
      alert(err?.message || 'Failed to create transaction');
    }
  }

  async function handleCreateCategory(e: React.FormEvent) {
    e.preventDefault();
    if (!newCatName.trim()) return;
    try {
      const cat = await createCategory({ name: newCatName.trim(), description: newCatDesc || undefined });
      onCategoryCreated(cat);
      setNewCatName(''); setNewCatDesc('');
    } catch (err: any) {
      alert(err?.message || 'Failed to create category');
    }
  }

  return (
    <>
      <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="date" placeholder="Date (optional)" value={txDate} onChange={(e) => setTxDate(e.target.value)} />
          <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>Categories</h3>
        <form className="form-row" onSubmit={handleCreateCategory}>
          <input className="input" type="text" placeholder="New category name" value={newCatName} onChange={(e) => setNewCatName(e.target.value)} />
          <input className="input" type="text" placeholder="Description (optional)" value={newCatDesc} onChange={(e) => setNewCatDesc(e.target.value)} />
          <button className="btn primary" type="submit">Create category</button>
        </form>
      </section>
    </>
  );
}
