import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Receipt, Plus, Trash2, Wallet, FileText } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, KpiCard, Btn, Field, inputCls, Modal, Spinner, EmptyState, ErrorBox, Table, StatusBadge } from '../components/ui';

const today = () => new Date().toISOString().split('T')[0];

const STATUS_LABELS = {
  draft: 'Concept', sent: 'Verzonden', paid: 'Betaald', overdue: 'Verlopen', cancelled: 'Geannuleerd'
};

const EMPTY_ITEM = { description: '', quantity: 1, unit_price: '' };

function NewInvoiceModal({ open, onClose, clients, onSaved }) {
  const [form, setForm] = useState({ client_id: '', date: '', due_date: '', notes: '' });
  const [items, setItems] = useState([{ ...EMPTY_ITEM }]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open) return;
    setForm({ client_id: '', date: today(), due_date: '', notes: '' });
    setItems([{ ...EMPTY_ITEM }]);
    setError(null);
  }, [open]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const setItem = (i, k, v) => setItems(list => list.map((it, idx) => idx === i ? { ...it, [k]: v } : it));
  const addItem = () => setItems(list => [...list, { ...EMPTY_ITEM }]);
  const removeItem = (i) => setItems(list => list.filter((_, idx) => idx !== i));

  const subtotal = useMemo(
    () => items.reduce((s, it) => s + (parseFloat(it.quantity) || 0) * (parseFloat(it.unit_price) || 0), 0),
    [items]
  );
  const tax = subtotal * 0.21;
  const total = subtotal + tax;

  const submit = async (e) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    try {
      await api.post('/invoices', {
        client_id: form.client_id,
        date: form.date,
        due_date: form.due_date,
        notes: form.notes,
        items: items.filter(it => it.description.trim()),
        subtotal,
        tax
      });
      onSaved();
      onClose();
    } catch (err) {
      setError(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Nieuwe factuur" wide>
      <form onSubmit={submit} className="space-y-4">
        <ErrorBox error={error} />
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <Field label="Cliënt *">
            <select required className={inputCls} value={form.client_id} onChange={e => set('client_id', e.target.value)}>
              <option value="">— Kies een cliënt —</option>
              {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </Field>
          <Field label="Factuurdatum">
            <input type="date" className={inputCls} value={form.date} onChange={e => set('date', e.target.value)} />
          </Field>
          <Field label="Vervaldatum">
            <input type="date" className={inputCls} value={form.due_date} onChange={e => set('due_date', e.target.value)} />
          </Field>
        </div>

        <div>
          <div className="flex items-center justify-between mb-2">
            <span className="text-[12px] text-muted">Factuurregels</span>
            <Btn type="button" variant="secondary" size="sm" onClick={addItem}>
              <Plus className="w-3 h-3" /> Regel toevoegen
            </Btn>
          </div>
          <div className="space-y-2">
            {items.map((it, i) => (
              <div key={i} className="flex items-center gap-2">
                <input
                  className={`${inputCls} flex-1`}
                  placeholder="Omschrijving"
                  value={it.description}
                  onChange={e => setItem(i, 'description', e.target.value)}
                />
                <input
                  type="number" min="0" step="0.25"
                  className={`${inputCls} !w-24`}
                  placeholder="Aantal"
                  value={it.quantity}
                  onChange={e => setItem(i, 'quantity', e.target.value)}
                />
                <input
                  type="number" min="0" step="0.01"
                  className={`${inputCls} !w-28`}
                  placeholder="Prijs"
                  value={it.unit_price}
                  onChange={e => setItem(i, 'unit_price', e.target.value)}
                />
                <span className="text-[12px] text-muted w-24 text-right shrink-0">{fmt.euro((parseFloat(it.quantity) || 0) * (parseFloat(it.unit_price) || 0))}</span>
                <button
                  type="button"
                  onClick={() => removeItem(i)}
                  disabled={items.length === 1}
                  className="p-1.5 rounded-md text-muted hover:text-red hover:bg-red/10 disabled:opacity-30 disabled:cursor-not-allowed shrink-0"
                  title="Regel verwijderen"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        </div>

        <div className="flex justify-end">
          <div className="w-64 space-y-1.5 text-[13px]">
            <div className="flex justify-between">
              <span className="text-muted">Subtotaal</span>
              <span>{fmt.euro(subtotal)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted">BTW (21%)</span>
              <span>{fmt.euro(tax)}</span>
            </div>
            <div className="flex justify-between font-semibold border-t border-border-soft pt-1.5">
              <span>Totaal</span>
              <span>{fmt.euro(total)}</span>
            </div>
          </div>
        </div>

        <Field label="Notities">
          <textarea className={inputCls} rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} placeholder="Bijv. betalingsvoorwaarden" />
        </Field>

        <div className="flex justify-end gap-2 pt-1">
          <Btn type="button" variant="secondary" onClick={onClose}>Annuleren</Btn>
          <Btn type="submit" loading={saving}>Factuur aanmaken</Btn>
        </div>
      </form>
    </Modal>
  );
}

export default function Invoices() {
  const [data, setData] = useState(null);
  const [clients, setClients] = useState([]);
  const [error, setError] = useState(null);
  const [modalOpen, setModalOpen] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    api.get('/clients').then(setClients).catch(() => {});
  }, []);

  const load = () => {
    setError(null);
    api.get('/invoices').then(setData).catch(setError);
  };
  useEffect(load, []);

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-xl font-bold tracking-tight">Facturen</h1>
          <p className="text-[13px] text-muted mt-0.5">Beheer je facturatie en betalingen</p>
        </div>
        <Btn onClick={() => setModalOpen(true)}>
          <Plus className="w-3.5 h-3.5" /> Nieuwe factuur
        </Btn>
      </div>

      {error ? (
        <ErrorBox error={error} onRetry={load} />
      ) : !data ? (
        <Spinner />
      ) : (
        <>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
            <KpiCard icon={Receipt} label="Openstaand" value={fmt.euro(data.totalOutstanding)} color="yellow" />
            <KpiCard icon={Wallet} label="Betaald" value={fmt.euro(data.totalPaid)} color="green" />
            <KpiCard icon={FileText} label="Totaal facturen" value={data.invoices.length} color="accent" />
          </div>

          <Card>
            <Table
              columns={[
                {
                  label: 'Nummer',
                  render: r => (
                    <Link to={`/invoices/${r.id}`} onClick={e => e.stopPropagation()} className="font-medium text-accent hover:underline">
                      {r.number}
                    </Link>
                  )
                },
                { label: 'Cliënt', key: 'client_name' },
                { label: 'Datum', render: r => <span className="text-muted">{fmt.date(r.date)}</span> },
                { label: 'Vervaldatum', render: r => <span className="text-muted">{r.due_date ? fmt.date(r.due_date) : '-'}</span> },
                { label: 'Totaal', render: r => fmt.euro(r.total) },
                { label: 'Status', render: r => <StatusBadge status={r.status} labels={STATUS_LABELS} /> }
              ]}
              rows={data.invoices}
              keyFn={r => r.id}
              onRowClick={r => navigate(`/invoices/${r.id}`)}
              empty={<EmptyState icon={Receipt} title="Nog geen facturen" hint="Maak je eerste factuur aan of genereer er een uit je uren." />}
            />
          </Card>
        </>
      )}

      <NewInvoiceModal open={modalOpen} onClose={() => setModalOpen(false)} clients={clients} onSaved={load} />
    </div>
  );
}
