import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'

// ── Constants ─────────────────────────────────────────────────────────────────

const CATEGORIES = [
  { id: 'supplier',    label: 'Προμηθευτής' },
  { id: 'utilities',  label: 'Κοινή Χρεία' },
  { id: 'rent',       label: 'Ενοίκιο' },
  { id: 'maintenance',label: 'Συντήρηση' },
  { id: 'staff',      label: 'Προσωπικό' },
  { id: 'equipment',  label: 'Εξοπλισμός' },
  { id: 'other',      label: 'Άλλο' },
]

const STATUS_CONFIG = {
  due:     { label: 'Οφείλεται',    bg: '#fee2e2', color: '#dc2626' },
  partial: { label: 'Μερική Πληρ.', bg: '#fef9c3', color: '#a16207' },
  paid:    { label: 'Πληρώθηκε',    bg: '#dcfce7', color: '#16a34a' },
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function fmt(n) {
  if (n == null) return '—'
  return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
}

function fmtDate(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit', year: 'numeric' })
}

function fmtDateTime(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
}

const inputStyle = {
  width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
  borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
}

// ── Expense form modal ────────────────────────────────────────────────────────

const EMPTY_FORM = { description: '', category: 'supplier', contact_id: '', total_amount: '', due_date: '', notes: '' }

function ExpenseModal({ initial, contacts, onClose, onSave, isPending }) {
  const [form, setForm] = useState(initial ?? EMPTY_FORM)
  const f = (k, v) => setForm(p => ({ ...p, [k]: v }))
  const isNew = !initial?.id
  const canSave = form.description.trim() && parseFloat(form.total_amount) > 0

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50, padding: 20 }}>
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 540, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{isNew ? 'Νέο Έξοδο' : 'Επεξεργασία Εξόδου'}</h2>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
        </div>

        <div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Περιγραφή *</label>
            <input style={inputStyle} value={form.description} onChange={e => f('description', e.target.value)} autoFocus placeholder="π.χ. Τιμολόγιο Νοεμβρίου — Γαλακτοκομικά" />
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Κατηγορία</label>
              <select style={inputStyle} value={form.category} onChange={e => f('category', e.target.value)}>
                {CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό (€) *</label>
              <input style={inputStyle} type="number" step="0.01" min="0" value={form.total_amount} onChange={e => f('total_amount', e.target.value)} placeholder="0.00" />
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Επαφή / Προμηθευτής</label>
              <select style={inputStyle} value={form.contact_id} onChange={e => f('contact_id', e.target.value)}>
                <option value="">— Χωρίς επαφή —</option>
                {contacts.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ημ/νία πληρωμής</label>
              <input style={inputStyle} type="date" value={form.due_date ? form.due_date.slice(0, 10) : ''} onChange={e => f('due_date', e.target.value)} />
            </div>
          </div>

          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημειώσεις</label>
            <textarea style={{ ...inputStyle, resize: 'none' }} rows={2} value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="Προαιρετικές σημειώσεις…" />
          </div>
        </div>

        <div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
          <button
            onClick={() => onSave(form)}
            disabled={!canSave || isPending}
            style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canSave && !isPending ? 'pointer' : 'default', background: canSave ? '#111827' : '#e5e7eb', color: canSave ? 'white' : '#9ca3af' }}
          >
            {isPending ? 'Αποθήκευση…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── Pay modal ─────────────────────────────────────────────────────────────────

function PayModal({ expense, onClose, onPay, isPending }) {
  const [amount, setAmount] = useState(String(Math.round((expense.due_amount) * 100) / 100))
  const [notes, setNotes] = useState('')
  const parsed = parseFloat(amount)
  const canPay = parsed > 0 && parsed <= expense.due_amount + 0.001

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 400, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
        <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef' }}>
          <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Καταγραφή Πληρωμής</h2>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: '#6b7280' }}>{expense.description}</p>
        </div>
        <div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ background: '#f9fafb', borderRadius: 10, padding: '12px 14px', display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 13, color: '#6b7280' }}>Εκκρεμεί</span>
            <span style={{ fontSize: 15, fontWeight: 700, color: '#dc2626' }}>{fmt(expense.due_amount)}</span>
          </div>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό πληρωμής (€)</label>
            <input style={inputStyle} type="number" step="0.01" min="0.01" max={expense.due_amount} value={amount} onChange={e => setAmount(e.target.value)} autoFocus />
          </div>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημείωση</label>
            <input style={inputStyle} value={notes} onChange={e => setNotes(e.target.value)} placeholder="π.χ. Μετρητά στο χέρι" />
          </div>
        </div>
        <div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
          <button
            onClick={() => onPay(parsed, notes || null)}
            disabled={!canPay || isPending}
            style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canPay && !isPending ? 'pointer' : 'default', background: canPay ? '#16a34a' : '#e5e7eb', color: canPay ? 'white' : '#9ca3af' }}
          >
            {isPending ? 'Αποθήκευση…' : 'Καταγραφή Πληρωμής'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── Expense row (expandable) ──────────────────────────────────────────────────

function ExpenseRow({ expense, isExpanded, onToggle, onPay, onEdit, onDelete }) {
  const sc = STATUS_CONFIG[expense.status] || STATUS_CONFIG.due
  const catLabel = CATEGORIES.find(c => c.id === expense.category)?.label || expense.category

  return (
    <>
      <tr
        onClick={onToggle}
        style={{ borderBottom: '1px solid #f3f4f6', cursor: 'pointer', background: isExpanded ? '#f9fafb' : 'white' }}
      >
        <td style={{ padding: '12px 16px' }}>
          <div style={{ fontWeight: 600, color: '#111315', fontSize: 13.5 }}>{expense.description}</div>
          {expense.contact_name && <div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 1 }}>{expense.contact_name}</div>}
        </td>
        <td style={{ padding: '12px 16px', fontSize: 12, color: '#6b7280' }}>{catLabel}</td>
        <td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 600, color: '#111315', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{fmt(expense.total_amount)}</td>
        <td style={{ padding: '12px 16px', fontSize: 13, color: '#16a34a', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{expense.paid_amount > 0 ? fmt(expense.paid_amount) : '—'}</td>
        <td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 700, color: '#dc2626', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{expense.due_amount > 0 ? fmt(expense.due_amount) : '—'}</td>
        <td style={{ padding: '12px 16px' }}>
          <span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: sc.bg, color: sc.color }}>{sc.label}</span>
        </td>
        <td style={{ padding: '12px 16px', fontSize: 12, color: '#9ca3af' }}>{expense.due_date ? fmtDate(expense.due_date) : '—'}</td>
        <td style={{ padding: '12px 16px', textAlign: 'right' }}>
          <div style={{ display: 'flex', gap: 5, justifyContent: 'flex-end' }}>
            {expense.status !== 'paid' && (
              <button
                onClick={e => { e.stopPropagation(); onPay() }}
                style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #bbf7d0', background: '#f0fdf4', fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#16a34a' }}
              >
                Πληρωμή
              </button>
            )}
            <button
              onClick={e => { e.stopPropagation(); onEdit() }}
              style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #e5e7eb', background: 'white', fontSize: 12, cursor: 'pointer', color: '#374151' }}
            >
              Επεξ.
            </button>
            <button
              onClick={e => { e.stopPropagation(); onDelete() }}
              style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid #fecaca', background: 'white', fontSize: 12, cursor: 'pointer', color: '#ef4444' }}
            >
              ✕
            </button>
          </div>
        </td>
      </tr>

      {isExpanded && (
        <tr style={{ background: '#f9fafb' }}>
          <td colSpan={8} style={{ padding: '12px 16px 16px', borderBottom: '1px solid #f0f0ef' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {expense.notes && (
                <p style={{ margin: 0, fontSize: 12.5, color: '#6b7280', fontStyle: 'italic' }}>📝 {expense.notes}</p>
              )}
              <div style={{ fontSize: 11.5, color: '#9ca3af' }}>
                Καταχωρήθηκε από {expense.created_by_name} · {fmtDate(expense.created_at)}
              </div>
              {expense.payments.length > 0 && (
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Ιστορικό Πληρωμών</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    {expense.payments.map(p => (
                      <div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 12px', background: 'white', borderRadius: 8, border: '1px solid #e5e7eb' }}>
                        <span style={{ fontSize: 12.5, color: '#374151' }}>
                          {p.paid_by_name} · {fmtDateTime(p.paid_at)}
                          {p.notes && <span style={{ color: '#9ca3af' }}> — {p.notes}</span>}
                        </span>
                        <span style={{ fontSize: 13, fontWeight: 700, color: '#16a34a' }}>{fmt(p.amount)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {expense.payments.length === 0 && expense.status === 'due' && (
                <div style={{ fontSize: 12.5, color: '#d1d5db' }}>Δεν έχουν καταγραφεί πληρωμές.</div>
              )}
            </div>
          </td>
        </tr>
      )}
    </>
  )
}

// ── Main page ─────────────────────────────────────────────────────────────────

export default function ExpensesPage() {
  const qc = useQueryClient()
  const [statusFilter, setStatusFilter] = useState('all')
  const [categoryFilter, setCategoryFilter] = useState('all')
  const [expanded, setExpanded] = useState(null)
  const [modal, setModal] = useState(null)   // null | { type: 'expense', expense? } | { type: 'pay', expense }

  const params = {}
  if (statusFilter !== 'all') params.status = statusFilter
  if (categoryFilter !== 'all') params.category = categoryFilter

  const { data: expenses = [], isLoading } = useQuery({
    queryKey: ['expenses', statusFilter, categoryFilter],
    queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data),
    staleTime: 15_000,
  })

  const { data: contacts = [] } = useQuery({
    queryKey: ['contacts'],
    queryFn: () => client.get('/api/contacts/').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: summary } = useQuery({
    queryKey: ['expenses-summary'],
    queryFn: () => client.get('/api/expenses/summary').then(r => r.data),
    staleTime: 15_000,
  })

  const saveExpense = useMutation({
    mutationFn: ({ form, id }) => id
      ? client.put(`/api/expenses/${id}`, form)
      : client.post('/api/expenses/', form),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['expenses'] })
      qc.invalidateQueries({ queryKey: ['expenses-summary'] })
      setModal(null)
      toast.success('Αποθηκεύτηκε')
    },
    onError: () => toast.error('Σφάλμα αποθήκευσης'),
  })

  const payExpense = useMutation({
    mutationFn: ({ id, amount, notes }) => client.post(`/api/expenses/${id}/pay`, { amount, notes }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['expenses'] })
      qc.invalidateQueries({ queryKey: ['expenses-summary'] })
      setModal(null)
      toast.success('Πληρωμή καταγράφηκε')
    },
    onError: () => toast.error('Σφάλμα καταγραφής πληρωμής'),
  })

  const deleteExpense = useMutation({
    mutationFn: (id) => client.delete(`/api/expenses/${id}`),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['expenses'] })
      qc.invalidateQueries({ queryKey: ['expenses-summary'] })
      toast.success('Διαγράφηκε')
    },
    onError: () => toast.error('Σφάλμα διαγραφής'),
  })

  const totalDue = summary?.total_due ?? 0
  const pendingCount = expenses.filter(e => e.status !== 'paid').length

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      {/* Header */}
      <div style={{ padding: '18px 28px 14px', borderBottom: '1px solid #f0f0ef', flexShrink: 0, background: 'white' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div>
            <p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>
              {pendingCount} εκκρεμή · Σύνολο οφειλών: <strong style={{ color: totalDue > 0 ? '#dc2626' : '#16a34a' }}>{fmt(totalDue)}</strong>
            </p>
          </div>
          <button
            onClick={() => setModal({ type: 'expense', expense: null })}
            style={{ padding: '9px 18px', borderRadius: 9, border: 'none', background: '#111827', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
          >
            + Νέο Έξοδο
          </button>
        </div>

        {/* Filters */}
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {/* Status filter */}
          <div style={{ display: 'flex', gap: 4 }}>
            {[['all', 'Όλα'], ['due', 'Οφείλεται'], ['partial', 'Μερική'], ['paid', 'Πληρώθηκε']].map(([v, l]) => (
              <button key={v} onClick={() => setStatusFilter(v)}
                style={{
                  padding: '5px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, cursor: 'pointer', border: '1.5px solid',
                  borderColor: statusFilter === v ? '#111827' : '#e5e7eb',
                  background: statusFilter === v ? '#111827' : 'white',
                  color: statusFilter === v ? 'white' : '#6b7280',
                }}>
                {l}
              </button>
            ))}
          </div>
          {/* Category filter */}
          <select
            value={categoryFilter}
            onChange={e => setCategoryFilter(e.target.value)}
            style={{ padding: '5px 10px', borderRadius: 8, border: '1px solid #e5e7eb', fontSize: 12, outline: 'none', background: 'white', color: '#374151' }}
          >
            <option value="all">Όλες οι κατηγορίες</option>
            {CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
          </select>
        </div>
      </div>

      {/* Table */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 28px' }}>
        {isLoading && <div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0' }}>Φόρτωση…</div>}
        {!isLoading && expenses.length === 0 && (
          <div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0', fontSize: 14 }}>
            Δεν βρέθηκαν έξοδα για τα επιλεγμένα φίλτρα.
          </div>
        )}
        {expenses.length > 0 && (
          <div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: '#f9fafb', borderBottom: '1px solid #e5e7eb' }}>
                  {['Περιγραφή', 'Κατηγορία', 'Σύνολο', 'Πληρωμένο', 'Εκκρεμεί', 'Κατάσταση', 'Ημ/νία', ''].map(h => (
                    <th key={h} style={{ padding: '10px 16px', textAlign: h === 'Σύνολο' || h === 'Πληρωμένο' || h === 'Εκκρεμεί' ? 'right' : 'left', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {expenses.map(e => (
                  <ExpenseRow
                    key={e.id}
                    expense={e}
                    isExpanded={expanded === e.id}
                    onToggle={() => setExpanded(expanded === e.id ? null : e.id)}
                    onPay={() => setModal({ type: 'pay', expense: e })}
                    onEdit={() => setModal({ type: 'expense', expense: e })}
                    onDelete={() => { if (window.confirm('Διαγραφή εξόδου;')) deleteExpense.mutate(e.id) }}
                  />
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Expense create/edit modal */}
      {modal?.type === 'expense' && (
        <ExpenseModal
          initial={modal.expense ? {
            ...modal.expense,
            contact_id: modal.expense.contact_id ? String(modal.expense.contact_id) : '',
            due_date: modal.expense.due_date || '',
            notes: modal.expense.notes || '',
          } : null}
          contacts={contacts}
          onClose={() => setModal(null)}
          isPending={saveExpense.isPending}
          onSave={(form) => saveExpense.mutate({
            form: {
              description: form.description,
              category: form.category,
              contact_id: form.contact_id ? Number(form.contact_id) : null,
              total_amount: parseFloat(form.total_amount),
              due_date: form.due_date || null,
              notes: form.notes || null,
            },
            id: modal.expense?.id,
          })}
        />
      )}

      {/* Pay modal */}
      {modal?.type === 'pay' && (
        <PayModal
          expense={modal.expense}
          onClose={() => setModal(null)}
          isPending={payExpense.isPending}
          onPay={(amount, notes) => payExpense.mutate({ id: modal.expense.id, amount, notes })}
        />
      )}
    </div>
  )
}
