"use client";

import React, { useRef, useState } from "react";
import { UploadCloud, Scan, Camera, ShieldCheck, FileSpreadsheet, Layers, X } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { RECEIPT_CAMERA_ACCEPT, RECEIPT_FILE_ACCEPT } from "@/lib/ingest/acceptedTypes";
import { MAX_UPLOAD_MB } from "@/lib/limits";

export interface BatchUploadDropzoneProps {
  onFilesSelected: (files: File[]) => void;
  isProcessing?: boolean;
  disabled?: boolean;
  className?: string;
  compact?: boolean;
  quotaInfo?: {
    isPro: boolean;
    scanCount: number;
    scanLimit: number;
    launchBonus?: boolean;
  };
  onOpenUpgrade?: () => void;
  highlight?: boolean;
  onHighlightDismiss?: () => void;
}

export function BatchUploadDropzone({
  onFilesSelected,
  isProcessing = false,
  disabled = false,
  className = "",
  compact = false,
  quotaInfo,
  onOpenUpgrade,
  highlight = false,
  onHighlightDismiss,
}: BatchUploadDropzoneProps) {
  const { language } = useI18n();
  const isDe = language === "de";
  const [isDragOver, setIsDragOver] = useState(false);
  const dragCounterRef = useRef(0);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const cameraInputRef = useRef<HTMLInputElement>(null);

  const handleDragEnter = (e: React.DragEvent) => {
    if (disabled) return;
    e.preventDefault();
    e.stopPropagation();
    dragCounterRef.current += 1;
    if (dragCounterRef.current === 1) {
      setIsDragOver(true);
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    if (disabled) return;
    e.preventDefault();
    e.stopPropagation();
    if (e.dataTransfer) {
      e.dataTransfer.dropEffect = "copy";
    }
  };

  const handleDragLeave = (e: React.DragEvent) => {
    if (disabled) return;
    e.preventDefault();
    e.stopPropagation();
    dragCounterRef.current -= 1;
    if (dragCounterRef.current <= 0) {
      dragCounterRef.current = 0;
      setIsDragOver(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    if (disabled) return;
    e.preventDefault();
    e.stopPropagation();
    dragCounterRef.current = 0;
    setIsDragOver(false);

    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      const filesArray = Array.from(e.dataTransfer.files);
      onFilesSelected(filesArray);
    }
  };

  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const filesArray = Array.from(e.target.files);
      onFilesSelected(filesArray);
    }
    if (fileInputRef.current) fileInputRef.current.value = "";
    if (cameraInputRef.current) cameraInputRef.current.value = "";
  };

  return (
    <div
      data-testid="batch-upload-dropzone"
      className={`bg-white border border-[#E2E8F0] p-5 sm:p-7 relative transition-all font-sans ${className} ${
        highlight ? "ring-2 ring-emerald-500 ring-offset-2 animate-pulse" : ""
      }`}
    >
      {/* First-Scan Guide Banner */}
      {highlight && (
        <div className="flex items-center justify-between gap-3 mb-4 p-3 bg-emerald-50 border border-emerald-300">
          <div className="flex items-center gap-2">
            <UploadCloud className="w-4 h-4 text-emerald-700 shrink-0" />
            <span className="text-xs font-semibold text-emerald-900">
              {isDe
                ? "Willkommen! Ziehe deinen ersten Beleg hierher oder klicke auf „Dateien auswählen“."
                : "Welcome! Drag your first receipt here or click “Browse Files”."}
            </span>
          </div>
          <button
            type="button"
            onClick={onHighlightDismiss}
            aria-label={isDe ? "Hinweis schließen" : "Dismiss hint"}
            className="shrink-0 text-emerald-700 hover:text-emerald-900"
          >
            <X className="w-3.5 h-3.5" />
          </button>
        </div>
      )}

      {/* Sharp 0px Corner Accents */}
      <div className="absolute top-0 left-0 w-2.5 h-2.5 border-t-2 border-l-2 border-black pointer-events-none"></div>
      <div className="absolute top-0 right-0 w-2.5 h-2.5 border-t-2 border-r-2 border-black pointer-events-none"></div>
      <div className="absolute bottom-0 left-0 w-2.5 h-2.5 border-b-2 border-l-2 border-black pointer-events-none"></div>
      <div className="absolute bottom-0 right-0 w-2.5 h-2.5 border-b-2 border-r-2 border-black pointer-events-none"></div>

      {/* Top Architectural System Header */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-4 pb-3 border-b border-[#E2E8F0]">
        <div className="flex items-center gap-2">
          <Scan className="w-4 h-4 text-black" />
          <span className="font-mono text-xs uppercase tracking-caps font-semibold text-black">
            {isDe ? "Belege hochladen" : "Upload receipts"}
          </span>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {quotaInfo && (
            <div
              onClick={(e) => {
                if (!quotaInfo.isPro && onOpenUpgrade) {
                  e.stopPropagation();
                  onOpenUpgrade();
                }
              }}
              className={`font-mono text-[10px] px-2.5 py-0.5 border uppercase tracking-wider font-semibold flex items-center gap-1.5 transition-colors ${
                quotaInfo.isPro
                  ? "bg-emerald-50 text-emerald-800 border-emerald-300"
                  : quotaInfo.scanCount >= quotaInfo.scanLimit
                  ? "bg-red-50 text-red-800 border-red-300 cursor-pointer hover:bg-red-100"
                  : "bg-[#EEF4FC] text-black border-[#E2E8F0] cursor-pointer hover:border-black"
              }`}
            >
              <span
                className={`w-1.5 h-1.5 rounded-full ${
                  quotaInfo.isPro
                    ? "bg-emerald-500"
                    : quotaInfo.scanCount >= quotaInfo.scanLimit
                    ? "bg-red-500"
                    : "bg-black"
                }`}
              ></span>
              <span>
                {quotaInfo.isPro
                  ? isDe
                    ? "PRO: UNBEGRENZT"
                    : "PRO: UNLIMITED"
                  : isDe
                  ? `KONTINGENT: ${quotaInfo.scanCount}/${quotaInfo.scanLimit} SCANS`
                  : `QUOTA: ${quotaInfo.scanCount}/${quotaInfo.scanLimit} SCANS`}
              </span>
            </div>
          )}
          <span className="font-mono text-[10px] bg-[#EEF4FC] text-black border border-[#E2E8F0] px-2 py-0.5 uppercase tracking-wider font-semibold">
            PDF • PNG • JPG • WEBP • HEIC
          </span>
          <span className="font-mono text-[10px] bg-[#F8FAFC] text-[#64748B] border border-[#E2E8F0] px-2 py-0.5 uppercase tracking-wider hidden sm:inline">
            Max. {MAX_UPLOAD_MB} MB
          </span>
        </div>
      </div>

      {/* Interactive Active Drop Area */}
      <div
        onDragEnter={handleDragEnter}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={() => !disabled && fileInputRef.current?.click()}
        className={`relative border-2 border-dashed ${
          compact ? "p-4 sm:p-6" : "p-6 sm:p-10"
        } text-center cursor-pointer transition-all overflow-hidden focus-within:ring-2 focus-within:ring-black ${
          isDragOver
            ? "border-black bg-[#EEF4FC]"
            : isProcessing
            ? "border-black bg-[#F8FAFC]"
            : "border-[#94A3B8] bg-[#F8FAFC] hover:border-black hover:bg-white"
        } ${disabled ? "opacity-60 cursor-not-allowed" : ""}`}
      >
        {/* Animated Laser Scanline when Processing or Dragging Over */}
        {(isProcessing || isDragOver) && <div className="animate-scanline"></div>}

        {/* Hidden File Inputs */}
        <input
          type="file"
          ref={fileInputRef}
          onChange={handleFileInputChange}
          accept={RECEIPT_FILE_ACCEPT}
          multiple
          disabled={disabled}
          className="hidden"
          data-testid="batch-file-input"
        />
        <input
          type="file"
          ref={cameraInputRef}
          onChange={handleFileInputChange}
          accept={RECEIPT_CAMERA_ACCEPT}
          capture="environment"
          disabled={disabled}
          className="hidden"
          data-testid="batch-camera-input"
        />

        <div className="flex flex-col items-center justify-center space-y-4 max-w-xl mx-auto">
          <div className="w-12 h-12 sm:w-14 sm:h-14 bg-black text-white flex items-center justify-center shadow-md">
            <UploadCloud className="w-6 h-6 sm:w-7 sm:h-7 text-white" />
          </div>

          <div className="space-y-1 text-center">
            <h3 className="font-display text-base sm:text-lg font-bold text-black">
              {isProcessing
                ? isDe
                  ? "Belege werden verarbeitet..."
                  : "Processing receipts..."
                : isDe
                ? "Mehrere Belege hierher ziehen oder durchsuchen"
                : "Drop multiple receipts here or browse"}
            </h3>
            <p className="text-xs text-[#64748B] font-sans max-w-md mx-auto">
              {isDe
                ? "Unterstützt PDF (auch mehrseitig), PNG, JPEG und WebP. Automatische Duplikaterkennung & deterministische Summenprüfung."
                : "Supports multi-page PDFs, PNG, JPEG, and WebP. Automatic duplicate check & deterministic math verification."}
            </p>
          </div>

          {/* Action Buttons */}
          <div className="flex flex-wrap items-center justify-center gap-3 pt-1">
            <button
              type="button"
              disabled={disabled}
              onClick={(e) => {
                e.stopPropagation();
                fileInputRef.current?.click();
              }}
              className="px-4 py-2 bg-black text-white font-mono text-xs uppercase tracking-caps hover:bg-[#334155] transition-colors font-medium flex items-center gap-2 disabled:opacity-50"
            >
              <UploadCloud className="w-3.5 h-3.5" />
              <span>{isDe ? "Dateien auswählen" : "Browse Files"}</span>
            </button>

            <button
              type="button"
              disabled={disabled}
              onClick={(e) => {
                e.stopPropagation();
                cameraInputRef.current?.click();
              }}
              className="px-4 py-2 bg-white border border-black text-black font-mono text-xs uppercase tracking-caps hover:bg-[#F8FAFC] transition-colors flex items-center gap-2 font-medium disabled:opacity-50"
            >
              <Camera className="w-3.5 h-3.5" />
              <span>{isDe ? "Kamera" : "Camera"}</span>
            </button>
          </div>
        </div>
      </div>

      {/* Footer Info Strip */}
      <div className="mt-4 pt-3 border-t border-[#E2E8F0] flex flex-wrap items-center justify-between gap-3 text-xs text-[#64748B] font-mono">
        <div className="flex items-center gap-1.5">
          <ShieldCheck className="w-3.5 h-3.5 text-black" />
          <span className="text-[11px]">
            {isDe ? "Sicher gespeichert • Deterministische Prüfung" : "Stored Securely • Deterministic Verification"}
          </span>
        </div>
        <div className="flex items-center gap-1.5 text-[11px] text-emerald-700 bg-emerald-50 px-2 py-0.5 border border-emerald-200">
          <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-pulse"></span>
          <span>{isDe ? "Multi-Worker Pipeline Aktiv" : "Multi-Worker Pipeline Active"}</span>
        </div>
      </div>
    </div>
  );
}
