"use client";

import React, { useMemo } from "react";
import {
  FileText,
  Calendar,
  AlertTriangle,
  CheckCircle2,
  TrendingUp,
  Filter,
} from "lucide-react";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { resolveReceiptStatusTier } from "./StatusBadge";
import { useI18n } from "@/lib/i18n/context";
import { isDateInPeriod, DateRange } from "@/lib/hooks/useReceiptFilters";
import { taxTotalsByRate } from "./receiptFormat";

export interface DashboardKPIMetrics {
  totalScanned: number;
  /** Bruttosumme der Rechnungsbetraege — MwSt-tragend, OHNE Trinkgeld. */
  totalGross: number;
  totalNet: number;
  /** Summe aller Trinkgelder. Traegt keine MwSt, daher separat von totalGross. */
  totalTips: number;
  /** Tatsaechlich gezahlt: totalGross + totalTips. */
  totalPaid: number;

  /** Werte für den ausgewählten Zeitraum (bzw. laufenden Monat) */
  periodSpend: number;
  periodSpendNet: number;
  periodSpendTips: number;
  periodSpendPaid: number;
  periodReceiptsCount: number;
  periodVat19: number;
  periodVat7: number;

  /** Alias-Felder für Rückwärtskompatibilität */
  monthlySpend: number;
  monthlySpendNet: number;
  monthlySpendTips: number;
  monthlySpendPaid: number;
  monthlyReceiptsCount: number;

  pendingReviewsCount: number;
  confirmedCount: number;
  averageAccuracy: number;
  accuracyTier: "optimal" | "high" | "medium" | "low";
  totalVat19: number;
  totalVat7: number;
}

/** Helper to calculate net amount safely */
function netOfReceipt(r: ProcessedReceipt): number {
  if (r.netAmount != null && !isNaN(r.netAmount)) {
    return r.netAmount;
  }
  const taxSum = (r.taxBreakdown || []).reduce((s, tx) => s + (tx.taxAmount || 0), 0);
  const gross = r.totalAmount?.value || 0;
  return Math.max(0, gross - taxSum);
}

/**
 * Deterministically computes comprehensive dashboard KPI metrics
 * from the loaded receipts dataset with zero synthetic or mock dependencies.
 */
export function calculateDashboardKPIs(
  receipts: ProcessedReceipt[] = [],
  activePeriod: string = "month",
  customRange?: DateRange
): DashboardKPIMetrics {
  const totalScanned = receipts.length;

  const totalGross = receipts.reduce(
    (acc, curr) => acc + (curr.totalAmount?.value || 0),
    0
  );
  const totalNet = receipts.reduce((acc, curr) => acc + netOfReceipt(curr), 0);
  const totalTips = receipts.reduce((acc, curr) => acc + (curr.tipAmount || 0), 0);
  const totalPaid = totalGross + totalTips;

  const totalVat19 = receipts.reduce((acc, curr) => {
    const item = curr.taxBreakdown?.find((t) => t.ratePercent === 19);
    return acc + (item?.taxAmount || 0);
  }, 0);

  const totalVat7 = receipts.reduce((acc, curr) => {
    const item = curr.taxBreakdown?.find((t) => t.ratePercent === 7);
    return acc + (item?.taxAmount || 0);
  }, 0);

  // Period / Month spend calculation
  const targetPeriod = activePeriod && activePeriod !== "all" ? activePeriod : "month";
  const periodReceipts = receipts.filter((r) =>
    isDateInPeriod(r.date?.isoDate, targetPeriod, customRange)
  );

  const periodSpend = periodReceipts.reduce(
    (acc, curr) => acc + (curr.totalAmount?.value || 0),
    0
  );
  const periodSpendNet = periodReceipts.reduce(
    (acc, curr) => acc + netOfReceipt(curr),
    0
  );
  const periodSpendTips = periodReceipts.reduce(
    (acc, curr) => acc + (curr.tipAmount || 0),
    0
  );
  const periodSpendPaid = periodSpend + periodSpendTips;
  const periodReceiptsCount = periodReceipts.length;

  const periodVat19 = periodReceipts.reduce((acc, curr) => {
    const item = curr.taxBreakdown?.find((t) => t.ratePercent === 19);
    return acc + (item?.taxAmount || 0);
  }, 0);

  const periodVat7 = periodReceipts.reduce((acc, curr) => {
    const item = curr.taxBreakdown?.find((t) => t.ratePercent === 7);
    return acc + (item?.taxAmount || 0);
  }, 0);

  // Pending reviews: Needs attention or math discrepancy and not yet confirmed
  const pendingReceipts = receipts.filter((r) => {
    const tier = resolveReceiptStatusTier(r);
    return tier === "pending_review";
  });
  const pendingReviewsCount = pendingReceipts.length;

  const confirmedReceipts = receipts.filter((r) => {
    const tier = resolveReceiptStatusTier(r);
    return tier === "confirmed";
  });
  const confirmedCount = confirmedReceipts.length;

  // Dynamic Average Accuracy calculation
  let averageAccuracy = 99.8;
  if (totalScanned > 0) {
    const totalScore = receipts.reduce((acc, r) => {
      const confTotal = r.totalAmount?.confidence ?? 0.98;
      const confMerchant = r.merchant?.confidence ?? 0.95;
      const confDate = r.date?.confidence ?? 0.95;

      const baseScore = confTotal * 0.4 + confMerchant * 0.3 + confDate * 0.3;

      let adjustedScore = baseScore;
      if (r.validation?.userConfirmed) {
        adjustedScore = 1.0;
      } else if (r.validation?.isMathValid === false) {
        adjustedScore = Math.max(0.65, baseScore - 0.1);
      } else if (r.validation?.needsUserReview) {
        adjustedScore = Math.max(0.75, baseScore - 0.05);
      }

      return acc + Math.min(1.0, Math.max(0.5, adjustedScore));
    }, 0);

    const rawAverage = (totalScore / totalScanned) * 100;
    averageAccuracy = Math.round(rawAverage * 10) / 10;
  }

  let accuracyTier: "optimal" | "high" | "medium" | "low" = "optimal";
  if (averageAccuracy >= 98.0) {
    accuracyTier = "optimal";
  } else if (averageAccuracy >= 92.0) {
    accuracyTier = "high";
  } else if (averageAccuracy >= 80.0) {
    accuracyTier = "medium";
  } else {
    accuracyTier = "low";
  }

  return {
    totalScanned,
    totalGross,
    totalNet,
    totalTips,
    totalPaid,
    periodSpend,
    periodSpendNet,
    periodSpendTips,
    periodSpendPaid,
    periodReceiptsCount,
    periodVat19,
    periodVat7,
    monthlySpend: periodSpend,
    monthlySpendNet: periodSpendNet,
    monthlySpendTips: periodSpendTips,
    monthlySpendPaid: periodSpendPaid,
    monthlyReceiptsCount: periodReceiptsCount,
    pendingReviewsCount,
    confirmedCount,
    averageAccuracy,
    accuracyTier,
    totalVat19,
    totalVat7,
  };
}

export interface KPICardsProps {
  receipts: ProcessedReceipt[];
  activePeriod?: string;
  customDateRange?: DateRange;
  activeStatus?: string;
  onFilterPeriod?: (period: string) => void;
  onFilterStatus?: (status: string) => void;
  onResetFilters?: () => void;
}

export function KPICards({
  receipts,
  activePeriod = "all",
  customDateRange,
  activeStatus,
  onFilterPeriod,
  onFilterStatus,
  onResetFilters,
}: KPICardsProps) {
  const { language } = useI18n();
  const isDe = language === "de";

  const metrics = useMemo(
    () => calculateDashboardKPIs(receipts, activePeriod, customDateRange),
    [receipts, activePeriod, customDateRange]
  );

  const isPendingFilterActive =
    activeStatus === "pending" || activeStatus === "pending_review" || activeStatus === "pruefen";
  const isPeriodFilterActive = activePeriod !== "all";

  const vatBreakdownLabel = useMemo(() => {
    const targetPeriod = activePeriod && activePeriod !== "all" ? activePeriod : "month";
    const periodReceipts = receipts.filter((r) =>
      isDateInPeriod(r.date?.isoDate, targetPeriod, customDateRange)
    );
    const rows = taxTotalsByRate(periodReceipts);
    if (rows.length === 0) return isDe ? "Keine MwSt erfasst" : "No VAT captured";
    return rows
      .map(
        (row) =>
          `${Number.isInteger(row.rate) ? row.rate : row.rate.toFixed(1)}%: ${row.amount.toFixed(2)} €`
      )
      .join(" • ");
  }, [receipts, activePeriod, customDateRange, isDe]);

  // Dynamic Title for Card 2
  const getPeriodCardTitle = () => {
    switch (activePeriod) {
      case "last_30_days":
        return isDe ? "AUSGABEN (LETZTE 30 TAGE)" : "SPEND (LAST 30 DAYS)";
      case "last_60_days":
        return isDe ? "AUSGABEN (LETZTE 60 TAGE)" : "SPEND (LAST 60 DAYS)";
      case "last_90_days":
        return isDe ? "AUSGABEN (LETZTE 90 TAGE)" : "SPEND (LAST 90 DAYS)";
      case "year":
        return isDe
          ? `JAHRESAUSGABEN (${new Date().getFullYear()})`
          : `ANNUAL SPEND (${new Date().getFullYear()})`;
      case "custom":
        return isDe ? "ZEITRAUM-AUSGABEN" : "PERIOD SPEND";
      case "today":
        return isDe ? "HEUTIGE AUSGABEN" : "TODAY'S SPEND";
      case "week":
        return isDe ? "WOCHENAUSGABEN" : "WEEKLY SPEND";
      case "month":
      default:
        return isDe ? "MONATSAUSGABEN" : "MONTHLY SPEND";
    }
  };

  return (
    <div
      data-testid="kpi-cards-grid"
      className="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6"
    >
      {/* ------------------------------------------------------------- */}
      {/* CARD 1: Total Scanned (Gesamt erfasst)                         */}
      {/* ------------------------------------------------------------- */}
      <div
        data-testid="kpi-card-total-scanned"
        onClick={onResetFilters}
        className="p-5 sm:p-6 bg-white border border-[#E2E8F0] space-y-3 relative group hover:border-black hover:shadow-lg transition-all duration-200 cursor-pointer overflow-hidden"
        title={isDe ? "Klicken zum Zurücksetzen aller Filter" : "Click to view all receipts"}
      >
        <div className="flex items-center justify-between">
          <span className="font-mono text-[11px] uppercase tracking-caps text-[#64748B] font-semibold">
            {isDe ? "GESAMTVOLUMEN (BRUTTO)" : "TOTAL VOLUME (GROSS)"}
          </span>
          <FileText className="w-4 h-4 text-[#94A3B8] group-hover:text-black transition-colors" />
        </div>

        <div>
          <div className="font-display text-2xl sm:text-3xl font-bold text-black tracking-tight">
            {metrics.totalGross.toLocaleString(isDe ? "de-DE" : "en-US", {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}{" "}
            €
          </div>
          <p className="font-mono text-xs text-[#475569] mt-1">
            {metrics.totalScanned} {isDe ? "Belege erfasst" : "Receipts scanned"}
          </p>
        </div>

        <div className="pt-2 border-t border-[#F1F5F9] flex items-center justify-between font-mono text-[11px] text-[#64748B]">
          <span>
            Netto: {metrics.totalNet.toFixed(2)} €
            {metrics.totalTips > 0 && (
              <>
                {" • "}
                {isDe ? "Trinkgeld" : "Tips"}: {metrics.totalTips.toFixed(2)} €
              </>
            )}
          </span>
          <span className="text-emerald-600 font-semibold flex items-center gap-1">
            <CheckCircle2 className="w-3 h-3" />
            {metrics.confirmedCount} {isDe ? "geprüft" : "verified"}
          </span>
        </div>
      </div>

      {/* ------------------------------------------------------------- */}
      {/* CARD 2: Period / Monthly Spend (Ausgaben Zeitraum)             */}
      {/* ------------------------------------------------------------- */}
      <div
        data-testid="kpi-card-monthly-spend"
        onClick={() => onFilterPeriod?.(activePeriod === "month" ? "all" : "month")}
        className={`p-5 sm:p-6 bg-white border space-y-3 relative group hover:border-black hover:shadow-lg transition-all duration-200 cursor-pointer overflow-hidden ${
          isPeriodFilterActive ? "border-black ring-1 ring-black bg-[#F8FAFC]" : "border-[#E2E8F0]"
        }`}
        title={
          isDe
            ? "Klicken zum Umschalten des Monatsfilters"
            : "Click to toggle month filter"
        }
      >
        <div className="flex items-center justify-between">
          <span className="font-mono text-[11px] uppercase tracking-caps text-[#64748B] font-semibold">
            {getPeriodCardTitle()}
          </span>
          <Calendar
            className={`w-4 h-4 transition-colors ${
              isPeriodFilterActive ? "text-black" : "text-[#94A3B8] group-hover:text-black"
            }`}
          />
        </div>

        <div>
          <div className="font-display text-2xl sm:text-3xl font-bold text-black tracking-tight">
            {metrics.periodSpendPaid.toLocaleString(isDe ? "de-DE" : "en-US", {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}{" "}
            €
          </div>
          <div className="flex items-center gap-1.5 mt-1 font-mono text-xs text-[#475569]">
            <TrendingUp className="w-3.5 h-3.5 text-black" />
            <span>
              {metrics.periodReceiptsCount} {isDe ? "Belege" : "receipts"}
              {metrics.periodSpendTips > 0 && (
                <>
                  {" • "}
                  {isDe
                    ? `inkl. ${metrics.periodSpendTips.toFixed(2)} € Trinkgeld`
                    : `incl. ${metrics.periodSpendTips.toFixed(2)} € tips`}
                </>
              )}
            </span>
          </div>
        </div>

        <div className="pt-2 border-t border-[#F1F5F9] flex items-center justify-between font-mono text-[11px]">
          <span className="text-[#64748B]">
            {vatBreakdownLabel}
          </span>
          {isPeriodFilterActive && (
            <span className="text-xs font-bold text-black uppercase tracking-wider">
              [AKTIV]
            </span>
          )}
        </div>
      </div>

      {/* ------------------------------------------------------------- */}
      {/* CARD 3: Pending Reviews (Prüfung erforderlich)                 */}
      {/* ------------------------------------------------------------- */}
      <div
        data-testid="kpi-card-pending-reviews"
        onClick={() => onFilterStatus?.(isPendingFilterActive ? "all" : "pending")}
        className={`p-5 sm:p-6 bg-white border space-y-3 relative group transition-all duration-200 cursor-pointer overflow-hidden ${
          isPendingFilterActive
            ? "border-amber-500 ring-2 ring-amber-400/50 bg-[#FEF3C7]/20 shadow-md"
            : metrics.pendingReviewsCount > 0
            ? "border-[#E2E8F0] hover:border-amber-400 hover:shadow-lg"
            : "border-[#E2E8F0] hover:border-black hover:shadow-lg"
        }`}
        title={
          isDe
            ? "Klicken zum Filtern auf ungeprüfte Belege"
            : "Click to filter receipts needing review"
        }
      >
        <div className="flex items-center justify-between">
          <span className="font-mono text-[11px] uppercase tracking-caps text-[#64748B] font-semibold">
            {isDe ? "PRÜFUNG ERFORDERLICH" : "PENDING REVIEWS"}
          </span>
          <AlertTriangle
            className={`w-4 h-4 transition-colors ${
              metrics.pendingReviewsCount > 0
                ? "text-amber-500 animate-pulse"
                : "text-[#94A3B8] group-hover:text-black"
            }`}
          />
        </div>

        <div>
          <div className="font-display text-2xl sm:text-3xl font-bold text-black tracking-tight flex items-center gap-2">
            <span>{metrics.pendingReviewsCount}</span>
            {metrics.pendingReviewsCount > 0 ? (
              <span className="font-mono text-[11px] bg-amber-100 border border-amber-300 text-amber-900 px-2 py-0.5 font-semibold">
                {isDe ? "Prüfung nötig" : "Action Needed"}
              </span>
            ) : (
              <span className="font-mono text-[11px] bg-emerald-100 border border-emerald-300 text-emerald-800 px-2 py-0.5 font-semibold">
                {isDe ? "Alle OK ✓" : "All Clean ✓"}
              </span>
            )}
          </div>
          <p className="font-mono text-xs text-[#475569] mt-1">
            {metrics.pendingReviewsCount > 0
              ? isDe
                ? "Diskrepanzen oder geringe Konfidenz"
                : "Math checks or low confidence"
              : isDe
              ? "Keine offenen Prüfungen"
              : "Zero pending issues"}
          </p>
        </div>

        <div className="pt-2 border-t border-[#F1F5F9] flex items-center justify-between font-mono text-[11px] text-[#64748B]">
          <span className="flex items-center gap-1.5">
            <Filter className="w-3 h-3 text-black" />
            <span>{isDe ? "Klick zum Filtern" : "Click to filter"}</span>
          </span>
          {isPendingFilterActive && (
            <span className="text-xs font-bold text-amber-700 uppercase tracking-wider">
              [GEFILTERT]
            </span>
          )}
        </div>
      </div>
    </div>
  );
}
