import { formatMoney } from "@/lib/format";
import {
  formatProfitRate,
  resolveProfitRateFromRecord,
} from "@/lib/profitRate";

export interface EarningsKpis {
  profit_rate?: number | string;
  profit_share_percent?: number;
  avg_daily_profit_30d: number;
  profit_this_month: {
    value: number;
    label: string;
    change: {
      formatted: string;
      trend: "up" | "down";
      label: string;
    };
  };
  total_profit: number;
}

interface StatView {
  icon: string;
  label: string;
  value: string;
  sub: string;
  subColor: string;
}

export default function EarningsSummary({
  kpis,
  currency,
}: Readonly<{
  kpis: EarningsKpis;
  currency: string;
}>) {
  const { trend, formatted, label: changeLabel } = kpis.profit_this_month.change;
  const trendColor = trend === "up" ? "text-[#FCD704]" : "text-red-400";
  const trendArrow = trend === "up" ? "↑" : "↓";

  const profitRate = resolveProfitRateFromRecord(
    kpis as unknown as Record<string, unknown>,
  );

  const stats: StatView[] = [
    {
      icon: "ri-money-dollar-circle-line",
      label: "إجمالي الأرباح",
      value: formatMoney(kpis.total_profit, currency),
      sub: "منذ بداية الاستثمار",
      subColor: "text-gray-400",
    },
    {
      icon: "ri-calendar-check-line",
      label: kpis.profit_this_month.label,
      value: formatMoney(kpis.profit_this_month.value, currency),
      sub: `${formatted} ${changeLabel} ${trendArrow}`,
      subColor: trendColor,
    },
    {
      icon: "ri-bar-chart-grouped-line",
      label: "متوسط الربح اليومي",
      value: formatMoney(kpis.avg_daily_profit_30d, currency),
      sub: "آخر 30 يوم",
      subColor: "text-gray-400",
    },
    {
      icon: "ri-pie-chart-2-line",
      label: "نسبة الأرباح",
      value: formatProfitRate(profitRate),
      sub: "من إجمالي إيرادات مركباتك",
      subColor: "text-gray-400",
    },
  ];

  return (
    <div className="grid grid-cols-4 gap-5 mb-6">
      {stats.map((s) => (
        <div key={s.label} className="bg-[#1E2128] rounded-2xl p-5">
          <div className="w-10 h-10 bg-[#FCD704]/15 rounded-xl flex items-center justify-center mb-4">
            <i className={`${s.icon} text-[#FCD704] text-xl`} />
          </div>
          <p className="text-white font-black text-2xl">{s.value}</p>
          <p className="text-gray-400 text-xs mt-1">{s.label}</p>
          <p className={`text-xs mt-1 ${s.subColor}`}>{s.sub}</p>
        </div>
      ))}
    </div>
  );
}
