import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Receipt, Download, Trash2, Plus, X, ChevronDown } from 'lucide-react'
import { toast } from 'sonner'
import {
  getInvoices, createInvoice, updateInvoiceStatus, deleteInvoice, downloadInvoicePdf,
  type Invoice, type InvoiceCreate,
} from '../api/billing'
import ConfirmModal from '../components/ConfirmModal'

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

const formatCurrency = (amount: number | null, currency = 'EUR') => {
  if (amount == null) return '—'
  return new Intl.NumberFormat('de-DE', { style: 'currency', currency }).format(amount)
}

const formatDate = (iso: string | null) =>
  iso ? new Date(iso).toLocaleDateString('de-DE') : '—'

const STATUS_COLORS: Record<string, string> = {
  draft: 'badge-gray',
  sent: 'badge-blue',
  paid: 'badge-green',
  cancelled: 'badge-red',
}

// ── New Invoice Modal ─────────────────────────────────────────────────────

function NewInvoiceModal({ onClose, onCreate }: { onClose: () => void; onCreate: (data: InvoiceCreate) => void }) {
  const [notes, setNotes] = useState('')
  const [issuedAt, setIssuedAt] = useState(new Date().toISOString().split('T')[0])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onCreate({ order_line_ids: [], notes: notes || undefined, issued_at: issuedAt || undefined })
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div
        className="rounded-xl shadow-2xl w-full max-w-md border"
        style={{ backgroundColor: 'var(--color-bg-surface)', borderColor: 'var(--color-border-default)' }}
      >
        <div
          className="px-6 py-4 border-b flex items-center justify-between"
          style={{ borderColor: 'var(--color-border-default)' }}
        >
          <h2 className="text-lg font-semibold text-content">New Invoice</h2>
          <button onClick={onClose} className="text-content-muted hover:text-content"><X size={18} /></button>
        </div>
        <form onSubmit={handleSubmit} className="px-6 py-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-content mb-1">Issue Date</label>
            <input
              type="date"
              value={issuedAt}
              onChange={e => setIssuedAt(e.target.value)}
              className="w-full px-3 py-2 text-sm border border-border-default rounded-lg focus:outline-none focus:ring-1 focus:ring-accent"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-content mb-1">Notes</label>
            <textarea
              value={notes}
              onChange={e => setNotes(e.target.value)}
              rows={3}
              placeholder="Optional notes..."
              className="w-full px-3 py-2 text-sm border border-border-default rounded-lg focus:outline-none focus:ring-1 focus:ring-accent resize-none"
            />
          </div>
          <div className="flex justify-end gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm text-content-secondary rounded-lg border border-border-default hover:bg-surface-hover transition-colors"
            >
              Cancel
            </button>
            <button type="submit" className="px-4 py-2 text-sm bg-accent text-white rounded-lg transition-colors">
              Create Invoice
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

// ── Page ──────────────────────────────────────────────────────────────────

export default function BillingPage() {
  const qc = useQueryClient()
  const [showModal, setShowModal] = useState(false)
  const [confirmState, setConfirmState] = useState<{ open: boolean; title: string; message: string; onConfirm: () => void }>({ open: false, title: '', message: '', onConfirm: () => {} })

  const { data: invoices = [], isLoading } = useQuery({
    queryKey: ['invoices'],
    queryFn: () => getInvoices(),
  })

  const createMutation = useMutation({
    mutationFn: createInvoice,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['invoices'] })
      setShowModal(false)
      toast.success('Invoice created')
    },
    onError: () => toast.error('Failed to create invoice'),
  })

  const statusMutation = useMutation({
    mutationFn: ({ id, status }: { id: string; status: string }) => updateInvoiceStatus(id, status),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['invoices'] }),
    onError: () => toast.error('Failed to update status'),
  })

  const deleteMutation = useMutation({
    mutationFn: deleteInvoice,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['invoices'] })
      toast.success('Invoice deleted')
    },
    onError: () => toast.error('Failed to delete invoice'),
  })

  // KPI aggregates
  const now = new Date()
  const currentMonth = now.getMonth()
  const currentYear = now.getFullYear()
  const monthRevenue = invoices
    .filter(inv => inv.status === 'paid' && inv.issued_at &&
      new Date(inv.issued_at).getMonth() === currentMonth &&
      new Date(inv.issued_at).getFullYear() === currentYear)
    .reduce((sum, inv) => sum + (inv.total_net ?? 0), 0)
  const openCount = invoices.filter(inv => inv.status === 'sent').length
  const paidCount = invoices.filter(inv => inv.status === 'paid').length

  return (
    <div className="p-6 space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-content flex items-center gap-2">
            <Receipt size={20} />
            Billing
          </h1>
          <p className="text-sm text-content-muted mt-0.5">Manage invoices and billing</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
        >
          <Plus size={16} />
          New Invoice
        </button>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-surface border border-border-default rounded-lg p-4">
          <p className="text-sm text-content-muted">Revenue This Month</p>
          <p className="text-2xl font-semibold text-content mt-1">{formatCurrency(monthRevenue)}</p>
        </div>
        <div className="bg-surface border border-border-default rounded-lg p-4">
          <p className="text-sm text-content-muted">Open Invoices</p>
          <p className="text-2xl font-semibold text-content mt-1">{openCount}</p>
        </div>
        <div className="bg-surface border border-border-default rounded-lg p-4">
          <p className="text-sm text-content-muted">Paid Invoices</p>
          <p className="text-2xl font-semibold text-content mt-1">{paidCount}</p>
        </div>
      </div>

      {/* Invoice Table */}
      <div className="bg-surface border border-border-default rounded-lg overflow-hidden">
        <table className="w-full text-left">
          <thead className="bg-surface-alt border-b border-border-default">
            <tr>
              <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Number</th>
              <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Status</th>
              <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Issued</th>
              <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Due</th>
              <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Net</th>
              <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Actions</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr><td colSpan={6} className="px-4 py-8 text-center text-sm text-content-muted">Loading...</td></tr>
            ) : invoices.length === 0 ? (
              <tr><td colSpan={6} className="px-4 py-8 text-center text-sm text-content-muted">No invoices yet</td></tr>
            ) : invoices.map(inv => (
              <tr key={inv.id} className="border-b border-border-default hover:bg-surface-hover transition-colors">
                <td className="px-4 py-3 text-sm font-mono text-content">{inv.invoice_number}</td>
                <td className="px-4 py-3">
                  <div className="inline-flex items-center gap-1 border border-transparent hover:border-border-default rounded-full transition-colors cursor-pointer pr-1">
                    <select
                      value={inv.status}
                      onChange={e => statusMutation.mutate({ id: inv.id, status: e.target.value })}
                      className={`text-xs px-2 py-0.5 rounded-full font-medium border-0 cursor-pointer focus:outline-none focus:ring-1 focus:ring-accent appearance-none ${STATUS_COLORS[inv.status] || 'badge-gray'}`}
                    >
                      {['draft', 'sent', 'paid', 'cancelled'].map(s => (
                        <option key={s} value={s}>{s}</option>
                      ))}
                    </select>
                    <ChevronDown size={12} className="text-content-muted pointer-events-none -ml-0.5" />
                  </div>
                </td>
                <td className="px-4 py-3 text-sm text-content-secondary">{formatDate(inv.issued_at)}</td>
                <td className="px-4 py-3 text-sm text-content-secondary">{formatDate(inv.due_at)}</td>
                <td className="px-4 py-3 text-sm text-content">{formatCurrency(inv.total_net, inv.currency)}</td>
                <td className="px-4 py-3 flex items-center gap-2">
                  <button
                    onClick={() => downloadInvoicePdf(inv.id).catch(() => toast.error('PDF download failed'))}
                    className="p-2 rounded-lg border border-border-default hover:bg-surface-hover text-content-muted hover:text-content transition-colors"
                    title="Download PDF"
                  >
                    <Download size={16} />
                  </button>
                  {inv.status === 'draft' && (
                    <button
                      onClick={() => {
                        setConfirmState({
                          open: true,
                          title: 'Delete Invoice',
                          message: `Delete draft invoice ${inv.invoice_number}?`,
                          onConfirm: () => {
                            deleteMutation.mutate(inv.id)
                            setConfirmState((s) => ({ ...s, open: false }))
                          },
                        })
                      }}
                      className="p-2 rounded-lg border border-border-default hover:bg-red-100 text-content-muted hover:text-red-600 transition-colors"
                      title="Delete draft"
                    >
                      <Trash2 size={16} />
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <NewInvoiceModal
          onClose={() => setShowModal(false)}
          onCreate={data => createMutation.mutate(data)}
        />
      )}

      <ConfirmModal
        open={confirmState.open}
        title={confirmState.title}
        message={confirmState.message}
        onConfirm={confirmState.onConfirm}
        onCancel={() => setConfirmState((s) => ({ ...s, open: false }))}
      />
    </div>
  )
}
