"use client";

import React, { useState } from "react";
import {
  CheckSquare,
  X,
  Trash2,
  FileSpreadsheet,
  FolderEdit,
  FolderKanban,
  FolderMinus,
  UserCheck,
  ChevronUp,
  Download,
  AlertTriangle,
  FileText,
  FileCode,
  FileDown,
} from "lucide-react";
import { ProcessedReceipt, ReceiptCategory } from "@/lib/schema/receipt";
import { generateDualSheetExcel } from "@/lib/export/excelGenerator";
import { generateAccountingCsv } from "@/lib/export/csvGenerator";
import { generateReceiptPdf } from "@/lib/export/pdfGenerator";
import { ReceiptStatusTier } from "./StatusBadge";
import { useI18n } from "@/lib/i18n/context";

const CATEGORIES: ReceiptCategory[] = [
  "Bewirtung",
  "Reisekosten & Hotel",
  "Tanken & KFZ",
  "Bürobedarf & IT",
  "Verpflegungsmehraufwand",
  "Material & Einkauf",
  "Sonstiges",
];

const CATEGORY_LABELS: Record<ReceiptCategory, { de: string; en: string }> = {
  "Bewirtung": { de: "Bewirtung", en: "Meals & Entertainment" },
  "Reisekosten & Hotel": { de: "Reisekosten & Hotel", en: "Travel & Lodging" },
  "Tanken & KFZ": { de: "Tanken & KFZ", en: "Fuel & Vehicle" },
  "Bürobedarf & IT": { de: "Bürobedarf & IT", en: "Office Supplies & IT" },
  "Verpflegungsmehraufwand": { de: "Verpflegungsmehraufwand", en: "Per Diem / Subsistence" },
  "Material & Einkauf": { de: "Material & Einkauf", en: "Supplies & Inventory" },
  "Sonstiges": { de: "Sonstiges", en: "Other / Misc" },
};

export interface BatchActionBarProject {
  id: string;
  name: string;
}

export interface BatchActionBarProps {
  /** IDs of all currently selected receipts */
  selectedIds: string[];
  /** Full list of receipts to extract selected records from */
  receipts: ProcessedReceipt[];
  /** Handler when user confirms bulk deletion */
  onBulkDelete: (ids: string[]) => void | Promise<void>;
  /** Handler when user selects a category for bulk categorization */
  onBulkCategorize: (ids: string[], category: ReceiptCategory) => void | Promise<void>;
  /** Handler when user updates status in bulk */
  onBulkStatusUpdate: (ids: string[], status: ReceiptStatusTier) => void | Promise<void>;
  /** Optional custom bulk export handler */
  onBulkExport?: (ids: string[], format: "xlsx" | "csv" | "pdf" | "json") => void | Promise<void>;
  /**
   * The caller's Pro-only projects (folders) and the handler to move the
   * selection into one (or clear it with `null`). Omitted / empty for
   * free-plan users, which hides the "Move to Project" control entirely.
   */
  projects?: BatchActionBarProject[];
  onBulkMoveToProject?: (ids: string[], projectId: string | null) => void | Promise<void>;
  /** Handler to clear all selections */
  onClearSelection: () => void;
  /** Additional styling */
  className?: string;
}

export function BatchActionBar({
  selectedIds,
  receipts,
  onBulkDelete,
  onBulkCategorize,
  onBulkStatusUpdate,
  onBulkExport,
  projects,
  onBulkMoveToProject,
  onClearSelection,
  className = "",
}: BatchActionBarProps) {
  const { language } = useI18n();
  const isDe = language === "de";

  const [isExportMenuOpen, setIsExportMenuOpen] = useState(false);
  const [isCategoryMenuOpen, setIsCategoryMenuOpen] = useState(false);
  const [isStatusMenuOpen, setIsStatusMenuOpen] = useState(false);
  const [isProjectMenuOpen, setIsProjectMenuOpen] = useState(false);
  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const [isExporting, setIsExporting] = useState(false);

  if (selectedIds.length === 0) return null;

  const selectedReceipts = receipts.filter((r) => selectedIds.includes(r.id));
  const count = selectedIds.length;

  const handleExport = async (format: "xlsx" | "csv" | "pdf" | "json") => {
    if (onBulkExport) {
      await onBulkExport(selectedIds, format);
      setIsExportMenuOpen(false);
      return;
    }

    setIsExporting(true);
    try {
      if (format === "xlsx") {
        const buffer = await generateDualSheetExcel(selectedReceipts);
        const blob = new Blob([new Uint8Array(buffer)], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = isDe
          ? `Belege_Auswahl_${count}_${new Date().toISOString().slice(0, 10)}.xlsx`
          : `Receipts_Selection_${count}_${new Date().toISOString().slice(0, 10)}.xlsx`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      } else if (format === "csv") {
        const csvContent = generateAccountingCsv(selectedReceipts);
        const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = isDe
          ? `Belege_Auswahl_${count}_${new Date().toISOString().slice(0, 10)}.csv`
          : `Receipts_Selection_${count}_${new Date().toISOString().slice(0, 10)}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      } else if (format === "pdf") {
        const pdfBytes = await generateReceiptPdf(selectedReceipts, { locale: isDe ? "de" : "en" });
        const blob = new Blob([new Uint8Array(pdfBytes)], { type: "application/pdf" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = isDe
          ? `Belege_Auswahl_${count}_${new Date().toISOString().slice(0, 10)}.pdf`
          : `Receipts_Selection_${count}_${new Date().toISOString().slice(0, 10)}.pdf`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      } else if (format === "json") {
        const jsonContent = JSON.stringify(selectedReceipts, null, 2);
        const blob = new Blob([jsonContent], { type: "application/json;charset=utf-8;" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = isDe
          ? `Belege_Auswahl_${count}_${new Date().toISOString().slice(0, 10)}.json`
          : `Receipts_Selection_${count}_${new Date().toISOString().slice(0, 10)}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }
    } catch (err) {
      console.error("Bulk export failed:", err);
    } finally {
      setIsExporting(false);
      setIsExportMenuOpen(false);
    }
  };

  const handleApplyCategory = async (cat: ReceiptCategory) => {
    await onBulkCategorize(selectedIds, cat);
    setIsCategoryMenuOpen(false);
  };

  const handleApplyStatus = async (status: ReceiptStatusTier) => {
    await onBulkStatusUpdate(selectedIds, status);
    setIsStatusMenuOpen(false);
  };

  const handleApplyProject = async (projectId: string | null) => {
    if (!onBulkMoveToProject) return;
    await onBulkMoveToProject(selectedIds, projectId);
    setIsProjectMenuOpen(false);
  };

  const handleConfirmDelete = async () => {
    await onBulkDelete(selectedIds);
    setIsDeleteConfirmOpen(false);
    onClearSelection();
  };

  return (
    <>
      {/* Floating Toolbar */}
      <div
        data-testid="batch-action-bar"
        className={`fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-[#161C22] text-white border border-slate-700 shadow-2xl px-4 py-2.5 flex flex-wrap items-center gap-3 font-mono text-xs select-none max-w-[95vw] ${className}`}
      >
        {/* Count & Clear */}
        <div className="flex items-center gap-2 pr-3 border-r border-slate-700">
          <CheckSquare className="w-4 h-4 text-emerald-400" />
          <span className="font-semibold text-white">
            <span data-testid="batch-selected-count">{count}</span> {isDe ? (count === 1 ? "Beleg gewählt" : "Belege gewählt") : (count === 1 ? "receipt selected" : "receipts selected")}
          </span>
          <button
            type="button"
            data-testid="batch-clear-selection-btn"
            onClick={onClearSelection}
            className="p-1 hover:bg-slate-800 text-slate-400 hover:text-white transition-colors"
            title={isDe ? "Auswahl aufheben" : "Clear selection"}
            aria-label={isDe ? "Auswahl aufheben" : "Clear selection"}
          >
            <X className="w-3.5 h-3.5" />
          </button>
        </div>

        {/* Bulk Export Menu */}
        <div className="relative">
          <button
            type="button"
            data-testid="batch-export-menu-btn"
            onClick={() => {
              setIsExportMenuOpen((prev) => !prev);
              setIsCategoryMenuOpen(false);
              setIsStatusMenuOpen(false);
              setIsProjectMenuOpen(false);
            }}
            disabled={isExporting}
            className="flex items-center gap-1.5 bg-slate-800 hover:bg-slate-700 text-white px-3 py-1.5 transition-colors uppercase tracking-wider text-[11px]"
          >
            <Download className="w-3.5 h-3.5 text-blue-400" />
            <span>{isDe ? "Exportieren" : "Export"}</span>
            <ChevronUp className={`w-3 h-3 transition-transform ${isExportMenuOpen ? "rotate-180" : ""}`} />
          </button>

          {isExportMenuOpen && (
            <div
              data-testid="batch-export-dropdown"
              className="absolute bottom-full left-0 mb-2 w-52 bg-white text-black border border-black shadow-2xl p-1 z-50 font-sans text-xs"
            >
              <button
                type="button"
                data-testid="batch-export-xlsx"
                onClick={() => handleExport("xlsx")}
                className="w-full text-left px-3 py-2 hover:bg-[#EEF4FC] flex items-center gap-2 font-mono text-xs"
              >
                <FileSpreadsheet className="w-3.5 h-3.5 text-emerald-600" />
                <span>Excel (.xlsx)</span>
              </button>
              <button
                type="button"
                data-testid="batch-export-csv"
                onClick={() => handleExport("csv")}
                className="w-full text-left px-3 py-2 hover:bg-[#EEF4FC] flex items-center gap-2 font-mono text-xs"
              >
                <FileText className="w-3.5 h-3.5 text-blue-600" />
                <span>{isDe ? "CSV-Datei (.csv)" : "CSV File (.csv)"}</span>
              </button>
              <button
                type="button"
                data-testid="batch-export-pdf"
                onClick={() => handleExport("pdf")}
                className="w-full text-left px-3 py-2 hover:bg-[#EEF4FC] flex items-center gap-2 font-mono text-xs"
              >
                <FileDown className="w-3.5 h-3.5 text-red-600" />
                <span>{isDe ? "PDF-Report (.pdf)" : "PDF Report (.pdf)"}</span>
              </button>
              <button
                type="button"
                data-testid="batch-export-json"
                onClick={() => handleExport("json")}
                className="w-full text-left px-3 py-2 hover:bg-[#EEF4FC] flex items-center gap-2 font-mono text-xs"
              >
                <FileCode className="w-3.5 h-3.5 text-slate-600" />
                <span>{isDe ? "JSON Daten (.json)" : "JSON Data (.json)"}</span>
              </button>
            </div>
          )}
        </div>

        {/* Bulk Categorize Menu */}
        <div className="relative">
          <button
            type="button"
            data-testid="batch-categorize-menu-btn"
            onClick={() => {
              setIsCategoryMenuOpen((prev) => !prev);
              setIsExportMenuOpen(false);
              setIsStatusMenuOpen(false);
              setIsProjectMenuOpen(false);
            }}
            className="flex items-center gap-1.5 bg-slate-800 hover:bg-slate-700 text-white px-3 py-1.5 transition-colors uppercase tracking-wider text-[11px]"
          >
            <FolderEdit className="w-3.5 h-3.5 text-amber-400" />
            <span>{isDe ? "Kategorisieren" : "Categorize"}</span>
            <ChevronUp className={`w-3 h-3 transition-transform ${isCategoryMenuOpen ? "rotate-180" : ""}`} />
          </button>

          {isCategoryMenuOpen && (
            <div
              data-testid="batch-category-dropdown"
              className="absolute bottom-full left-0 mb-2 w-56 bg-white text-black border border-black shadow-2xl p-1 z-50 font-sans text-xs"
            >
              <div className="px-3 py-1.5 font-mono text-[10px] uppercase tracking-caps text-[#64748B] border-b border-[#E2E8F0] font-bold">
                {isDe ? `Kategorie zuweisen (${count})` : `Assign Category (${count})`}
              </div>
              {CATEGORIES.map((cat) => (
                <button
                  key={cat}
                  type="button"
                  data-testid={`batch-cat-option-${cat}`}
                  onClick={() => handleApplyCategory(cat)}
                  className="w-full text-left px-3 py-1.5 hover:bg-[#EEF4FC] font-sans text-xs truncate"
                >
                  {isDe ? CATEGORY_LABELS[cat]?.de || cat : CATEGORY_LABELS[cat]?.en || cat}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Bulk Status Menu */}
        <div className="relative">
          <button
            type="button"
            data-testid="batch-status-menu-btn"
            onClick={() => {
              setIsStatusMenuOpen((prev) => !prev);
              setIsExportMenuOpen(false);
              setIsCategoryMenuOpen(false);
              setIsProjectMenuOpen(false);
            }}
            className="flex items-center gap-1.5 bg-slate-800 hover:bg-slate-700 text-white px-3 py-1.5 transition-colors uppercase tracking-wider text-[11px]"
          >
            <UserCheck className="w-3.5 h-3.5 text-emerald-400" />
            <span>{isDe ? "Status ändern" : "Change Status"}</span>
            <ChevronUp className={`w-3 h-3 transition-transform ${isStatusMenuOpen ? "rotate-180" : ""}`} />
          </button>

          {isStatusMenuOpen && (
            <div
              data-testid="batch-status-dropdown"
              className="absolute bottom-full left-0 mb-2 w-56 bg-white text-black border border-black shadow-2xl p-1 z-50 font-sans text-xs"
            >
              <button
                type="button"
                data-testid="batch-status-confirm-btn"
                onClick={() => handleApplyStatus("confirmed")}
                className="w-full text-left px-3 py-2 hover:bg-[#EEF4FC] flex items-center gap-2 font-mono text-xs text-blue-800"
              >
                <span className="w-2 h-2 rounded-full bg-blue-600" />
                <span>{isDe ? "Als Bestätigt markieren" : "Mark as Confirmed"}</span>
              </button>
              <button
                type="button"
                data-testid="batch-status-scanned-btn"
                onClick={() => handleApplyStatus("scanned")}
                className="w-full text-left px-3 py-2 hover:bg-[#EEF4FC] flex items-center gap-2 font-mono text-xs text-emerald-800"
              >
                <span className="w-2 h-2 rounded-full bg-emerald-500" />
                <span>{isDe ? "Als Erfasst markieren" : "Mark as Captured"}</span>
              </button>
              <button
                type="button"
                data-testid="batch-status-pending-btn"
                onClick={() => handleApplyStatus("pending_review")}
                className="w-full text-left px-3 py-2 hover:bg-[#EEF4FC] flex items-center gap-2 font-mono text-xs text-amber-800"
              >
                <span className="w-2 h-2 rounded-full bg-amber-500" />
                <span>{isDe ? "Prüfung erforderlich" : "Mark as Review Required"}</span>
              </button>
            </div>
          )}
        </div>

        {/* Bulk Move-to-Project Menu (Pro-only — hidden when no projects exist) */}
        {projects && projects.length > 0 && onBulkMoveToProject && (
          <div className="relative">
            <button
              type="button"
              data-testid="batch-project-menu-btn"
              onClick={() => {
                setIsProjectMenuOpen((prev) => !prev);
                setIsExportMenuOpen(false);
                setIsCategoryMenuOpen(false);
                setIsStatusMenuOpen(false);
              }}
              className="flex items-center gap-1.5 bg-slate-800 hover:bg-slate-700 text-white px-3 py-1.5 transition-colors uppercase tracking-wider text-[11px]"
            >
              <FolderKanban className="w-3.5 h-3.5 text-blue-400" />
              <span>{isDe ? "Projekt zuweisen" : "Move to Project"}</span>
              <ChevronUp className={`w-3 h-3 transition-transform ${isProjectMenuOpen ? "rotate-180" : ""}`} />
            </button>

            {isProjectMenuOpen && (
              <div
                data-testid="batch-project-dropdown"
                className="absolute bottom-full left-0 mb-2 w-56 bg-white text-black border border-black shadow-2xl p-1 z-50 font-sans text-xs"
              >
                <div className="px-3 py-1.5 font-mono text-[10px] uppercase tracking-caps text-[#64748B] border-b border-[#E2E8F0] font-bold">
                  {isDe ? `Projekt zuweisen (${count})` : `Assign Project (${count})`}
                </div>
                {projects.map((project) => (
                  <button
                    key={project.id}
                    type="button"
                    data-testid={`batch-project-option-${project.id}`}
                    onClick={() => handleApplyProject(project.id)}
                    className="w-full text-left px-3 py-1.5 hover:bg-[#EEF4FC] font-sans text-xs truncate"
                  >
                    {project.name}
                  </button>
                ))}
                <button
                  type="button"
                  data-testid="batch-project-option-remove"
                  onClick={() => handleApplyProject(null)}
                  className="w-full text-left px-3 py-1.5 hover:bg-[#EEF4FC] font-sans text-xs flex items-center gap-2 border-t border-[#E2E8F0] text-[#475569]"
                >
                  <FolderMinus className="w-3.5 h-3.5" />
                  {isDe ? "Aus Projekt entfernen" : "Remove from project"}
                </button>
              </div>
            )}
          </div>
        )}

        {/* Bulk Delete Button */}
        <button
          type="button"
          data-testid="batch-delete-btn"
          onClick={() => setIsDeleteConfirmOpen(true)}
          className="flex items-center gap-1.5 bg-red-950/80 hover:bg-red-900 text-red-300 border border-red-800 px-3 py-1.5 transition-colors uppercase tracking-wider text-[11px]"
        >
          <Trash2 className="w-3.5 h-3.5" />
          <span>{isDe ? "Löschen" : "Delete"}</span>
        </button>
      </div>

      {/* Bulk Delete Confirmation Dialog */}
      {isDeleteConfirmOpen && (
        <div
          data-testid="batch-delete-dialog"
          className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 font-sans"
        >
          <div className="bg-white border-2 border-black max-w-md w-full p-6 shadow-2xl">
            <div className="flex items-center gap-3 mb-4 text-red-600">
              <AlertTriangle className="w-6 h-6 shrink-0" />
              <h3 className="font-display text-lg font-bold text-black">
                {isDe
                  ? `${count} Beleg${count === 1 ? "" : "e"} wirklich löschen?`
                  : `Delete ${count} receipt${count === 1 ? "" : "s"} permanently?`}
              </h3>
            </div>
            <p className="text-xs text-[#475569] mb-6">
              {isDe
                ? `Diese Aktion entfernt die ${count} ausgewählten Belege unwiderruflich aus dem lokalen Speicher.`
                : `This action will permanently remove the ${count} selected receipts from local storage.`}
            </p>
            <div className="flex items-center justify-end gap-3 font-mono text-xs uppercase tracking-caps">
              <button
                type="button"
                onClick={() => setIsDeleteConfirmOpen(false)}
                className="px-4 py-2 border border-[#CBD5E1] bg-white hover:border-black text-black"
              >
                {isDe ? "Abbrechen" : "Cancel"}
              </button>
              <button
                type="button"
                data-testid="batch-delete-confirm-action"
                onClick={handleConfirmDelete}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-bold"
              >
                {isDe ? "Endgültig löschen" : "Delete Permanently"}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
