"use client";

import { useState } from "react";
import { Download, Trash2, MousePointerClick, Square, PenTool, Loader2, Sparkles } from "lucide-react";
import { Button } from "@/shared/components/ui/button";
// Direct buttons instead of dropdown — works reliably on mobile + fixed containers
import { Badge } from "@/shared/components/ui/badge";
import { cn } from "@/shared/lib/utils";
import type { SelectedFeature, ExportFormat } from "../types";

export type SelectionMode = "off" | "click" | "rect" | "freehand";

type SelectionToolbarProps = {
  selectedFeatures: SelectedFeature[];
  selectionMode: SelectionMode;
  onSelectionModeChange: (mode: SelectionMode) => void;
  onClearSelection: () => void;
  className?: string;
  /** Hide the enrichment button (e.g. in portal view) */
  hideEnrichment?: boolean;
};

const EXPORT_FORMATS: { id: ExportFormat; label: string }[] = [
  { id: "dxf", label: "AutoCAD DXF (.dxf)" },
  { id: "gpkg", label: "GeoPackage (.gpkg) — cu metadata" },
];

const MODE_BUTTONS: { mode: SelectionMode; icon: typeof MousePointerClick; label: string; tooltip: string }[] = [
  { mode: "click", icon: MousePointerClick, label: "Click", tooltip: "Click pe parcele individuale. ESC sau right-click pentru a iesi." },
  { mode: "rect", icon: Square, label: "Dreptunghi", tooltip: "Trage un dreptunghi pe harta. ESC sau right-click pentru a anula." },
  { mode: "freehand", icon: PenTool, label: "Desen", tooltip: "Click puncte pe harta, dublu-click inchide. ESC sau right-click anuleaza." },
];

export function SelectionToolbar({
  selectedFeatures,
  selectionMode,
  onSelectionModeChange,
  onClearSelection,
  className,
  hideEnrichment,
}: SelectionToolbarProps) {
  const [exporting, setExporting] = useState(false);
  const [enriching, setEnriching] = useState(false);
  const [enrichProgress, setEnrichProgress] = useState("");
  const active = selectionMode !== "off";

  const handleExport = async (format: ExportFormat) => {
    if (selectedFeatures.length === 0) return;
    setExporting(true);
    try {
      const ids = selectedFeatures.map((f) => f.id);
      const resp = await fetch("/api/geoportal/export", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids, format }),
      });
      if (!resp.ok) {
        const errData = await resp.json().catch(() => null);
        const msg = (errData && typeof errData === "object" && "error" in errData)
          ? String((errData as { error: string }).error) : `Export esuat (${resp.status})`;
        alert(msg);
        return;
      }
      const blob = await resp.blob();
      const disposition = resp.headers.get("Content-Disposition");
      let filename = `export.${format}`;
      if (disposition) {
        const match = disposition.match(/filename\*?=(?:UTF-8'')?["']?([^"';\n]+)/i);
        if (match?.[1]) filename = decodeURIComponent(match[1]);
      }
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      alert("Eroare la export");
    } finally {
      setExporting(false);
    }
  };

  return (
    <div className={cn("bg-background/95 backdrop-blur-sm border rounded-lg shadow-lg p-1.5 flex flex-col gap-1.5", className)}>
      {/* Selection mode row */}
      <div className="flex items-center gap-1">
        {MODE_BUTTONS.map((btn) => {
          const Icon = btn.icon;
          const isActive = selectionMode === btn.mode;
          return (
            <Button
              key={btn.mode}
              variant={isActive ? "default" : "ghost"}
              size="sm"
              className="h-7 px-2 text-xs gap-1"
              onClick={() => onSelectionModeChange(isActive ? "off" : btn.mode)}
              title={btn.tooltip}
            >
              <Icon className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">{btn.label}</span>
            </Button>
          );
        })}
      </div>

      {/* Help text when selection active */}
      {active && selectedFeatures.length === 0 && (
        <p className="text-xs text-muted-foreground px-1">
          {selectionMode === "click" && "Click pe parcele pentru a le selecta"}
          {selectionMode === "rect" && "Trage un dreptunghi pe harta"}
          {selectionMode === "freehand" && "Click puncte pe harta, dublu-click pentru a inchide zona"}
        </p>
      )}

      {/* Count + export + clear */}
      {selectedFeatures.length > 0 && (
        <div className="flex items-center gap-1.5">
          <Badge variant="secondary" className="text-xs h-5 px-1.5">
            {selectedFeatures.length} parcele
          </Badge>

          {EXPORT_FORMATS.map((fmt) => (
            <Button
              key={fmt.id}
              variant="ghost"
              size="sm"
              className="h-7 px-2 text-xs gap-1"
              disabled={exporting}
              onClick={() => void handleExport(fmt.id)}
              title={fmt.label}
            >
              {exporting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Download className="h-3.5 w-3.5" />}
              <span className="hidden sm:inline">{fmt.id.toUpperCase()}</span>
            </Button>
          ))}

          {!hideEnrichment && <Button
            variant="ghost" size="sm" className="h-7 px-2 text-xs gap-1"
            disabled={enriching}
            title="Enrichment pentru parcelele selectate. Datele se salveaza permanent in baza de date."
            onClick={async () => {
              setEnriching(true);
              setEnrichProgress("0/" + selectedFeatures.length);
              let done = 0;
              let ok = 0;
              for (const f of selectedFeatures) {
                try {
                  const siruta = String(f.properties.siruta ?? "");
                  const objectId = Number(f.properties.object_id ?? f.id);
                  const r = await fetch("/api/geoportal/enrich", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ siruta, objectId }),
                  });
                  if (r.ok) ok++;
                } catch { /* noop */ }
                done++;
                setEnrichProgress(done + "/" + selectedFeatures.length);
              }
              setEnrichProgress(ok + " parcele imbogatite");
              setTimeout(() => setEnrichProgress(""), 5000);
              setEnriching(false);
            }}
          >
            {enriching ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Sparkles className="h-3.5 w-3.5" />}
            Enrichment
          </Button>}

          <Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={onClearSelection} title="Sterge selectia">
            <Trash2 className="h-3.5 w-3.5" />
          </Button>

          {enrichProgress && (
            <span className="text-xs text-muted-foreground">{enrichProgress}</span>
          )}
        </div>
      )}
    </div>
  );
}
