"use client";

import * as React from "react";
import { FormState, Totals } from "../types";
import { PRICING } from "../constants";
import { AnimatedNumber } from "./AnimatedNumber";

import { ConceptAutomation } from "../../Landing/ConceptIllustrations";
import { Download, Share2, RefreshCw } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
// EstimationPDF will be imported dynamically where used or inside the and client-side block
import IconWhite from "../../../assets/logo/Icon White Transparent.png";
import LogoBlack from "../../../assets/logo/Logo Black Transparent.png";

// PDF components removed from top-level dynamic import to fix ESM resolution issues in Next.js 16/Webpack

interface PriceCalculationProps {
  state: FormState;
  totals: Totals;
  isClient: boolean;
  _qrCodeData: string;
  onShare?: () => void;
}

export function PriceCalculation({
  state,
  totals,
  isClient,
  _qrCodeData,
  onShare,
}: PriceCalculationProps) {
  const {
    totalPrice,
    monthlyPrice,
    totalPagesCount,
    totalFeatures,
    totalFunctions,
    totalApis,
    languagesCount,
  } = totals;
  const totalPages = totalPagesCount;

  const [pdfLoading, setPdfLoading] = React.useState(false);

  const handleDownload = async () => {
    if (pdfLoading) return;

    setPdfLoading(true);

    try {
      const { LocalEstimationPDF } = await import("../pdf/LocalEstimationPDF");
      const doc = (
        <LocalEstimationPDF
          state={state}
          totalPrice={totalPrice}
          monthlyPrice={monthlyPrice}
          totalPagesCount={totalPagesCount}
          pricing={PRICING}
          headerIcon={
            typeof IconWhite === "string" ? IconWhite : (IconWhite as any).src
          }
          footerLogo={
            typeof LogoBlack === "string" ? LogoBlack : (LogoBlack as any).src
          }
          qrCodeData={_qrCodeData}
        />
      );

      const { pdf } = await import("@react-pdf/renderer");

      // Minimum loading time of 2 seconds for better UX
      const [blob] = await Promise.all([
        pdf(doc).toBlob(),
        new Promise((resolve) => setTimeout(resolve, 2000)),
      ]);

      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `kalkulation-${state.name.toLowerCase().replace(/\s+/g, "-") || "projekt"}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error("PDF generation failed:", error);
    } finally {
      setPdfLoading(false);
    }
  };

  return (
    <div className="lg:col-span-4 lg:sticky lg:top-32 self-start z-30">
      <div className="bg-slate-50 border border-slate-100 rounded-2xl p-5 space-y-4">
        <div className="space-y-4">
          {state.projectType === "website" ? (
            <>
              <div className="space-y-4 overflow-y-auto pr-2 hide-scrollbar max-h-[120px]">
                {totalPages > 0 && (
                  <div className="flex justify-between items-center text-sm">
                    <span className="text-slate-500">{totalPages}x Seite</span>
                    <span className="font-medium text-slate-900">
                      {(totalPages * PRICING.PAGE).toLocaleString()} €
                    </span>
                  </div>
                )}
                {totalFeatures > 0 && (
                  <div className="flex justify-between items-center text-sm">
                    <span className="text-slate-500">
                      {totalFeatures}x System-Modul
                    </span>
                    <span className="font-medium text-slate-900">
                      {(totalFeatures * PRICING.FEATURE).toLocaleString()} €
                    </span>
                  </div>
                )}
                {totalFunctions > 0 && (
                  <div className="flex justify-between items-center text-sm">
                    <span className="text-slate-500">
                      {totalFunctions}x Logik-Funktion
                    </span>
                    <span className="font-medium text-slate-900">
                      {(totalFunctions * PRICING.FUNCTION).toLocaleString()} €
                    </span>
                  </div>
                )}
                {totalApis > 0 && (
                  <div className="flex justify-between items-center text-sm">
                    <span className="text-slate-500">
                      {totalApis}x API Sync
                    </span>
                    <span className="font-medium text-slate-900">
                      {(totalApis * PRICING.API_INTEGRATION).toLocaleString()} €
                    </span>
                  </div>
                )}
                {state.cmsSetup && (
                  <div className="flex justify-between items-center text-sm">
                    <span className="text-slate-500">Inhalts-Verwaltung</span>
                    <span className="font-medium text-slate-900">
                      {(
                        Math.max(1, totalFeatures) *
                        PRICING.CMS_CONNECTION_PER_FEATURE
                      ).toLocaleString()}{" "}
                      €
                    </span>
                  </div>
                )}
                {state.newDatasets > 0 && (
                  <div className="flex justify-between items-center text-sm">
                    <span className="text-slate-500">
                      {state.newDatasets}x Inhalte einpflegen
                    </span>
                    <span className="font-medium text-slate-900">
                      {(
                        state.newDatasets * PRICING.NEW_DATASET
                      ).toLocaleString()}{" "}
                      €
                    </span>
                  </div>
                )}
                {languagesCount > 1 && (
                  <div className="flex justify-between items-center text-sm text-slate-900 font-bold pt-2 border-t border-slate-100">
                    <span className="text-slate-500">
                      Mehrsprachigkeit ({languagesCount}x)
                    </span>
                    <span>
                      +
                      {(
                        totalPrice -
                        totalPrice / (1 + (languagesCount - 1) * 0.2)
                      ).toLocaleString()}{" "}
                      €
                    </span>
                  </div>
                )}
              </div>
              <div className="pt-4 space-y-2">
                <div className="flex justify-between items-end">
                  <span className="text-lg font-bold text-slate-900">
                    Gesamt
                  </span>
                  <div className="text-right">
                    <div className="text-2xl font-bold tracking-tighter text-slate-900">
                      <AnimatedNumber value={totalPrice} /> €
                    </div>
                  </div>
                </div>
              </div>
              <div className="pt-4 border-t border-slate-200 space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-slate-600 font-medium text-sm">
                    Sorglos Betrieb (Hosting + Support)
                  </span>
                  <span className="text-base font-bold text-slate-900">
                    {(monthlyPrice * 12).toLocaleString()} € / Jahr
                  </span>
                </div>
              </div>

              <div className="pt-4 space-y-4">
                {isClient && (
                  <button
                    type="button"
                    disabled={pdfLoading}
                    onClick={handleDownload}
                    className="w-full h-14 rounded-full border border-slate-200 text-slate-900 font-bold text-sm uppercase tracking-widest hover:bg-white hover:border-slate-900 transition-all focus:outline-none overflow-hidden relative"
                  >
                    <AnimatePresence mode="wait">
                      {pdfLoading ? (
                        <motion.div
                          key="loading"
                          initial={{ opacity: 0 }}
                          animate={{ opacity: 1 }}
                          exit={{ opacity: 0 }}
                          className="absolute inset-0 flex items-center justify-center bg-white"
                        >
                          <motion.div
                            className="absolute bottom-0 left-0 h-1 bg-slate-900"
                            initial={{ width: "0%" }}
                            animate={{ width: "100%" }}
                            transition={{ duration: 2, ease: "easeInOut" }}
                          />
                          <span className="flex items-center gap-2">
                            <RefreshCw className="animate-spin" size={16} />
                            PDF wird erstellt...
                          </span>
                        </motion.div>
                      ) : (
                        <motion.div
                          key="idle"
                          initial={{ opacity: 0 }}
                          animate={{ opacity: 1 }}
                          exit={{ opacity: 0 }}
                          className="flex items-center justify-center gap-3"
                        >
                          <Download size={18} />
                          <span>Als PDF speichern</span>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </button>
                )}

                {onShare && (
                  <button
                    type="button"
                    onClick={onShare}
                    className="w-full flex items-center justify-center gap-3 rounded-full bg-slate-900 text-white font-bold text-sm uppercase tracking-widest hover:bg-slate-800 transition-all focus:outline-none px-6 py-3"
                  >
                    <Share2 size={18} />
                    <span>Teilen</span>
                  </button>
                )}
              </div>
            </>
          ) : (
            <div className="space-y-6">
              <div className="py-6 text-center space-y-4">
                <div className="w-16 h-16 bg-white rounded-full flex items-center justify-center mx-auto border border-slate-100">
                  <ConceptAutomation className="w-10 h-10 text-black" />
                </div>
                <div className="space-y-1">
                  <p className="text-slate-600 text-xs leading-relaxed">
                    Web Apps werden nach Aufwand abgerechnet.
                  </p>
                  <p className="text-2xl font-bold text-slate-900">
                    {PRICING.APP_HOURLY} €{" "}
                    <span className="text-base text-slate-400 font-normal">
                      / Std.
                    </span>
                  </p>
                </div>
              </div>
              {onShare && (
                <button
                  type="button"
                  onClick={onShare}
                  className="w-full flex items-center justify-center gap-3 px-6 py-3 rounded-full bg-slate-900 text-white font-bold text-sm uppercase tracking-widest hover:bg-slate-800 transition-all focus:outline-none"
                >
                  <Share2 size={18} />
                  <span>Teilen</span>
                </button>
              )}
            </div>
          )}
        </div>
        <p className="text-[10px] leading-relaxed text-slate-400 italic text-center">
          Ein verbindliches Angebot erstelle ich nach einem persönlichen
          Gespräch.
        </p>
      </div>
    </div>
  );
}
