import { useQuery } from '@tanstack/react-query'
import { DollarSign, FileText } from 'lucide-react'
import api from '../../../api/client'
import { useAuthStore } from '../../../store/auth'

interface Invoice {
  id: string
  amount: number
  status: string
  created_at: string
}

interface InvoiceListResponse {
  items: Invoice[]
  total: number
}

function Skeleton() {
  return (
    <div className="animate-pulse space-y-3">
      <div className="h-12 rounded-lg bg-surface-muted" />
      <div className="h-8 rounded bg-surface-muted" />
    </div>
  )
}

export default function CostOverviewWidget() {
  const user = useAuthStore((s) => s.user)
  const isPrivileged =
    user?.role === 'admin' || user?.role === 'project_manager'

  const { data, isLoading, error } = useQuery<Invoice[]>({
    queryKey: ['invoices-widget'],
    queryFn: async () => {
      try {
        const res = await api.get<InvoiceListResponse>('/billing/invoices', {
          params: { limit: 50 },
        })
        return res.data?.items ?? []
      } catch {
        return []
      }
    },
    enabled: isPrivileged,
    staleTime: 120_000,
    retry: 1,
  })

  if (!isPrivileged) {
    return (
      <p className="text-xs text-content-muted text-center py-4">
        Available for admin and project managers only.
      </p>
    )
  }

  if (isLoading) return <Skeleton />
  if (error) {
    return <p className="text-xs text-red-500">Failed to load invoices</p>
  }

  const invoices = data ?? []

  const now = new Date()
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
  const thisMonthTotal = invoices
    .filter((inv) => new Date(inv.created_at) >= monthStart)
    .reduce((sum, inv) => sum + (inv.amount ?? 0), 0)

  const openCount = invoices.filter(
    (inv) => inv.status === 'open' || inv.status === 'pending'
  ).length

  return (
    <div className="space-y-3">
      {/* This month */}
      <div
        className="flex items-center gap-3 rounded-lg border border-border-default p-3"
        style={{ backgroundColor: 'var(--color-bg-surface)' }}
      >
        <DollarSign size={18} className="text-green-500 shrink-0" />
        <div>
          <p className="text-xs text-content-muted">This month</p>
          <p className="text-xl font-bold text-content">
            € {thisMonthTotal.toFixed(2)}
          </p>
        </div>
      </div>

      {/* Open invoices */}
      <div
        className="flex items-center gap-3 rounded-lg border border-border-default p-3"
        style={{ backgroundColor: 'var(--color-bg-surface)' }}
      >
        <FileText
          size={16}
          className={openCount > 0 ? 'text-amber-500' : 'text-content-muted'}
        />
        <div>
          <p className="text-xs text-content-muted">Open invoices</p>
          <p className="text-base font-semibold text-content">{openCount}</p>
        </div>
      </div>
    </div>
  )
}
