export const dynamic = 'force-dynamic'

import { prisma } from '@/lib/prisma'
import LogoutButton from './LogoutButton'
import StatusSelect from './StatusSelect'

type LeadRow = {
  id: string
  createdAt: Date
  name: string
  email: string
  company: string | null
  sector: string | null
  budget: number
  complexity: string
  status: string
  devisNumber: string | null
}

export default async function AdminLeadsPage() {
  const leads: LeadRow[] = await prisma.lead.findMany({
    orderBy: { createdAt: 'desc' },
    take: 200,
  })

  const totalLeads = leads.length
  const totalBudget = leads.reduce((sum: number, l: LeadRow) => sum + l.budget, 0)
  const avgBudget = totalLeads ? Math.round(totalBudget / totalLeads) : 0
  const wonCount = leads.filter((l: LeadRow) => l.status === 'WON').length
  const qualifiedCount = leads.filter((l: LeadRow) => l.status === 'QUALIFIED').length

  return (
    <main className="min-h-screen bg-background px-4 py-10 lg:px-8">
      <div className="mx-auto max-w-6xl">
        <div className="mb-8 flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold">CRM — Leads configurateur</h1>
            <p className="text-muted-foreground">
              Chaque fiche est déjà pré-remplie : secteur, budget, modules recommandés.
            </p>
          </div>
          <LogoutButton />
        </div>

        {/* KPIs */}
        <div className="mb-8 grid grid-cols-2 gap-4 sm:grid-cols-4">
          <Kpi label="Leads reçus" value={totalLeads} />
          <Kpi label="Budget moyen" value={`${avgBudget.toLocaleString('fr-FR')} €`} />
          <Kpi label="Qualifiés" value={qualifiedCount} />
          <Kpi label="Gagnés" value={wonCount} />
        </div>

        {/* Pipeline */}
        <div className="overflow-x-auto rounded-2xl border border-border bg-card">
          <table className="w-full text-left text-sm">
            <thead>
              <tr className="border-b border-border text-xs uppercase text-muted-foreground">
                <th className="px-4 py-3">Date</th>
                <th className="px-4 py-3">Contact</th>
                <th className="px-4 py-3">Secteur</th>
                <th className="px-4 py-3">Budget</th>
                <th className="px-4 py-3">Complexité</th>
                <th className="px-4 py-3">Statut</th>
                <th className="px-4 py-3">Étude</th>
                <th className="px-4 py-3">Devis</th>
              </tr>
            </thead>
            <tbody>
              {leads.map((lead: LeadRow) => (
                <tr key={lead.id} className="border-b border-border/60">
                  <td className="px-4 py-3 text-muted-foreground">
                    {lead.createdAt.toLocaleDateString('fr-FR')}
                  </td>
                  <td className="px-4 py-3">
                    <div className="font-medium">{lead.name}</div>
                    <div className="text-xs text-muted-foreground">{lead.email}</div>
                    {lead.company && <div className="text-xs text-muted-foreground">{lead.company}</div>}
                  </td>
                  <td className="px-4 py-3">{lead.sector || '—'}</td>
                  <td className="px-4 py-3">{lead.budget.toLocaleString('fr-FR')} €</td>
                  <td className="px-4 py-3">{lead.complexity}</td>
                  <td className="px-4 py-3">
                    <StatusSelect leadId={lead.id} initialStatus={lead.status} />
                  </td>
                  <td className="px-4 py-3">
                    <a
                      href={`/api/leads/${lead.id}/pdf`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-primary hover:underline"
                    >
                      Voir le PDF
                    </a>
                  </td>
                  <td className="px-4 py-3">
                    <a
                      href={`/api/leads/${lead.id}/devis`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-primary hover:underline"
                    >
                      {lead.devisNumber ? lead.devisNumber : 'Générer le devis'}
                    </a>
                  </td>
                </tr>
              ))}
              {leads.length === 0 && (
                <tr>
                  <td colSpan={8} className="px-4 py-8 text-center text-muted-foreground">
                    Aucun lead pour l&apos;instant.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </main>
  )
}

function Kpi({ label, value }: { label: string; value: string | number }) {
  return (
    <div className="rounded-2xl border border-border bg-card p-4 text-center">
      <p className="text-2xl font-bold">{value}</p>
      <p className="mt-1 text-xs text-muted-foreground">{label}</p>
    </div>
  )
}
