"use client";

import React from "react";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { DuplicateMatch } from "@/lib/storage/duplicates";
import { formatMoney, receiptCurrency } from "./receiptFormat";
import { Copy, ShieldAlert, Trash2 } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";

export interface PendingDuplicate {
  /** Der noch nicht gespeicherte Beleg. */
  candidate: ProcessedReceipt;
  /** Gefundene Treffer, stärkster zuerst. */
  matches: DuplicateMatch[];
}

interface DuplicateWarningDialogProps {
  pending: PendingDuplicate | null;
  /** Beleg trotz Verdacht speichern. */
  onKeep: () => void;
  /** Beleg verwerfen (er wurde noch nicht gespeichert). */
  onDiscard: () => void;
}

function ReceiptSummary({
  receipt,
  label,
  accent,
}: {
  receipt: ProcessedReceipt;
  label: string;
  accent: boolean;
}) {
  const currency = receiptCurrency(receipt);
  return (
    <div
      className={`border p-3 ${accent ? "border-black bg-[#EEF4FC]" : "border-[#E2E8F0] bg-white"}`}
    >
      <span className="block font-mono text-[9px] uppercase tracking-caps text-[#64748B]">
        {label}
      </span>
      <p className="mt-1 truncate text-xs font-bold text-black">
        {receipt.merchant?.name ?? "—"}
      </p>
      <p className="font-mono text-[11px] text-[#475569]">
        {receipt.date?.isoDate ?? "—"} ·{" "}
        {formatMoney(receipt.totalAmount?.value ?? 0, currency)}
      </p>
      <p className="mt-1 truncate font-mono text-[10px] text-[#94A3B8]">
        {receipt.originalFileName || receipt.id}
      </p>
    </div>
  );
}

/**
 * Warnt vor einem doppelt erfassten Beleg und überlässt die Entscheidung dem
 * Benutzer. Es wird bewusst nichts still verworfen.
 */
export function DuplicateWarningDialog({
  pending,
  onKeep,
  onDiscard,
}: DuplicateWarningDialogProps) {
  const { language } = useI18n();
  const isDe = language === "de";

  if (!pending) return null;

  const { candidate, matches } = pending;
  const isExact = matches.some((match) => match.kind === "exact");

  return (
    <div className="fixed inset-0 z-[90] flex items-center justify-center bg-black/60 p-4 font-sans backdrop-blur-sm">
      <div
        data-testid="duplicate-dialog"
        className="w-full max-w-2xl border-2 border-black bg-white"
      >
        <div className="flex items-center gap-3 border-b border-[#E2E8F0] px-6 py-4">
          <div className="flex h-8 w-8 shrink-0 items-center justify-center bg-black text-white">
            {isExact ? (
              <Copy className="h-4 w-4" />
            ) : (
              <ShieldAlert className="h-4 w-4" />
            )}
          </div>
          <div>
            <h3 className="font-display text-lg font-bold text-black">
              {isExact
                ? (isDe ? "Beleg bereits vorhanden" : "Receipt Already Exists")
                : (isDe ? "Möglicher Doppel-Beleg" : "Possible Duplicate Receipt")}
            </h3>
            <p className="font-mono text-[11px] text-[#64748B]">
              {isExact
                ? (isDe
                    ? "Dieses Bild wurde bereits einmal eingelesen (identischer SHA-256 Hash)."
                    : "This file was already scanned before (identical SHA-256 hash).")
                : (isDe
                    ? "Händler, Datum und Betrag stimmen mit einem vorhandenen Beleg überein."
                    : "Merchant, date, and amount match an existing receipt.")}
            </p>
          </div>
        </div>

        <div className="space-y-4 px-6 py-5">
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            <ReceiptSummary receipt={candidate} label={isDe ? "Neu eingelesen" : "Newly Scanned"} accent />
            <ReceiptSummary
              receipt={matches[0].existing}
              label={isDe ? "Bereits gespeichert" : "Already Stored"}
              accent={false}
            />
          </div>

          <ul className="space-y-1.5 border border-[#E2E8F0] bg-[#F8FAFC] p-3">
            {matches.slice(0, 4).map((match, index) => (
              <li key={index} className="flex items-start gap-2 text-[11px]">
                <span
                  className={`mt-0.5 shrink-0 px-1.5 font-mono text-[9px] uppercase ${
                    match.kind === "exact"
                      ? "bg-[#FFDAD6] text-[#93000A]"
                      : "bg-[#FDE68A] text-[#92400E]"
                  }`}
                >
                  {match.kind === "exact" ? (isDe ? "Identisch" : "Identical") : (isDe ? "Ähnlich" : "Similar")}
                </span>
                <span className="text-black">{match.reason}</span>
              </li>
            ))}
          </ul>

          <p className="text-xs text-[#475569]">
            {isDe
              ? "Doppelt erfasste Belege erscheinen zweimal in deinem Export. Prüfe kurz, ob es wirklich derselbe Beleg ist."
              : "Duplicate receipts would appear twice in your export. Please confirm this is really the same receipt."}
          </p>
        </div>

        <div className="flex flex-wrap items-center justify-end gap-3 border-t border-[#E2E8F0] bg-[#F8FAFC] px-6 py-4 font-mono text-xs uppercase tracking-caps">
          <button
            type="button"
            data-testid="duplicate-discard"
            onClick={onDiscard}
            className="flex items-center gap-2 border border-[#BA1A1A] bg-white px-4 py-2 text-[#BA1A1A] transition-colors hover:bg-[#FFDAD6]"
          >
            <Trash2 className="h-3.5 w-3.5" />
            <span>{isDe ? "Nicht übernehmen" : "Discard"}</span>
          </button>
          <button
            type="button"
            data-testid="duplicate-keep"
            onClick={onKeep}
            className="bg-black px-5 py-2 font-medium text-white transition-colors hover:bg-[#334155]"
          >
            {isDe ? "Trotzdem speichern" : "Save Anyway"}
          </button>
        </div>
      </div>
    </div>
  );
}
