import { useMemo, useState } from 'react'
import { Link } from 'react-router'
import { useQueries, useQuery } from '@tanstack/react-query'
import { useTheme } from '@/hooks/useTheme'
import { apiFetch } from '@/lib/api'
import type { Client, Expense, Invoice, Staff, WorkOrder, WorkOrderDetail } from '@/lib/types'
import { WORK_ORDER_STATUS_LABEL, onTimeDeliveryStats } from '@/lib/workOrderStatus'

const STATUS_ORDER: WorkOrder['status'][] = ['quote', 'in_progress', 'completed', 'invoiced', 'cancelled']
type PeriodKey = 'month' | '30d' | '90d' | 'year'

const PERIOD_OPTIONS: { key: PeriodKey; label: string }[] = [
  { key: 'month', label: 'Mês atual' },
  { key: '30d', label: '30 dias' },
  { key: '90d', label: '90 dias' },
  { key: 'year', label: '12 meses' },
]

function currency(v: number) {
  return new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(v)
}

function monthKey(d: Date) {
  return `${d.getFullYear()}-${d.getMonth()}`
}

function getPeriodStart(period: PeriodKey, now = new Date()) {
  const start = new Date(now)
  if (period === 'month') {
    start.setDate(1)
    start.setHours(0, 0, 0, 0)
    return start
  }
  if (period === '30d') {
    start.setDate(now.getDate() - 30)
    return start
  }
  if (period === '90d') {
    start.setDate(now.getDate() - 90)
    return start
  }
  start.setMonth(now.getMonth() - 12)
  return start
}

function DashboardCard({
  title,
  value,
  subtitle,
  isLight,
}: {
  title: string
  value: string
  subtitle: string
  isLight: boolean
}) {
  return (
    <article className={`rounded-2xl border p-4 transition-colors ${isLight ? 'border-slate-300 bg-white hover:border-slate-400' : 'border-slate-700/70 bg-slate-900/65 hover:border-slate-500/80'}`}>
      <p className={`text-[11px] uppercase tracking-[0.14em] ${isLight ? 'text-slate-500' : 'text-slate-400'}`}>{title}</p>
      <p className={`mt-2 text-2xl font-semibold [font-family:'Space_Grotesk',ui-sans-serif,sans-serif] ${isLight ? 'text-slate-900' : 'text-white'}`}>
        {value}
      </p>
      <p className={`mt-1 text-xs ${isLight ? 'text-slate-600' : 'text-slate-400'}`}>{subtitle}</p>
    </article>
  )
}

export default function DashboardPage() {
  const { theme } = useTheme('ui_theme', 'dark')
  const isLight = theme === 'light'
  const [period, setPeriod] = useState<PeriodKey>('month')

  const workOrdersQ = useQuery<WorkOrder[]>({
    queryKey: ['work-orders'],
    queryFn: () => apiFetch<WorkOrder[]>('/work-orders'),
  })

  const invoicesQ = useQuery<Invoice[]>({
    queryKey: ['invoices'],
    queryFn: () => apiFetch<Invoice[]>('/invoices'),
  })

  const expensesQ = useQuery<Expense[]>({
    queryKey: ['expenses'],
    queryFn: () => apiFetch<Expense[]>('/expenses'),
  })

  const staffQ = useQuery<Staff[]>({
    queryKey: ['staff'],
    queryFn: () => apiFetch<Staff[]>('/staff'),
  })

  const clientsQ = useQuery<Client[]>({
    queryKey: ['clients'],
    queryFn: () => apiFetch<Client[]>('/clients'),
  })

  const workOrders = workOrdersQ.data ?? []
  const invoices = invoicesQ.data ?? []
  const expenses = expensesQ.data ?? []
  const staff = staffQ.data ?? []
  const clients = clientsQ.data ?? []
  const invoiceDocs = invoices.filter((doc) => doc.type === 'invoice')

  const invoiceTotalsQ = useQueries({
    queries: invoiceDocs.map((doc) => ({
      queryKey: ['work-order-detail', doc.work_order_id, 'dashboard-total'],
      queryFn: () => apiFetch<WorkOrderDetail>(`/work-orders/${doc.work_order_id}`),
      staleTime: 5 * 60 * 1000,
    })),
  })

  const isLoading = [workOrdersQ, invoicesQ, expensesQ, staffQ, clientsQ].some((q) => q.isLoading)
  const hasError = [workOrdersQ, invoicesQ, expensesQ, staffQ, clientsQ].some((q) => q.isError)
  const entriesLoading = invoiceTotalsQ.some((q) => q.isLoading)
  const entriesError = invoiceTotalsQ.some((q) => q.isError)

  const workOrderTotals = useMemo(() => {
    const totals: Record<string, number> = {}
    for (let i = 0; i < invoiceDocs.length; i++) {
      const q = invoiceTotalsQ[i]
      const doc = invoiceDocs[i]
      if (!q?.data || !doc) continue
      const items = q.data.items.reduce((sum, item) => sum + item.total, 0)
      const hours = q.data.staff_hours.reduce((sum, h) => sum + h.total, 0)
      totals[doc.work_order_id] = items + hours
    }
    return totals
  }, [invoiceDocs, invoiceTotalsQ])

  const metrics = useMemo(() => {
    const now = new Date()
    const periodStart = getPeriodStart(period, now)

    // Pipeline state (byStatus, activeOrders, awaitingInvoice, recentOrders) reflects
    // ALL work orders regardless of period — an open OT started before the period
    // window must not disappear from the dashboard just because it's "old".
    const invoicesPeriod = invoices.filter((inv) => new Date(inv.issued_at) >= periodStart)
    const expensesPeriod = expenses.filter((exp) => new Date(exp.date) >= periodStart)
    const invoicesMonth = invoices.filter((inv) => monthKey(new Date(inv.issued_at)) === monthKey(now))
    const expensesMonth = expenses.filter((exp) => monthKey(new Date(exp.date)) === monthKey(now))

    const byStatus = Object.fromEntries(STATUS_ORDER.map((s) => [s, 0])) as Record<WorkOrder['status'], number>
    for (const wo of workOrders) byStatus[wo.status] += 1

    const activeOrders = byStatus.quote + byStatus.in_progress
    const awaitingInvoice = workOrders.filter((wo) => wo.status === 'completed').length
    const periodExpenses = expensesPeriod.reduce((sum, e) => sum + e.amount, 0)
    const monthExpenses = expensesMonth.reduce((sum, e) => sum + e.amount, 0)
    const monthDocs = invoicesMonth.length
    const activeStaff = staff.filter((s) => s.active).length
    const periodEntries = invoicesPeriod
      .filter((inv) => inv.type === 'invoice')
      .reduce((sum, inv) => sum + (workOrderTotals[inv.work_order_id] ?? 0), 0)
    const monthEntries = invoicesMonth
      .filter((inv) => inv.type === 'invoice')
      .reduce((sum, inv) => sum + (workOrderTotals[inv.work_order_id] ?? 0), 0)

    const recentOrders = [...workOrders]
      .sort((a, b) => +new Date(b.updated_at) - +new Date(a.updated_at))
      .slice(0, 3)

    const recentExpenses = [...expensesPeriod]
      .sort((a, b) => +new Date(b.date) - +new Date(a.date))
      .slice(0, 3)

    const delivery = onTimeDeliveryStats(workOrders)

    return {
      byStatus,
      activeOrders,
      awaitingInvoice,
      periodExpenses,
      periodEntries,
      monthEntries,
      monthExpenses,
      monthDocs,
      activeStaff,
      recentOrders,
      recentExpenses,
      delivery,
      totalOrdersCount: workOrders.length,
      periodDocsCount: invoicesPeriod.length,
    }
  }, [period, workOrders, invoices, expenses, staff, workOrderTotals])

  const entriesVsExpensesMax = Math.max(metrics.periodEntries, metrics.periodExpenses, 1)
  const entriesBarWidth = (metrics.periodEntries / entriesVsExpensesMax) * 100
  const expensesBarWidth = (metrics.periodExpenses / entriesVsExpensesMax) * 100

  return (
    <section className="space-y-6 [font-family:'Sora',ui-sans-serif,sans-serif]">
      <header className={`relative overflow-hidden rounded-2xl border p-6 ${isLight ? 'border-slate-300 bg-gradient-to-br from-white via-slate-50 to-sky-50' : 'border-slate-700/60 bg-gradient-to-br from-slate-900 via-slate-900 to-sky-950/35'}`}>
        <div className="absolute -right-16 -top-16 h-44 w-44 rounded-full bg-cyan-600/10 blur-2xl" />
        <div className="absolute -left-12 bottom-0 h-32 w-32 rounded-full bg-amber-500/10 blur-2xl" />
        <p className={`text-xs uppercase tracking-[0.2em] ${isLight ? 'text-slate-500' : 'text-slate-400'}`}>Painel Operacional</p>
        <h1 className={`mt-1 text-3xl font-semibold [font-family:'Space_Grotesk',ui-sans-serif,sans-serif] ${isLight ? 'text-slate-900' : 'text-white'}`}>
          Dashboard da Oficina
        </h1>
        <p className={`mt-2 max-w-2xl text-sm ${isLight ? 'text-slate-600' : 'text-slate-300'}`}>
          Visão rápida do trabalho em curso, faturação e despesas para apoiar as decisões do dia.
        </p>
        <div className="mt-4 flex flex-wrap gap-2">
          {PERIOD_OPTIONS.map((opt) => (
            <button
              key={opt.key}
              onClick={() => setPeriod(opt.key)}
              className={`rounded-md border px-3 py-1.5 text-xs transition-colors ${
                period === opt.key
                  ? isLight
                    ? 'border-sky-300 bg-sky-100 text-sky-900'
                    : 'border-cyan-400/80 bg-cyan-500/20 text-cyan-100'
                  : isLight
                    ? 'border-slate-300 bg-white text-slate-700 hover:border-slate-400 hover:text-slate-900'
                    : 'border-slate-700 bg-slate-900/80 text-slate-300 hover:border-slate-500 hover:text-white'
              }`}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </header>

      {isLoading && (
        <p className={`rounded-xl border px-4 py-3 text-sm ${isLight ? 'border-slate-300 bg-white text-slate-600' : 'border-slate-700 bg-slate-900/60 text-slate-300'}`}>
          A carregar métricas do dashboard...
        </p>
      )}

      {hasError && !isLoading && (
        <p className="rounded-xl border px-4 py-3 text-sm text-[var(--ui-danger)]" style={{ borderColor: 'color-mix(in srgb, var(--ui-danger) 55%, var(--ui-border))', backgroundColor: 'color-mix(in srgb, var(--ui-danger) 12%, transparent)' }}>
          Alguns dados não foram carregados. As métricas visíveis podem estar incompletas.
        </p>
      )}

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
        <DashboardCard
          title="Orçamento + Em Progresso"
          value={String(metrics.activeOrders)}
          subtitle={`${metrics.totalOrdersCount} OTs no total`}
          isLight={isLight}
        />
        <DashboardCard
          title="Clientes"
          value={String(clients.length)}
          subtitle="Base total de clientes"
          isLight={isLight}
        />
        <DashboardCard
          title="Técnicos Ativos"
          value={`${metrics.activeStaff}/${staff.length}`}
          subtitle="Recursos disponíveis"
          isLight={isLight}
        />
        <DashboardCard
          title="Despesas do Período"
          value={currency(metrics.periodExpenses)}
          subtitle="Somatório no filtro selecionado"
          isLight={isLight}
        />
        <DashboardCard
          title="Eficiência de Entrega"
          value={metrics.delivery.rate === null ? '—' : `${metrics.delivery.rate.toFixed(0)}%`}
          subtitle={
            metrics.delivery.rate === null
              ? 'Sem OTs concluídas com prazo'
              : `${metrics.delivery.onTimeCount}/${metrics.delivery.eligibleCount} dentro do prazo`
          }
          isLight={isLight}
        />
      </div>

      <article className={`rounded-2xl border p-5 ${isLight ? 'border-slate-300 bg-white' : 'border-slate-700/70 bg-slate-900/65'}`}>
        <div className="mb-4 flex items-center justify-between">
          <h2 className={`text-base font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>Entradas Recebidas vs Despesas</h2>
          <span className={`text-xs ${isLight ? 'text-slate-500' : 'text-slate-400'}`}>
            {PERIOD_OPTIONS.find((p) => p.key === period)?.label}
          </span>
        </div>
        <div className="grid gap-4 md:grid-cols-2">
          <div className={`rounded-lg border p-3 ${isLight ? 'border-emerald-200 bg-emerald-50' : 'border-emerald-800/60 bg-emerald-950/20'}`}>
            <p className={`text-xs uppercase tracking-wide ${isLight ? 'text-emerald-700' : 'text-emerald-300'}`}>Entradas (faturas)</p>
            <p className={`mt-1 text-2xl font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>{currency(metrics.periodEntries)}</p>
          </div>
          <div className={`rounded-lg border p-3 ${isLight ? 'border-rose-200 bg-rose-50' : 'border-rose-800/60 bg-rose-950/20'}`}>
            <p className={`text-xs uppercase tracking-wide ${isLight ? 'text-rose-700' : 'text-rose-300'}`}>Despesas</p>
            <p className={`mt-1 text-2xl font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>{currency(metrics.periodExpenses)}</p>
          </div>
        </div>
        <div className="mt-4 space-y-3">
          <div>
            <div className="mb-1 flex justify-between text-xs">
              <span className={isLight ? 'text-slate-700' : 'text-slate-300'}>Entradas recebidas</span>
              <span className={`font-mono ${isLight ? 'text-emerald-700' : 'text-emerald-300'}`}>{currency(metrics.periodEntries)}</span>
            </div>
            <div className={`h-3 rounded-full ${isLight ? 'bg-slate-200' : 'bg-slate-800'}`}>
              <div className="h-3 rounded-full bg-gradient-to-r from-emerald-500 to-teal-400" style={{ width: `${entriesBarWidth}%` }} />
            </div>
          </div>
          <div>
            <div className="mb-1 flex justify-between text-xs">
              <span className={isLight ? 'text-slate-700' : 'text-slate-300'}>Despesas registadas</span>
              <span className={`font-mono ${isLight ? 'text-rose-700' : 'text-rose-300'}`}>{currency(metrics.periodExpenses)}</span>
            </div>
            <div className={`h-3 rounded-full ${isLight ? 'bg-slate-200' : 'bg-slate-800'}`}>
              <div className="h-3 rounded-full bg-gradient-to-r from-rose-500 to-orange-400" style={{ width: `${expensesBarWidth}%` }} />
            </div>
          </div>
        </div>
        <p className={`mt-4 text-sm ${isLight ? 'text-slate-700' : 'text-slate-300'}`}>
          Saldo estimado: <span className={metrics.periodEntries - metrics.periodExpenses >= 0 ? (isLight ? 'text-emerald-700' : 'text-emerald-300') : (isLight ? 'text-rose-700' : 'text-rose-300')}>
            {currency(metrics.periodEntries - metrics.periodExpenses)}
          </span>
        </p>
        {(entriesLoading || entriesError) && (
          <p className={`mt-2 text-xs ${isLight ? 'text-slate-500' : 'text-slate-400'}`}>
            {entriesLoading ? 'A calcular totais de entradas...' : 'Algumas entradas não puderam ser calculadas.'}
          </p>
        )}
      </article>

      <div className="grid items-stretch gap-4 xl:grid-cols-2">
        <article className={`h-full rounded-2xl border p-6 ${isLight ? 'border-slate-300 bg-white' : 'border-slate-700/70 bg-slate-900/65'}`}>
          <div className="mb-6 flex items-center justify-between">
            <h2 className={`text-base font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>Fluxo das Ordens de Trabalho</h2>
            <Link to="/app/work-orders" className={`text-xs ${isLight ? 'text-sky-700 hover:text-sky-800' : 'text-cyan-300 hover:text-cyan-200'}`}>
              Ver todas
            </Link>
          </div>
          <div className="space-y-5">
            {STATUS_ORDER.map((status) => {
              const count = metrics.byStatus[status]
              const total = Math.max(metrics.totalOrdersCount, 1)
              const width = Math.max((count / total) * 100, count > 0 ? 6 : 0)
              return (
                <div key={status}>
                  <div className="mb-1.5 flex justify-between text-xs">
                    <span className={isLight ? 'text-slate-700' : 'text-slate-300'}>{WORK_ORDER_STATUS_LABEL[status]}</span>
                    <span className={`font-mono ${isLight ? 'text-slate-500' : 'text-slate-400'}`}>{count}</span>
                  </div>
                  <div className={`h-2 rounded-full ${isLight ? 'bg-slate-200' : 'bg-slate-800'}`}>
                    <div className="h-2 rounded-full bg-gradient-to-r from-cyan-500 to-emerald-500" style={{ width: `${width}%` }} />
                  </div>
                </div>
              )
            })}
          </div>
        </article>

        <article className={`h-full rounded-2xl border p-6 ${isLight ? 'border-slate-300 bg-white' : 'border-slate-700/70 bg-slate-900/65'}`}>
          <h2 className={`text-base font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>Faturação e Prioridades</h2>
          <div className="mt-5 space-y-3 text-sm">
            <div className={`rounded-lg border px-3 py-2 ${isLight ? 'border-slate-200 bg-slate-100' : 'border-slate-700 bg-slate-900/70'}`}>
              <p className={isLight ? 'text-slate-600' : 'text-slate-400'}>Documentos emitidos no período</p>
              <p className={`text-xl font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>{metrics.periodDocsCount}</p>
            </div>
            <div
              className="rounded-lg border px-3 py-2"
              style={{
                borderColor: 'color-mix(in srgb, var(--ui-warning) 55%, var(--ui-border))',
                backgroundColor: 'color-mix(in srgb, var(--ui-warning) 12%, transparent)',
                color: 'var(--ui-warning)',
              }}
            >
              <p className="text-xs uppercase tracking-wide">Ação recomendada</p>
              <p className="mt-1">
                {metrics.awaitingInvoice > 0
                  ? `${metrics.awaitingInvoice} OT(s) em "Concluída" pronta(s) para faturar.`
                  : 'Sem OTs finalizadas pendentes de emissão de fatura.'}
              </p>
            </div>
            <div className={`rounded-lg border px-3 py-2 ${isLight ? 'border-cyan-200 bg-cyan-50 text-cyan-900' : 'border-cyan-900/70 bg-cyan-950/25 text-cyan-100'}`}>
              <p className="text-xs uppercase tracking-wide">Em orçamento</p>
              <p className="mt-1">
                {metrics.byStatus.quote > 0
                  ? `${metrics.byStatus.quote} OT(s) em "Orçamento" prontas para "Em Progresso".`
                  : 'Não existem OTs pendentes em orçamento.'}
              </p>
            </div>
            <div className={`rounded-lg border px-3 py-2 ${isLight ? 'border-slate-200 bg-slate-100' : 'border-slate-700 bg-slate-900/70'}`}>
              <p className={isLight ? 'text-slate-600' : 'text-slate-400'}>Contexto mensal</p>
              <p className={`mt-1 text-xs ${isLight ? 'text-slate-700' : 'text-slate-200'}`}>
                Entradas no mês: {currency(metrics.monthEntries)} | Despesas no mês: {currency(metrics.monthExpenses)} | Documentos: {metrics.monthDocs}
              </p>
            </div>
          </div>
        </article>
      </div>

      <div className="grid gap-4 xl:grid-cols-2">
        <article className={`rounded-2xl border p-5 ${isLight ? 'border-slate-300 bg-white' : 'border-slate-700/70 bg-slate-900/65'}`}>
          <div className="mb-3 flex items-center justify-between">
            <h2 className={`text-base font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>Atividade Recente de OTs</h2>
            <Link to="/app/work-orders" className={`text-xs ${isLight ? 'text-sky-700 hover:text-sky-800' : 'text-cyan-300 hover:text-cyan-200'}`}>
              Mostrar tudo →
            </Link>
          </div>
          {metrics.recentOrders.length === 0 ? (
            <p className={`text-sm ${isLight ? 'text-slate-600' : 'text-slate-400'}`}>Ainda não existem ordens de trabalho.</p>
          ) : (
            <ul className={`divide-y ${isLight ? 'divide-slate-200' : 'divide-slate-800'}`}>
              {metrics.recentOrders.map((wo) => (
                <li key={wo.id} className="flex items-center justify-between py-2">
                  <div>
                    <p className={`text-sm font-medium ${isLight ? 'text-slate-900' : 'text-white'}`}>OT #{wo.number}</p>
                    <p className={`text-xs ${isLight ? 'text-slate-600' : 'text-slate-400'}`}>{WORK_ORDER_STATUS_LABEL[wo.status]}</p>
                  </div>
                  <span className={`text-xs ${isLight ? 'text-slate-500' : 'text-slate-500'}`}>
                    {new Intl.DateTimeFormat('pt-PT', { dateStyle: 'short', timeStyle: 'short' }).format(new Date(wo.updated_at))}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </article>

        <article className={`rounded-2xl border p-5 ${isLight ? 'border-slate-300 bg-white' : 'border-slate-700/70 bg-slate-900/65'}`}>
          <div className="mb-3 flex items-center justify-between">
            <h2 className={`text-base font-semibold ${isLight ? 'text-slate-900' : 'text-white'}`}>Despesas Recentes</h2>
            <Link to="/app/expenses" className={`text-xs ${isLight ? 'text-sky-700 hover:text-sky-800' : 'text-cyan-300 hover:text-cyan-200'}`}>
              Mostrar tudo →
            </Link>
          </div>
          {metrics.recentExpenses.length === 0 ? (
            <p className={`text-sm ${isLight ? 'text-slate-600' : 'text-slate-400'}`}>Sem despesas no período selecionado.</p>
          ) : (
            <ul className={`divide-y ${isLight ? 'divide-slate-200' : 'divide-slate-800'}`}>
              {metrics.recentExpenses.map((exp) => (
                <li key={exp.id} className="flex items-center justify-between py-2">
                  <div>
                    <p className={`text-sm font-medium ${isLight ? 'text-slate-900' : 'text-white'}`}>
                      {currency(exp.amount)}
                    </p>
                    <p className={`text-xs ${isLight ? 'text-slate-600' : 'text-slate-400'}`}>
                      {exp.type === 'fuel' ? 'Combustível' : exp.type === 'parts' ? 'Peças' : exp.type === 'tools' ? 'Ferramentas' : 'Outros'}
                      {exp.description ? ` · ${exp.description}` : ''}
                    </p>
                  </div>
                  <span className={`text-xs ${isLight ? 'text-slate-500' : 'text-slate-500'}`}>
                    {new Intl.DateTimeFormat('pt-PT', { dateStyle: 'short' }).format(new Date(exp.date))}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </article>
      </div>
    </section>
  )
}
