"use client";

import React, { useState } from "react";
import { useI18n } from "@/lib/i18n/context";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import {
  FileSpreadsheet,
  FileText,
  FileDown,
  Trash2,
  Lock,
} from "lucide-react";
import { apiFetch } from "@/lib/csrf/client";
import { taxTotalsByRate } from "./receiptFormat";

interface ExportBarProps {
  receipts: ProcessedReceipt[];
  isPro: boolean;
  onClearAll?: () => void;
  onOpenPaywall: () => void;
  /** View-only mode: hides the destructive "Clear All" action */
  readOnly?: boolean;
}

export function ExportBar({
  receipts,
  isPro,
  onClearAll,
  onOpenPaywall,
  readOnly = false,
}: ExportBarProps) {
  const { t, language } = useI18n();
  const isDe = language === "de";
  const [isExportingExcel, setIsExportingExcel] = useState(false);
  const [isExportingCsv, setIsExportingCsv] = useState(false);
  const [isExportingPdf, setIsExportingPdf] = useState(false);

  // Totals Calculations
  const totalGross = receipts.reduce((acc, r) => acc + (r.totalAmount?.value || 0), 0);
  const taxTotals = taxTotalsByRate(receipts);
  const totalNet = receipts.reduce((acc, r) => {
    const rTax = (r.taxBreakdown || []).reduce((s, tx) => s + (tx.taxAmount || 0), 0);
    const net = r.netAmount ?? ((r.totalAmount?.value || 0) - rTax);
    return acc + (net || 0);
  }, 0);

  const requirePro = (): boolean => {
    if (isPro) return true;
    onOpenPaywall();
    return false;
  };

  const handleExportExcel = async () => {
    if (receipts.length === 0) return;
    if (!requirePro()) return;
    try {
      setIsExportingExcel(true);
      const res = await apiFetch("/api/export/excel", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ receipts, locale: language }),
      });

      if (res.status === 401 || res.status === 403) {
        onOpenPaywall();
        return;
      }
      if (!res.ok) throw new Error("Excel export failed");

      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = isDe
        ? `Belege_Export_${new Date().toISOString().split("T")[0]}.xlsx`
        : `Receipts_Export_${new Date().toISOString().split("T")[0]}.xlsx`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    } catch (err) {
      console.error(err);
      alert(isDe ? "Fehler beim Herunterladen der Excel-Datei." : "Failed to download Excel file.");
    } finally {
      setIsExportingExcel(false);
    }
  };

  const handleExportCsv = async () => {
    if (receipts.length === 0) return;
    if (!requirePro()) return;
    try {
      setIsExportingCsv(true);
      const res = await apiFetch("/api/export/csv", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ receipts, locale: language }),
      });

      if (res.status === 401 || res.status === 403) {
        onOpenPaywall();
        return;
      }
      if (!res.ok) throw new Error("CSV export failed");

      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = isDe
        ? `Belege_${new Date().toISOString().split("T")[0]}.csv`
        : `Receipts_${new Date().toISOString().split("T")[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    } catch (err) {
      console.error(err);
      alert(isDe ? "Fehler beim Herunterladen der CSV-Datei." : "Failed to download CSV file.");
    } finally {
      setIsExportingCsv(false);
    }
  };

  const handleExportPdf = async () => {
    if (receipts.length === 0) return;
    if (!requirePro()) return;
    try {
      setIsExportingPdf(true);
      const res = await apiFetch("/api/export/pdf", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ receipts, locale: language }),
      });

      if (res.status === 401 || res.status === 403) {
        onOpenPaywall();
        return;
      }
      if (!res.ok) throw new Error("PDF export failed");

      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = isDe
        ? `Belege_Export_${new Date().toISOString().split("T")[0]}.pdf`
        : `Receipts_Export_${new Date().toISOString().split("T")[0]}.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    } catch (err) {
      console.error(err);
      alert(isDe ? "Fehler beim Herunterladen der PDF-Datei." : "Failed to download PDF file.");
    } finally {
      setIsExportingPdf(false);
    }
  };

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

  return (
    <div className="mb-6 bg-white border border-[#E2E8F0] p-5 font-sans">
      <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6">
        {/* Live Totals Card */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 w-full lg:w-auto">
          <div className="p-3 bg-[#F8FAFC] border border-[#E2E8F0]">
            <span className="font-mono text-[10px] uppercase tracking-caps text-[#64748B] block">
              {t.dashboard?.countLabel || (isDe ? "ANZAHL BELEGE" : "RECEIPT COUNT")}
            </span>
            <span className="font-display text-xl font-bold text-black">
              {receipts.length}
            </span>
          </div>

          <div className="p-3 bg-[#F8FAFC] border border-[#E2E8F0]">
            <span className="font-mono text-[10px] uppercase tracking-caps text-[#64748B] block">
              {t.dashboard?.totalNet || (isDe ? "NETTO GESAMT" : "TOTAL NET")}
            </span>
            <span className="font-mono text-base font-bold text-black">
              {totalNet.toFixed(2)} €
            </span>
          </div>

          <div className="p-3 bg-[#F8FAFC] border border-[#E2E8F0]">
            <span className="font-mono text-[10px] uppercase tracking-caps text-[#64748B] block">
              {isDe ? "MWST" : "TAX"}
            </span>
            <span className="font-mono text-xs font-semibold text-[#475569]">
              {taxTotals.length === 0
                ? "—"
                : taxTotals
                    .map(
                      (row) =>
                        `${Number.isInteger(row.rate) ? row.rate : row.rate.toFixed(1)}%: ${row.amount.toFixed(2)}€`
                    )
                    .join(" · ")}
            </span>
          </div>

          <div className="p-3 bg-[#EEF4FC] border border-[#E2E8F0]">
            <span className="font-mono text-[10px] uppercase tracking-caps text-black block font-semibold">
              {t.dashboard?.totalGross || (isDe ? "BRUTTO GESAMT" : "TOTAL GROSS")}
            </span>
            <span className="font-mono text-base font-bold text-black">
              {totalGross.toFixed(2)} €
            </span>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex flex-wrap items-center gap-3 w-full lg:w-auto justify-end">
          {/* Clear All */}
          {!readOnly && onClearAll && (
            <button
              onClick={onClearAll}
              className="px-3 py-2 text-xs font-mono uppercase tracking-caps text-red-600 hover:bg-red-50 border border-transparent hover:border-red-200 transition-colors flex items-center gap-1.5"
            >
              <Trash2 className="h-3.5 w-3.5" />
              <span>{t.dashboard?.btnClearAll || (isDe ? "Leeren" : "Clear All")}</span>
            </button>
          )}

          {/* CSV Export Button */}
          <button
            onClick={handleExportCsv}
            disabled={isExportingCsv}
            className="px-4 py-2.5 bg-white border border-black text-black font-mono text-xs uppercase tracking-caps hover:bg-[#F8FAFC] transition-colors flex items-center gap-2 disabled:opacity-50"
          >
            {isPro ? <FileText className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
            <span>{t.dashboard?.btnExportCsv || (isDe ? "CSV EXPORT" : "EXPORT CSV")}</span>
          </button>

          {/* PDF Report Button */}
          <button
            onClick={handleExportPdf}
            disabled={isExportingPdf}
            className="px-4 py-2.5 bg-white border border-black text-black font-mono text-xs uppercase tracking-caps hover:bg-[#F8FAFC] transition-colors flex items-center gap-2 disabled:opacity-50"
          >
            {isPro ? <FileDown className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
            <span>{t.dashboard?.btnExportPdf || (isDe ? "PDF EXPORT" : "EXPORT PDF")}</span>
          </button>

          {/* Primary Dual-Sheet Excel Button */}
          <button
            onClick={handleExportExcel}
            disabled={isExportingExcel}
            className="px-5 py-2.5 bg-black text-white font-mono text-xs uppercase tracking-caps hover:bg-[#334155] transition-colors flex items-center gap-2 font-medium disabled:opacity-50"
          >
            {isPro ? <FileSpreadsheet className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
            <span>{t.dashboard?.btnExportExcel || (isDe ? "EXCEL EXPORT (.XLSX)" : "EXPORT EXCEL (.XLSX)")}</span>
          </button>
        </div>
      </div>
    </div>
  );
}
