import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { RecentTransaction } from "../../shared/types";
import {
  KEYWORD_MAX_LENGTH,
  KEYWORD_MIN_LENGTH,
  KEYWORD_PREVIEW_LIMIT,
  applyKeywordWithReassignment,
  previewKeywordMatches,
  validateKeyword,
} from "../../services/categorizationService";
import { getAllCategoriesWithCounts } from "../../services/categoryService";

interface CategoryOption {
  id: number;
  name: string;
}

export interface AddKeywordDialogProps {
  initialKeyword: string;
  initialCategoryId?: number | null;
  onClose: () => void;
  onApplied?: () => void;
}

type PreviewState =
  | { kind: "idle" }
  | { kind: "loading" }
  | { kind: "ready"; visible: RecentTransaction[]; totalMatches: number }
  | { kind: "error"; message: string };

export default function AddKeywordDialog({
  initialKeyword,
  initialCategoryId = null,
  onClose,
  onApplied,
}: AddKeywordDialogProps) {
  const { t } = useTranslation();
  const [keyword, setKeyword] = useState(initialKeyword);
  const [categoryId, setCategoryId] = useState<number | null>(initialCategoryId);
  const [categories, setCategories] = useState<CategoryOption[]>([]);
  const [checked, setChecked] = useState<Set<number>>(new Set());
  const [applyToHidden, setApplyToHidden] = useState(false);
  const [preview, setPreview] = useState<PreviewState>({ kind: "idle" });
  const [isApplying, setIsApplying] = useState(false);
  const [applyError, setApplyError] = useState<string | null>(null);
  const [replacePrompt, setReplacePrompt] = useState<string | null>(null);
  const [allowReplaceExisting, setAllowReplaceExisting] = useState(false);

  const validation = useMemo(() => validateKeyword(keyword), [keyword]);

  useEffect(() => {
    getAllCategoriesWithCounts()
      .then((rows) => setCategories(rows.map((r) => ({ id: r.id, name: r.name }))))
      .catch(() => setCategories([]));
  }, []);

  useEffect(() => {
    if (!validation.ok) {
      setPreview({ kind: "idle" });
      return;
    }
    let cancelled = false;
    setPreview({ kind: "loading" });
    previewKeywordMatches(validation.value, KEYWORD_PREVIEW_LIMIT)
      .then(({ visible, totalMatches }) => {
        if (cancelled) return;
        setPreview({ kind: "ready", visible, totalMatches });
        setChecked(new Set(visible.map((tx) => tx.id)));
      })
      .catch((e: unknown) => {
        if (cancelled) return;
        setPreview({ kind: "error", message: e instanceof Error ? e.message : String(e) });
      });
    return () => {
      cancelled = true;
    };
  }, [validation]);

  const toggleRow = (id: number) => {
    setChecked((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const canApply =
    validation.ok &&
    categoryId !== null &&
    preview.kind === "ready" &&
    !isApplying &&
    checked.size > 0;

  const handleApply = async () => {
    if (!validation.ok || categoryId === null) return;
    setIsApplying(true);
    setApplyError(null);
    try {
      await applyKeywordWithReassignment({
        keyword: validation.value,
        categoryId,
        transactionIds: Array.from(checked),
        allowReplaceExisting,
      });
      if (onApplied) onApplied();
      onClose();
    } catch (e) {
      const msg = e instanceof Error ? e.message : String(e);
      if (msg === "keyword_already_exists") {
        setReplacePrompt(t("reports.keyword.alreadyExists", { category: "" }));
      } else {
        setApplyError(msg);
      }
    } finally {
      setIsApplying(false);
    }
  };

  const preventBackdropClose = (e: React.MouseEvent) => e.stopPropagation();

  return (
    <div
      onClick={onClose}
      className="fixed inset-0 z-[200] bg-black/40 flex items-center justify-center p-4"
      role="dialog"
      aria-modal="true"
    >
      <div
        onClick={preventBackdropClose}
        className="bg-[var(--card)] border border-[var(--border)] rounded-xl shadow-xl max-w-xl w-full max-h-[90vh] flex flex-col"
      >
        <header className="px-5 py-3 border-b border-[var(--border)]">
          <h2 className="text-base font-semibold">{t("reports.keyword.dialogTitle")}</h2>
        </header>

        <div className="px-5 py-4 flex flex-col gap-4 overflow-y-auto">
          <label className="flex flex-col gap-1">
            <span className="text-xs font-medium text-[var(--muted-foreground)] uppercase tracking-wide">
              {t("reports.keyword.dialogTitle")}
            </span>
            <input
              type="text"
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              maxLength={KEYWORD_MAX_LENGTH * 2 /* allow user to paste longer then see error */}
              className="bg-[var(--card)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm"
            />
            {!validation.ok && (
              <span className="text-xs text-[var(--negative)]">
                {validation.reason === "tooShort"
                  ? t("reports.keyword.tooShort", { min: KEYWORD_MIN_LENGTH })
                  : t("reports.keyword.tooLong", { max: KEYWORD_MAX_LENGTH })}
              </span>
            )}
          </label>

          <label className="flex flex-col gap-1">
            <span className="text-xs font-medium text-[var(--muted-foreground)] uppercase tracking-wide">
              {t("reports.highlights.category")}
            </span>
            <select
              value={categoryId ?? ""}
              onChange={(e) => setCategoryId(e.target.value ? Number(e.target.value) : null)}
              className="bg-[var(--card)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm"
            >
              <option value="">—</option>
              {categories.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </label>

          <section>
            <h3 className="text-xs font-medium text-[var(--muted-foreground)] uppercase tracking-wide mb-2">
              {t("reports.keyword.willMatch")}
            </h3>
            {preview.kind === "idle" && (
              <p className="text-sm text-[var(--muted-foreground)] italic">—</p>
            )}
            {preview.kind === "loading" && (
              <p className="text-sm text-[var(--muted-foreground)] italic">{t("common.loading")}</p>
            )}
            {preview.kind === "error" && (
              <p className="text-sm text-[var(--negative)]">{preview.message}</p>
            )}
            {preview.kind === "ready" && (
              <>
                <p className="text-sm mb-2">
                  {t("reports.keyword.nMatches", { count: preview.totalMatches })}
                </p>
                <ul className="divide-y divide-[var(--border)] max-h-[220px] overflow-y-auto border border-[var(--border)] rounded-lg">
                  {preview.visible.map((tx) => (
                    <li key={tx.id} className="flex items-center gap-2 px-3 py-1.5 text-sm">
                      <input
                        type="checkbox"
                        checked={checked.has(tx.id)}
                        onChange={() => toggleRow(tx.id)}
                        className="accent-[var(--primary)]"
                      />
                      <span className="text-[var(--muted-foreground)] tabular-nums flex-shrink-0">
                        {tx.date}
                      </span>
                      <span className="flex-1 min-w-0 truncate">{tx.description}</span>
                      <span className="tabular-nums font-medium flex-shrink-0">
                        {new Intl.NumberFormat("en-CA", {
                          style: "currency",
                          currency: "CAD",
                        }).format(tx.amount)}
                      </span>
                    </li>
                  ))}
                </ul>
                {preview.totalMatches > preview.visible.length && (
                  <label className="flex items-center gap-2 text-xs mt-2 text-[var(--muted-foreground)]">
                    <input
                      type="checkbox"
                      checked={applyToHidden}
                      onChange={(e) => setApplyToHidden(e.target.checked)}
                      className="accent-[var(--primary)]"
                    />
                    {t("reports.keyword.applyToHidden", {
                      count: preview.totalMatches - preview.visible.length,
                    })}
                  </label>
                )}
              </>
            )}
          </section>

          {replacePrompt && (
            <div className="bg-[var(--muted)]/50 border border-[var(--border)] rounded-lg p-3 text-sm flex flex-col gap-2">
              <p>{replacePrompt}</p>
              <button
                type="button"
                onClick={() => {
                  setAllowReplaceExisting(true);
                  setReplacePrompt(null);
                  void handleApply();
                }}
                className="self-start px-3 py-1.5 rounded-lg bg-[var(--primary)] text-white text-sm"
              >
                {t("common.confirm")}
              </button>
            </div>
          )}

          {applyError && (
            <div className="bg-[var(--negative)]/10 text-[var(--negative)] rounded-lg p-3 text-sm">
              {applyError}
            </div>
          )}
        </div>

        <footer className="px-5 py-3 border-t border-[var(--border)] flex items-center justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="px-3 py-2 rounded-lg text-sm bg-[var(--card)] border border-[var(--border)] hover:bg-[var(--muted)]"
          >
            {t("common.cancel")}
          </button>
          <button
            type="button"
            onClick={handleApply}
            disabled={!canApply}
            className="px-3 py-2 rounded-lg text-sm bg-[var(--primary)] text-white font-medium disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isApplying ? t("common.loading") : t("reports.keyword.applyAndRecategorize")}
          </button>
        </footer>
      </div>
    </div>
  );
}
