import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { FileText, AlertCircle, CheckCircle, Clock } from 'lucide-react'
import client from '../../api/client'
import { FilterBar, FilterSelect } from './shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD } from './shared/TablePrimitives'
import StatCard from './shared/StatCard'
import EmptyState from './shared/EmptyState'
import SkeletonTable from './shared/SkeletonTable'
import { fmtEUR, fmtDate } from './shared/reportDesignTokens'

const CATEGORY_LABELS = {
  food: 'Τρόφιμα',
  beverage: 'Ποτά',
  supplies: 'Αναλώσιμα',
  utilities: 'Κοινόχρηστα',
  rent: 'Ενοίκιο',
  salary: 'Μισθοί',
  maintenance: 'Συντήρηση',
  other: 'Άλλο',
}

const STATUS_META = {
  due:     { label: 'Εκκρεμεί',   bg: '#fef2f2', color: '#dc2626' },
  partial: { label: 'Μερική',     bg: '#fff7ed', color: '#c2410c' },
  paid:    { label: 'Πληρώθηκε', bg: '#eef7f0', color: '#1f7042' },
}

// 12 distinct colours for combined view supplier segments
const SUPPLIER_COLORS = [
  '#3b82f6','#10b981','#f59e0b','#ef4444','#8b5cf6',
  '#06b6d4','#f97316','#84cc16','#ec4899','#14b8a6',
  '#a78bfa','#fb923c',
]

function fmtCat(cat) {
  return CATEGORY_LABELS[cat] || cat || '—'
}

// ── Breakdown section ─────────────────────────────────────────────────────────

const BREAKDOWN_VIEWS = [
  { key: 'category', label: 'ΑΝΑ ΚΑΤΗΓΟΡΙΑ' },
  { key: 'contact',  label: 'ΑΝΑ ΕΠΑΦΗ' },
  { key: 'combined', label: 'ΣΥΝΔΙΑΣΤΙΚΑ' },
]

function BreakdownToggle({ value, onChange }) {
  return (
    <div style={{
      display: 'flex', background: '#f1f5f9', borderRadius: 8, padding: 3, gap: 2,
    }}>
      {BREAKDOWN_VIEWS.map(v => (
        <button
          key={v.key}
          onClick={() => onChange(v.key)}
          style={{
            padding: '4px 10px', borderRadius: 6, border: 'none', cursor: 'pointer',
            fontSize: 10, fontWeight: 700, letterSpacing: 0.4,
            transition: 'all 120ms',
            background: value === v.key ? 'white' : 'transparent',
            color: value === v.key ? '#0f172a' : '#64748b',
            boxShadow: value === v.key ? '0 1px 3px rgba(0,0,0,0.12)' : 'none',
          }}
        >
          {v.label}
        </button>
      ))}
    </div>
  )
}

function BreakdownByCategoryRow({ cat, total }) {
  return (
    <div className="flex items-center gap-4 px-5 py-3">
      <div className="w-28 text-[13px] text-slate-700 font-medium flex-shrink-0">{fmtCat(cat.category)}</div>
      <div className="flex-1 h-2 bg-slate-100 rounded-full overflow-hidden">
        <div className="h-full bg-sky-500 rounded-full transition-all" style={{ width: `${total > 0 ? (cat.total / total) * 100 : 0}%` }} />
      </div>
      <div className="text-right flex-shrink-0 w-20">
        <div className="text-[13px] font-mono font-medium text-slate-900">{fmtEUR(cat.total)}</div>
        {cat.due > 0 && <div className="text-[11px] text-rose-500">{fmtEUR(cat.due)} εκκρεμεί</div>}
      </div>
    </div>
  )
}

function BreakdownByContactRow({ name, total, due, grandTotal }) {
  return (
    <div className="flex items-center gap-4 px-5 py-3">
      <div style={{ width: 140 }} className="text-[13px] text-slate-700 font-medium flex-shrink-0 truncate">{name}</div>
      <div className="flex-1 h-2 bg-slate-100 rounded-full overflow-hidden">
        <div className="h-full rounded-full transition-all" style={{
          width: `${grandTotal > 0 ? (total / grandTotal) * 100 : 0}%`,
          background: '#10b981',
        }} />
      </div>
      <div className="text-right flex-shrink-0 w-20">
        <div className="text-[13px] font-mono font-medium text-slate-900">{fmtEUR(total)}</div>
        {due > 0 && <div className="text-[11px] text-rose-500">{fmtEUR(due)} εκκρεμεί</div>}
      </div>
    </div>
  )
}

function BreakdownCombinedRow({ cat, segments, supplierColorMap, grandTotal }) {
  const catTotal = segments.reduce((s, sg) => s + sg.amount, 0)
  if (catTotal === 0) return null
  return (
    <div className="flex items-center gap-4 px-5 py-3">
      <div className="w-28 text-[13px] text-slate-700 font-medium flex-shrink-0">{fmtCat(cat)}</div>
      <div className="flex-1 h-4 bg-slate-100 rounded-full overflow-hidden flex">
        {segments.map(sg => (
          sg.amount > 0 ? (
            <div
              key={sg.name}
              title={`${sg.name}: ${fmtEUR(sg.amount)}`}
              style={{
                width: `${grandTotal > 0 ? (sg.amount / grandTotal) * 100 : 0}%`,
                background: supplierColorMap[sg.name] || '#94a3b8',
                transition: 'width 300ms',
              }}
            />
          ) : null
        ))}
      </div>
      <div className="text-right flex-shrink-0 w-20">
        <div className="text-[13px] font-mono font-medium text-slate-900">{fmtEUR(catTotal)}</div>
      </div>
    </div>
  )
}

function BreakdownSection({ expenses, summary }) {
  const [view, setView] = useState('category')

  // By contact
  const byContact = useMemo(() => {
    const map = {}
    for (const e of expenses) {
      const key = e.contact_name || '(χωρίς προμηθευτή)'
      if (!map[key]) map[key] = { name: key, total: 0, due: 0 }
      map[key].total += e.total_amount
      map[key].due   += e.due_amount
    }
    return Object.values(map).sort((a, b) => b.total - a.total)
  }, [expenses])

  // By combined (category × contact stacked)
  const { combinedRows, supplierColorMap, allSuppliers } = useMemo(() => {
    const catMap = {}
    const suppSet = new Set()
    for (const e of expenses) {
      const cat = e.category || 'other'
      const supp = e.contact_name || '(χωρίς)'
      suppSet.add(supp)
      if (!catMap[cat]) catMap[cat] = {}
      catMap[cat][supp] = (catMap[cat][supp] || 0) + e.total_amount
    }
    const allSupps = [...suppSet]
    const colorMap = {}
    allSupps.forEach((s, i) => { colorMap[s] = SUPPLIER_COLORS[i % SUPPLIER_COLORS.length] })

    const rows = Object.entries(catMap)
      .map(([cat, suppAmounts]) => ({
        cat,
        segments: allSupps.map(s => ({ name: s, amount: suppAmounts[s] || 0 })),
      }))
      .sort((a, b) => {
        const ta = a.segments.reduce((s, sg) => s + sg.amount, 0)
        const tb = b.segments.reduce((s, sg) => s + sg.amount, 0)
        return tb - ta
      })

    return { combinedRows: rows, supplierColorMap: colorMap, allSuppliers: allSupps }
  }, [expenses])

  const grandTotal = expenses.reduce((s, e) => s + e.total_amount, 0)
  const catGrandTotal = (summary?.by_category || []).reduce((s, c) => s + c.total, 0)

  const hasData = expenses.length > 0 || (summary?.by_category?.length > 0)
  if (!hasData) return null

  return (
    <div className="mb-6">
      <div className="rounded-lg border border-slate-200 bg-white shadow-[0_1px_0_rgba(15,23,42,0.04)] overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-100 flex items-center justify-between">
          <div className="text-[11px] font-semibold uppercase tracking-[0.1em] text-slate-500">
            {view === 'category' ? 'Ανά Κατηγορία' : view === 'contact' ? 'Ανά Επαφή / Προμηθευτή' : 'Συνδιαστική Ανάλυση'}
          </div>
          <BreakdownToggle value={view} onChange={setView} />
        </div>

        {view === 'category' && (
          <div className="divide-y divide-slate-100">
            {(summary?.by_category || [])
              .sort((a, b) => b.total - a.total)
              .map(cat => (
                <BreakdownByCategoryRow key={cat.category} cat={cat} total={catGrandTotal} />
              ))}
          </div>
        )}

        {view === 'contact' && (
          <div className="divide-y divide-slate-100">
            {byContact.map(row => (
              <BreakdownByContactRow
                key={row.name} name={row.name}
                total={row.total} due={row.due}
                grandTotal={grandTotal}
              />
            ))}
            {byContact.length === 0 && (
              <div className="px-5 py-4 text-[13px] text-slate-400">Δεν υπάρχουν δεδομένα.</div>
            )}
          </div>
        )}

        {view === 'combined' && (
          <>
            <div className="divide-y divide-slate-100">
              {combinedRows.map(row => (
                <BreakdownCombinedRow
                  key={row.cat} cat={row.cat}
                  segments={row.segments}
                  supplierColorMap={supplierColorMap}
                  grandTotal={grandTotal}
                />
              ))}
              {combinedRows.length === 0 && (
                <div className="px-5 py-4 text-[13px] text-slate-400">Δεν υπάρχουν δεδομένα.</div>
              )}
            </div>
            {allSuppliers.length > 0 && (
              <div className="px-5 py-3 border-t border-slate-100 flex flex-wrap gap-3">
                {allSuppliers.map(s => (
                  <div key={s} className="flex items-center gap-1.5">
                    <div style={{ width: 10, height: 10, borderRadius: 3, background: supplierColorMap[s], flexShrink: 0 }} />
                    <span style={{ fontSize: 11, color: '#64748b' }}>{s}</span>
                  </div>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  )
}

// ── Detail modal ──────────────────────────────────────────────────────────────

function ExpenseDetailModal({ expense, onClose }) {
  return (
    <div
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}
      onClick={e => { if (e.target === e.currentTarget) onClose() }}
    >
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 520, maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 20px 60px rgba(0,0,0,0.2)' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid #edeff1', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 700, color: '#111315' }}>{expense.description}</div>
            <div style={{ fontSize: 12, color: '#5a6169', marginTop: 2 }}>{fmtCat(expense.category)} · {fmtDate(expense.created_at)}</div>
          </div>
          <button onClick={onClose} style={{ width: 30, height: 30, borderRadius: 8, border: '1px solid #edeff1', background: 'white', fontSize: 16, cursor: 'pointer' }}>×</button>
        </div>
        <div style={{ padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
            {[
              { label: 'Σύνολο', value: fmtEUR(expense.total_amount), color: '#111315' },
              { label: 'Πληρώθηκε', value: fmtEUR(expense.paid_amount), color: '#1f7042' },
              { label: 'Εκκρεμεί', value: fmtEUR(expense.due_amount), color: expense.due_amount > 0 ? '#dc2626' : '#1f7042' },
            ].map(s => (
              <div key={s.label} style={{ padding: '12px 14px', borderRadius: 10, background: '#fafafa', border: '1px solid #edeff1' }}>
                <div style={{ fontSize: 11, color: '#8a9099', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5 }}>{s.label}</div>
                <div style={{ fontSize: 20, fontWeight: 700, color: s.color, fontFamily: 'monospace', marginTop: 4 }}>{s.value}</div>
              </div>
            ))}
          </div>

          {expense.contact_name && (
            <div style={{ fontSize: 13, color: '#374151' }}>
              <span style={{ fontWeight: 600 }}>Προμηθευτής:</span> {expense.contact_name}
            </div>
          )}

          {expense.due_date && (
            <div style={{ fontSize: 13, color: '#374151' }}>
              <span style={{ fontWeight: 600 }}>Ημ. λήξης:</span> {fmtDate(expense.due_date)}
            </div>
          )}

          {expense.notes && (
            <div style={{ fontSize: 13, color: '#374151', background: '#f9fafb', borderRadius: 8, padding: '10px 14px' }}>
              {expense.notes}
            </div>
          )}

          {expense.payments.length > 0 && (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Πληρωμές</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {expense.payments.map(p => (
                  <div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '8px 12px', borderRadius: 8, background: '#eef7f0', border: '1px solid #d1fae5' }}>
                    <span style={{ color: '#374151' }}>{fmtDate(p.paid_at)}{p.paid_by_name ? ` · ${p.paid_by_name}` : ''}</span>
                    <span style={{ fontWeight: 700, color: '#1f7042', fontFamily: 'monospace' }}>{fmtEUR(p.amount)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

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

export default function ExpensesPage() {
  const [statusF, setStatusF] = useState('all')
  const [categoryF, setCategoryF] = useState('all')
  const [selectedExpense, setSelectedExpense] = useState(null)

  const queryParams = {
    ...(statusF !== 'all' ? { status: statusF } : {}),
    ...(categoryF !== 'all' ? { category: categoryF } : {}),
  }

  const { data: expenses = [], isLoading, isError, refetch } = useQuery({
    queryKey: ['expenses-report', statusF, categoryF],
    queryFn: () => client.get('/api/expenses/', { params: queryParams }).then(r => r.data),
    staleTime: 30_000,
  })

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

  const allCategories = [...new Set(expenses.map(e => e.category).filter(Boolean))]
  const categoryOptions = [
    { value: 'all', label: 'Όλες οι Κατηγορίες' },
    ...allCategories.map(c => ({ value: c, label: fmtCat(c) })),
  ]
  const statusOptions = [
    { value: 'all',     label: 'Όλες Κατάσταση' },
    { value: 'due',     label: 'Εκκρεμείς' },
    { value: 'partial', label: 'Μερική Πληρωμή' },
    { value: 'paid',    label: 'Πληρωμένες' },
  ]

  const totalAmount = expenses.reduce((s, e) => s + e.total_amount, 0)
  const paidAmount  = expenses.reduce((s, e) => s + e.paid_amount, 0)
  const dueAmount   = expenses.reduce((s, e) => s + e.due_amount, 0)
  const dueCount    = expenses.filter(e => e.status !== 'paid').length

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} columns={6} /></div>
  if (isError) return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
      <div className="flex flex-1 items-center justify-center">
        <button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button>
      </div>
    </div>
  )

  return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar>
        <FilterSelect value={statusF} onChange={setStatusF} options={statusOptions} label="Κατάσταση" />
        <FilterSelect value={categoryF} onChange={setCategoryF} options={categoryOptions} label="Κατηγορία" />
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        {/* Summary stat cards */}
        <div className="grid grid-cols-4 gap-4 mb-6">
          <StatCard label="Συνολικές Δαπάνες" value={fmtEUR(totalAmount)} icon={FileText} />
          <StatCard label="Πληρωμένο" value={fmtEUR(paidAmount)} icon={CheckCircle} accent />
          <StatCard label="Εκκρεμεί" value={fmtEUR(dueAmount)} icon={AlertCircle} sub={dueCount > 0 ? `${dueCount} εκκρεμείς` : 'όλα πληρωμένα'} />
          <StatCard label="Αριθμός Δαπανών" value={String(expenses.length)} icon={Clock} />
        </div>

        <BreakdownSection expenses={expenses} summary={summary} />

        {/* Expense list */}
        <Panel title="Λίστα Δαπανών" subtitle={`${expenses.length} αποτελέσματα`} padded={false}>
          {expenses.length === 0 ? (
            <EmptyState title="Δεν βρέθηκαν δαπάνες" description="Δοκιμάστε διαφορετικά φίλτρα." />
          ) : (
            <DataTable>
              <THead>
                <TH>Περιγραφή</TH>
                <TH>Κατηγορία</TH>
                <TH>Προμηθευτής</TH>
                <TH>Σύνολο</TH>
                <TH>Εκκρεμεί</TH>
                <TH>Κατάσταση</TH>
                <TH>Ημερομηνία</TH>
              </THead>
              <tbody>
                {expenses.map(e => {
                  const meta = STATUS_META[e.status] || STATUS_META.due
                  return (
                    <TR
                      key={e.id}
                      striped
                      className="cursor-pointer hover:bg-sky-50/40"
                      onClick={() => setSelectedExpense(e)}
                    >
                      <TD className="font-medium">{e.description}</TD>
                      <TD>{fmtCat(e.category)}</TD>
                      <TD className="text-slate-500">{e.contact_name || '—'}</TD>
                      <TD mono>{fmtEUR(e.total_amount)}</TD>
                      <TD mono className={e.due_amount > 0 ? 'text-rose-600 font-semibold' : 'text-slate-400'}>
                        {e.due_amount > 0 ? fmtEUR(e.due_amount) : '—'}
                      </TD>
                      <TD>
                        <span style={{ padding: '2px 8px', borderRadius: 999, fontSize: 11, fontWeight: 700, background: meta.bg, color: meta.color }}>
                          {meta.label}
                        </span>
                      </TD>
                      <TD className="text-slate-500 text-[12px]">{fmtDate(e.created_at)}</TD>
                    </TR>
                  )
                })}
              </tbody>
            </DataTable>
          )}
        </Panel>
      </div>

      {selectedExpense && (
        <ExpenseDetailModal expense={selectedExpense} onClose={() => setSelectedExpense(null)} />
      )}
    </div>
  )
}
