import { useState, useMemo } from "react";
import { Radio, ChevronDown, ChevronUp, Zap, ZapOff } from "lucide-react";
import type { MqttData, MqttEntity } from "../api";

interface Props {
  data: MqttData;
}

export default function MqttCard({ data }: Props) {
  const [expanded, setExpanded] = useState(false);
  const [filter, setFilter] = useState<string | null>(null);

  // Group entities by category
  const grouped = useMemo(() => {
    const map: Record<string, MqttEntity[]> = {};
    for (const e of data.entities) {
      const cat = e.category || "other";
      if (!map[cat]) map[cat] = [];
      map[cat].push(e);
    }
    return map;
  }, [data.entities]);

  const categories = Object.keys(grouped).sort();
  const filtered = filter ? grouped[filter] || [] : data.entities;
  const shown = expanded ? filtered : filtered.slice(0, 8);

  return (
    <div className="deck-card p-5 animate-fade-in" data-accent="iris">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <Radio className="w-4 h-4 text-iris" />
          <h3 className="text-sm font-semibold text-base-900">MQTT</h3>
          <span className="tag border-iris/30 text-iris bg-iris/5">
            {data.entities.length}
          </span>
        </div>

        <div className="flex items-center gap-2">
          {data.connected ? (
            <Zap className="w-3.5 h-3.5 text-iris" />
          ) : (
            <ZapOff className="w-3.5 h-3.5 text-base-500" />
          )}
          <span
            className={`text-[10px] font-mono font-medium ${
              data.connected ? "text-mint" : "text-cherry"
            }`}
          >
            {data.connected ? "Verbunden" : "Getrennt"}
          </span>
        </div>
      </div>

      {/* Category filter tabs */}
      {categories.length > 1 && (
        <div className="flex gap-1 mb-4 flex-wrap">
          <button
            onClick={() => setFilter(null)}
            className={`tab-btn ${filter === null ? "active" : ""}`}
          >
            Alle
          </button>
          {categories.map((cat) => (
            <button
              key={cat}
              onClick={() => setFilter(filter === cat ? null : cat)}
              className={`tab-btn ${filter === cat ? "active" : ""} flex items-center gap-1.5`}
            >
              {cat}
              <span
                className={`text-[10px] font-bold ${
                  filter === cat ? "text-gold" : "text-base-500"
                }`}
              >
                {grouped[cat].length}
              </span>
            </button>
          ))}
        </div>
      )}

      {/* Entity list */}
      {data.entities.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-8 text-base-500">
          <Radio className="w-8 h-8 mb-2 opacity-20" />
          <p className="text-xs font-mono">
            {data.connected
              ? "Warte auf Nachrichten..."
              : "Nicht konfiguriert"}
          </p>
        </div>
      ) : (
        <div className="space-y-px max-h-80 overflow-y-auto">
          {shown.map((entity) => (
            <EntityRow key={entity.topic} entity={entity} />
          ))}
        </div>
      )}

      {/* Expand/collapse */}
      {filtered.length > 8 && (
        <button
          onClick={() => setExpanded(!expanded)}
          className="mt-3 w-full flex items-center justify-center gap-1.5 text-[10px] font-mono text-base-500 hover:text-base-700 transition-colors py-1.5"
        >
          {expanded ? (
            <>
              <ChevronUp className="w-3 h-3" />
              Weniger anzeigen
            </>
          ) : (
            <>
              <ChevronDown className="w-3 h-3" />
              Alle {filtered.length} anzeigen
            </>
          )}
        </button>
      )}
    </div>
  );
}

function EntityRow({ entity }: { entity: MqttEntity }) {
  const age = Math.round(Date.now() / 1000 - entity.timestamp);
  const ageStr =
    age < 60
      ? `${age}s`
      : age < 3600
        ? `${Math.floor(age / 60)}m`
        : `${Math.floor(age / 3600)}h`;

  const displayValue = formatValue(entity.value);
  const isNumeric = typeof entity.value === "number";

  return (
    <div className="flex items-center justify-between gap-3 px-3 py-2 bg-base-100 border-l-2 border-base-300 hover:border-iris transition-colors group">
      <div className="flex-1 min-w-0">
        <p className="text-xs text-base-700 truncate">{entity.name}</p>
        <p className="text-[9px] text-base-500 truncate font-mono mt-0.5">
          {entity.topic}
        </p>
      </div>

      <div className="flex items-center gap-2 shrink-0">
        <span
          className={`text-sm font-mono font-medium ${
            isNumeric ? "text-iris data-value" : "text-base-800"
          }`}
        >
          {displayValue}
        </span>
        {(entity as any).unit && (
          <span className="text-[10px] font-mono text-base-500">
            {(entity as any).unit}
          </span>
        )}
        <span className="text-[9px] font-mono text-base-500 w-6 text-right opacity-50">
          {ageStr}
        </span>
      </div>
    </div>
  );
}

function formatValue(value: any): string {
  if (value === null || value === undefined) return "\u2014";
  if (typeof value === "boolean") return value ? "ON" : "OFF";
  if (typeof value === "number") {
    return Number.isInteger(value) ? value.toString() : value.toFixed(1);
  }
  if (typeof value === "object") {
    return JSON.stringify(value).slice(0, 40);
  }
  const str = String(value);
  if (str === "on" || str === "ON") return "ON";
  if (str === "off" || str === "OFF") return "OFF";
  if (str === "online") return "Online";
  if (str === "offline") return "Offline";
  return str.length > 30 ? str.slice(0, 30) + "\u2026" : str;
}
