"use client"

import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import { RefreshCw, TrendingUp, Wallet, BadgePercent, FolderKanban, AlertTriangle } from "lucide-react"
import {
  ResponsiveContainer,
  PieChart, Pie, Cell,
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
  BarChart, Bar,
  Legend,
} from "recharts"
import { getTenantStats, type TenantStats } from "@/src/lib/api/stats"

const NAVY = "#1a3578"
const TEAL = "#4dba96"

const STATUS_COLORS: Record<string, string> = {
  new:        "#94a3b8",
  in_review:  "#60a5fa",
  preventive: "#38bdf8",
  amicable:   TEAL,
  pre_legal:  "#facc15",
  legal:      "#f97316",
  disputed:   "#f87171",
  settled:    "#34d399",
  closed:     NAVY,
  write_off:  "#475569",
}

const METHOD_COLORS: Record<string, string> = {
  cash:          "#4ade80",
  bank_transfer: NAVY,
  mobile_money:  TEAL,
  cheque:        "#f97316",
  card:          "#a78bfa",
  other:         "#94a3b8",
}

function fmt(n: number) {
  return new Intl.NumberFormat("fr-FR", { maximumFractionDigits: 0 }).format(n)
}

function KpiCard({
  icon: Icon, label, value, sub, color,
}: {
  icon: React.ElementType
  label: string
  value: string
  sub?: string
  color?: string
}) {
  return (
    <div className="rounded-2xl border bg-card p-5 flex items-start gap-4">
      <div className="h-10 w-10 rounded-xl flex items-center justify-center shrink-0" style={{ background: `${color || NAVY}18` }}>
        <Icon className="h-5 w-5" style={{ color: color || NAVY }} />
      </div>
      <div className="min-w-0">
        <p className="text-xs text-muted-foreground leading-tight">{label}</p>
        <p className="text-2xl font-bold tracking-tight mt-0.5">{value}</p>
        {sub && <p className="text-xs text-muted-foreground mt-0.5">{sub}</p>}
      </div>
    </div>
  )
}

function ChartCard({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="rounded-2xl border bg-card p-5">
      <p className="text-sm font-semibold mb-4">{title}</p>
      {children}
    </div>
  )
}

export default function ReportsPage() {
  const t = useTranslations("reports")
  const [stats, setStats] = useState<TenantStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  async function load(silent = false) {
    if (!silent) setLoading(true)
    setError(null)
    try {
      setStats(await getTenantStats())
    } catch (e: any) {
      setError(e?.message ?? "Erreur")
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { load() }, [])

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold">{t("title")}</h1>
          <p className="text-sm text-muted-foreground">{t("subtitle")}</p>
        </div>
        <button
          onClick={() => load(true)}
          disabled={loading}
          className="rounded-lg p-2 text-muted-foreground hover:bg-muted transition-colors"
        >
          <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
        </button>
      </div>

      {error && (
        <div className="rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive">
          {error}
        </div>
      )}

      {loading && !stats ? (
        <p className="text-sm text-muted-foreground py-10 text-center">{t("loading")}</p>
      ) : stats ? (
        <>
          {/* KPI Cards */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <KpiCard
              icon={FolderKanban}
              label={t("kpi_total_cases")}
              value={fmt(stats.cases.total)}
              sub={`${stats.cases.overdue} ${t("kpi_overdue")}`}
              color={NAVY}
            />
            <KpiCard
              icon={Wallet}
              label={t("kpi_total_amount")}
              value={fmt(stats.cases.total_amount)}
              color="#6366f1"
            />
            <KpiCard
              icon={TrendingUp}
              label={t("kpi_recovered")}
              value={fmt(stats.cases.total_paid)}
              color={TEAL}
            />
            <KpiCard
              icon={BadgePercent}
              label={t("kpi_recovery_rate")}
              value={`${stats.cases.recovery_rate} %`}
              color={stats.cases.recovery_rate >= 50 ? TEAL : "#f97316"}
            />
          </div>

          {/* Charts row 1 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* Dossiers par statut */}
            <ChartCard title={t("chart_by_status")}>
              {stats.cases.by_status.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">{t("no_data")}</p>
              ) : (
                <ResponsiveContainer width="100%" height={240}>
                  <PieChart>
                    <Pie
                      data={stats.cases.by_status.map((s) => ({ name: t(`status_${s.status}` as any), value: s.count, key: s.status }))}
                      dataKey="value"
                      nameKey="name"
                      cx="50%"
                      cy="50%"
                      innerRadius={55}
                      outerRadius={90}
                      paddingAngle={2}
                    >
                      {stats.cases.by_status.map((s) => (
                        <Cell key={s.status} fill={STATUS_COLORS[s.status] ?? "#94a3b8"} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(v: number | undefined) => [v ?? 0, t("kpi_total_cases")]} />
                    <Legend iconSize={10} iconType="circle" />
                  </PieChart>
                </ResponsiveContainer>
              )}
            </ChartCard>

            {/* Tendance mensuelle */}
            <ChartCard title={t("chart_monthly")}>
              {stats.payments.monthly_trend.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">{t("no_data")}</p>
              ) : (
                <ResponsiveContainer width="100%" height={240}>
                  <AreaChart data={stats.payments.monthly_trend} margin={{ top: 4, right: 8, left: 0, bottom: 0 }}>
                    <defs>
                      <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor={TEAL} stopOpacity={0.25} />
                        <stop offset="95%" stopColor={TEAL} stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                    <XAxis dataKey="month" tick={{ fontSize: 11 }} />
                    <YAxis tick={{ fontSize: 11 }} width={56} tickFormatter={(v) => fmt(v)} />
                    <Tooltip formatter={(v: number | undefined) => [fmt(v ?? 0), t("amount_label")]} />
                    <Area type="monotone" dataKey="amount" stroke={TEAL} strokeWidth={2} fill="url(#areaGrad)" />
                  </AreaChart>
                </ResponsiveContainer>
              )}
            </ChartCard>
          </div>

          {/* Charts row 2 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* Actions par type */}
            <ChartCard title={t("chart_actions")}>
              {stats.actions.by_type.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">{t("no_data")}</p>
              ) : (
                <ResponsiveContainer width="100%" height={220}>
                  <BarChart
                    data={stats.actions.by_type.map((a) => ({ name: t(`action_${a.type}` as any), count: a.count }))}
                    layout="vertical"
                    margin={{ top: 0, right: 16, left: 8, bottom: 0 }}
                  >
                    <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#e5e7eb" />
                    <XAxis type="number" tick={{ fontSize: 11 }} />
                    <YAxis type="category" dataKey="name" tick={{ fontSize: 11 }} width={90} />
                    <Tooltip />
                    <Bar dataKey="count" fill={NAVY} radius={[0, 4, 4, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              )}
            </ChartCard>

            {/* Méthodes de paiement */}
            <ChartCard title={t("chart_methods")}>
              {stats.payments.by_method.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">{t("no_data")}</p>
              ) : (
                <ResponsiveContainer width="100%" height={220}>
                  <PieChart>
                    <Pie
                      data={stats.payments.by_method.map((m) => ({ name: t(`method_${m.method}` as any), value: m.count, key: m.method }))}
                      dataKey="value"
                      nameKey="name"
                      cx="50%"
                      cy="50%"
                      outerRadius={85}
                      paddingAngle={2}
                    >
                      {stats.payments.by_method.map((m) => (
                        <Cell key={m.method} fill={METHOD_COLORS[m.method] ?? "#94a3b8"} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend iconSize={10} iconType="circle" />
                  </PieChart>
                </ResponsiveContainer>
              )}
            </ChartCard>
          </div>

          {/* Promesses de paiement */}
          <ChartCard title={t("chart_promises")}>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              {(["pending", "kept", "broken", "cancelled"] as const).map((key) => {
                const colors = { pending: "#facc15", kept: TEAL, broken: "#f87171", cancelled: "#94a3b8" }
                return (
                  <div key={key} className="rounded-xl border p-4 text-center">
                    <p className="text-2xl font-bold" style={{ color: colors[key] }}>{stats.promises[key]}</p>
                    <p className="text-xs text-muted-foreground mt-1">{t(`promises_${key}`)}</p>
                  </div>
                )
              })}
            </div>
          </ChartCard>
        </>
      ) : null}
    </div>
  )
}
