import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import SearchBar from "../components/SearchBar";
import ConfirmDialog from "../components/ConfirmDialog";

const TIER_OPTIONS = ["", "basic", "small", "mini", "premium", "vip", "custom"];

// All available columns with their defaults
const ALL_COLUMNS = [
  { key: "status", label: "Status", defaultOn: true },
  { key: "name", label: "Name", defaultOn: true, alwaysOn: true },
  { key: "serialNumber", label: "Serial Number", defaultOn: true },
  { key: "location", label: "Location", defaultOn: true },
  { key: "subscrTier", label: "Subscr Tier", defaultOn: true },
  { key: "maxOutputs", label: "Max Outputs", defaultOn: false },
  { key: "hasClock", label: "Has Clock", defaultOn: false },
  { key: "hasBells", label: "Has Bells", defaultOn: false },
  { key: "totalBells", label: "Total Bells", defaultOn: true },
  { key: "bellGuard", label: "Bell Guard", defaultOn: false },
  { key: "warningsOn", label: "Warnings On", defaultOn: false },
  { key: "serialLogLevel", label: "Serial Log Level", defaultOn: false },
  { key: "sdLogLevel", label: "SD Log Level", defaultOn: false },
  { key: "bellOutputs", label: "Bell Outputs", defaultOn: false },
  { key: "hammerTimings", label: "Hammer Timings", defaultOn: false },
  { key: "ringAlertsMaster", label: "Ring Alerts Master", defaultOn: false },
  { key: "totalPlaybacks", label: "Total Playbacks", defaultOn: false },
  { key: "totalHammerStrikes", label: "Total Hammer Strikes", defaultOn: false },
  { key: "totalWarnings", label: "Total Warnings", defaultOn: false },
  { key: "warrantyActive", label: "Warranty Active", defaultOn: false },
  { key: "totalMelodies", label: "Total Melodies", defaultOn: false },
  { key: "assignedUsers", label: "Assigned Users", defaultOn: true },
  { key: "tags", label: "Tags", defaultOn: false },
  { key: "hw_family", label: "HW Family", defaultOn: false },
  { key: "hw_revision", label: "HW Revision", defaultOn: false },
];

function getDefaultVisibleColumns() {
  const saved = localStorage.getItem("deviceListColumns");
  if (saved) {
    try {
      return JSON.parse(saved);
    } catch {
      // ignore
    }
  }
  return ALL_COLUMNS.filter((c) => c.defaultOn).map((c) => c.key);
}

function BoolBadge({ value, yesLabel = "Yes", noLabel = "No" }) {
  return (
    <span
      className="px-2 py-0.5 text-xs rounded-full"
      style={
        value
          ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
          : { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
      }
    >
      {value ? yesLabel : noLabel}
    </span>
  );
}

function isSubscriptionActive(device) {
  const sub = device.device_subscription;
  if (!sub?.subscrStart || !sub?.subscrDuration) return false;
  try {
    const start = parseFirestoreDate(sub.subscrStart);
    if (!start) return false;
    const end = new Date(start.getTime() + sub.subscrDuration * 86400000);
    return end > new Date();
  } catch {
    return false;
  }
}

function isWarrantyActive(device) {
  const stats = device.device_stats;
  if (!stats?.warrantyStart || !stats?.warrantyPeriod) return !!stats?.warrantyActive;
  try {
    const start = parseFirestoreDate(stats.warrantyStart);
    if (!start) return !!stats?.warrantyActive;
    const end = new Date(start.getTime() + stats.warrantyPeriod * 86400000);
    return end > new Date();
  } catch {
    return !!stats?.warrantyActive;
  }
}

function parseFirestoreDate(str) {
  if (!str) return null;
  // Handle format like "22 December 2025 at 16:35:56 UTC+0000"
  const cleaned = str.replace(" at ", " ").replace("UTC+0000", "UTC").replace(/UTC\+(\d{4})/, "UTC");
  const d = new Date(cleaned);
  return isNaN(d.getTime()) ? null : d;
}

export default function DeviceList() {
  const [devices, setDevices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [onlineFilter, setOnlineFilter] = useState("");
  const [tierFilter, setTierFilter] = useState("");
  const [subscrStatusFilter, setSubscrStatusFilter] = useState("");
  const [warrantyStatusFilter, setWarrantyStatusFilter] = useState("");
  const [hasClockFilter, setHasClockFilter] = useState("");
  const [hasBellsFilter, setHasBellsFilter] = useState("");
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [visibleColumns, setVisibleColumns] = useState(getDefaultVisibleColumns);
  const [pageSize, setPageSize] = useState(20);
  const [page, setPage] = useState(1);
  const [showColumnPicker, setShowColumnPicker] = useState(false);
  const [mqttStatusMap, setMqttStatusMap] = useState({});
  const columnPickerRef = useRef(null);
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("devices", "edit");

  // Close column picker on outside click
  useEffect(() => {
    const handleClick = (e) => {
      if (columnPickerRef.current && !columnPickerRef.current.contains(e.target)) {
        setShowColumnPicker(false);
      }
    };
    if (showColumnPicker) {
      document.addEventListener("mousedown", handleClick);
      return () => document.removeEventListener("mousedown", handleClick);
    }
  }, [showColumnPicker]);

  const fetchDevices = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (onlineFilter === "true") params.set("online", "true");
      if (onlineFilter === "false") params.set("online", "false");
      if (tierFilter) params.set("tier", tierFilter);
      const qs = params.toString();
      // Phase 1: load devices from DB immediately
      const data = await api.get(`/devices${qs ? `?${qs}` : ""}`);
      setDevices(data.devices);
      setLoading(false);

      // Phase 2: fetch MQTT status in background and update online indicators
      api.get("/mqtt/status").then((mqttData) => {
        if (mqttData?.devices) {
          const map = {};
          for (const s of mqttData.devices) {
            map[s.device_serial] = s;
          }
          setMqttStatusMap(map);
        }
      }).catch(() => {});
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDevices();
  }, [search, onlineFilter, tierFilter]);

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await api.delete(`/devices/${deleteTarget.id}`);
      setDeleteTarget(null);
      fetchDevices();
    } catch (err) {
      setError(err.message);
      setDeleteTarget(null);
    }
  };

  const toggleColumn = (key) => {
    const col = ALL_COLUMNS.find((c) => c.key === key);
    if (col?.alwaysOn) return;
    setVisibleColumns((prev) => {
      const next = prev.includes(key)
        ? prev.filter((k) => k !== key)
        : [...prev, key];
      localStorage.setItem("deviceListColumns", JSON.stringify(next));
      return next;
    });
  };

  const isVisible = (key) => visibleColumns.includes(key);

  const renderCellValue = (key, device) => {
    const attr = device.device_attributes || {};
    const clock = attr.clockSettings || {};
    const sub = device.device_subscription || {};
    const stats = device.device_stats || {};

    switch (key) {
      case "status": {
        const sn = device.serial_number || device.device_id;
        const mqtt = mqttStatusMap[sn];
        const isOnline = mqtt ? mqtt.online : device.is_Online;
        return (
          <span
            className={`inline-block w-2.5 h-2.5 rounded-full ${isOnline ? "bg-green-500" : ""}`}
            style={!isOnline ? { backgroundColor: "var(--border-primary)" } : undefined}
            title={isOnline ? "Online" : "Offline"}
          />
        );
      }
      case "name":
        return (
          <span className="font-medium" style={{ color: "var(--text-heading)" }}>
            {device.device_name || "Unnamed Device"}
          </span>
        );
      case "serialNumber":
        return <span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>{device.serial_number || device.device_id || "-"}</span>;
      case "location":
        return device.device_location || "-";
      case "subscrTier":
        return (
          <span
            className="px-2 py-0.5 text-xs rounded-full capitalize"
            style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
          >
            {sub.subscrTier || "basic"}
          </span>
        );
      case "maxOutputs":
        return sub.maxOutputs ?? "-";
      case "hasClock":
        return <BoolBadge value={attr.hasClock} />;
      case "hasBells":
        return <BoolBadge value={attr.hasBells} />;
      case "totalBells":
        return attr.totalBells ?? 0;
      case "bellGuard":
        return <BoolBadge value={attr.bellGuardOn} />;
      case "warningsOn":
        return <BoolBadge value={attr.warningsOn} />;
      case "serialLogLevel":
        return attr.serialLogLevel ?? 0;
      case "sdLogLevel":
        return attr.sdLogLevel ?? 0;
      case "bellOutputs":
        return attr.bellOutputs?.length > 0 ? attr.bellOutputs.join(", ") : "-";
      case "hammerTimings":
        return attr.hammerTimings?.length > 0 ? attr.hammerTimings.join(", ") : "-";
      case "ringAlertsMaster":
        return <BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" />;
      case "totalPlaybacks":
        return stats.totalPlaybacks ?? 0;
      case "totalHammerStrikes":
        return stats.totalHammerStrikes ?? 0;
      case "totalWarnings":
        return stats.totalWarningsGiven ?? 0;
      case "warrantyActive":
        return <BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />;
      case "totalMelodies":
        return device.device_melodies_all?.length ?? 0;
      case "assignedUsers": {
        const ul = Array.isArray(device.user_list) ? device.user_list : [];
        return ul.length;
      }
      case "tags": {
        const tagList = Array.isArray(device.tags) ? device.tags : [];
        if (tagList.length === 0) return <span style={{ color: "var(--text-muted)" }}>—</span>;
        return (
          <div className="flex flex-wrap gap-1">
            {tagList.map((t) => (
              <span
                key={t}
                className="px-1.5 py-0.5 text-xs rounded-full"
                style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
              >
                {t}
              </span>
            ))}
          </div>
        );
      }
      case "hw_family":
        return device.hw_family || <span style={{ color: "var(--text-muted)" }}>—</span>;
      case "hw_revision":
        return device.hw_revision || <span style={{ color: "var(--text-muted)" }}>—</span>;
      default:
        return "-";
    }
  };

  // Apply client-side filters
  const filteredDevices = devices.filter((device) => {
    if (subscrStatusFilter === "active" && !isSubscriptionActive(device)) return false;
    if (subscrStatusFilter === "expired" && isSubscriptionActive(device)) return false;
    if (warrantyStatusFilter === "active" && !isWarrantyActive(device)) return false;
    if (warrantyStatusFilter === "expired" && isWarrantyActive(device)) return false;
    if (hasClockFilter === "yes" && !device.device_attributes?.hasClock) return false;
    if (hasClockFilter === "no" && device.device_attributes?.hasClock) return false;
    if (hasBellsFilter === "yes" && !device.device_attributes?.hasBells) return false;
    if (hasBellsFilter === "no" && device.device_attributes?.hasBells) return false;
    return true;
  });

  const totalPages = pageSize > 0 ? Math.ceil(filteredDevices.length / pageSize) : 1;
  const safePage = Math.min(page, Math.max(1, totalPages));
  const pagedDevices = pageSize > 0
    ? filteredDevices.slice((safePage - 1) * pageSize, safePage * pageSize)
    : filteredDevices;

  const activeColumns = ALL_COLUMNS.filter((c) => isVisible(c.key));

  const selectClass = "px-3 py-2 rounded-md text-sm cursor-pointer border";
  const selectStyle = {
    backgroundColor: "var(--bg-card)",
    color: "var(--text-primary)",
    borderColor: "var(--border-primary)",
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>Device Fleet</h1>
        <div className="flex items-center gap-3">
          <span className="text-sm whitespace-nowrap" style={{ color: "var(--text-muted)" }}>
            {filteredDevices.length} {filteredDevices.length === 1 ? "device" : "devices"}
          </span>
          {canEdit && (
            <button
              onClick={() => navigate("/devices/new")}
              className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
            >
              Add Device
            </button>
          )}
        </div>
      </div>

      <div className="mb-4 flex flex-wrap gap-3 items-center">
        <SearchBar
          onSearch={setSearch}
          placeholder="Search by name, location, or serial number..."
          style={{ flex: "1 1 300px", minWidth: 300 }}
        />
        <select value={onlineFilter} onChange={(e) => setOnlineFilter(e.target.value)} className={selectClass} style={selectStyle}>
          <option value="">All Status</option>
          <option value="true">Online</option>
          <option value="false">Offline</option>
        </select>
        <select value={tierFilter} onChange={(e) => setTierFilter(e.target.value)} className={selectClass} style={selectStyle}>
          <option value="">All Tiers</option>
          {TIER_OPTIONS.filter(Boolean).map((t) => (
            <option key={t} value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>
          ))}
        </select>
        <select value={subscrStatusFilter} onChange={(e) => setSubscrStatusFilter(e.target.value)} className={selectClass} style={selectStyle}>
          <option value="">Subscr Status</option>
          <option value="active">Active</option>
          <option value="expired">Expired</option>
        </select>
        <select value={warrantyStatusFilter} onChange={(e) => setWarrantyStatusFilter(e.target.value)} className={selectClass} style={selectStyle}>
          <option value="">Warranty Status</option>
          <option value="active">Active</option>
          <option value="expired">Expired</option>
        </select>
        <select value={hasClockFilter} onChange={(e) => setHasClockFilter(e.target.value)} className={selectClass} style={selectStyle}>
          <option value="">Has Clock</option>
          <option value="yes">Yes</option>
          <option value="no">No</option>
        </select>
        <select value={hasBellsFilter} onChange={(e) => setHasBellsFilter(e.target.value)} className={selectClass} style={selectStyle}>
          <option value="">Has Bells</option>
          <option value="yes">Yes</option>
          <option value="no">No</option>
        </select>

        {/* Column visibility dropdown */}
        <div className="relative" ref={columnPickerRef}>
          <button
            type="button"
            onClick={() => setShowColumnPicker((prev) => !prev)}
            className="px-3 py-2 rounded-md text-sm transition-colors cursor-pointer flex items-center gap-1.5 border"
            style={{
              borderColor: "var(--border-primary)",
              color: "var(--text-secondary)",
            }}
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
            </svg>
            Columns
          </button>
          {showColumnPicker && (
            <div
              className="absolute right-0 top-full mt-1 z-20 rounded-lg shadow-lg py-2 w-52 border max-h-80 overflow-y-auto"
              style={{
                backgroundColor: "var(--bg-card)",
                borderColor: "var(--border-primary)",
              }}
            >
              {ALL_COLUMNS.map((col) => (
                <label
                  key={col.key}
                  className="flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer"
                  style={{
                    color: col.alwaysOn ? "var(--text-muted)" : "var(--text-primary)",
                  }}
                >
                  <input
                    type="checkbox"
                    checked={isVisible(col.key)}
                    onChange={() => toggleColumn(col.key)}
                    disabled={col.alwaysOn}
                    className="h-3.5 w-3.5 rounded cursor-pointer"
                  />
                  {col.label}
                </label>
              ))}
            </div>
          )}
        </div>

        <select
          value={String(pageSize)}
          onChange={(e) => { setPageSize(Number(e.target.value)); setPage(1); }}
          className={selectClass}
          style={selectStyle}
        >
          <option value="10">10 / page</option>
          <option value="20">20 / page</option>
          <option value="50">50 / page</option>
          <option value="0">All</option>
        </select>
      </div>

      {error && (
        <div
          className="text-sm rounded-md p-3 mb-4 border"
          style={{
            backgroundColor: "var(--danger-bg)",
            borderColor: "var(--danger)",
            color: "var(--danger-text)",
          }}
        >
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : filteredDevices.length === 0 ? (
        <div
          className="rounded-lg p-8 text-center text-sm border"
          style={{
            backgroundColor: "var(--bg-card)",
            borderColor: "var(--border-primary)",
            color: "var(--text-muted)",
          }}
        >
          No devices found.
        </div>
      ) : (
        <div
          className="rounded-lg overflow-hidden border"
          style={{
            backgroundColor: "var(--bg-card)",
            borderColor: "var(--border-primary)",
          }}
        >
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
                  {activeColumns.map((col) => (
                    <th
                      key={col.key}
                      className={`px-4 py-3 text-left font-medium ${col.key === "status" ? "w-10" : ""}`}
                      style={{ color: "var(--text-secondary)" }}
                    >
                      {col.key === "status" ? "" : col.label}
                    </th>
                  ))}
                  {canEdit && (
                    <th className="px-4 py-3 text-left font-medium w-24" style={{ color: "var(--text-secondary)" }} />
                  )}
                </tr>
              </thead>
              <tbody>
                {pagedDevices.map((device, index) => (
                  <tr
                    key={device.id}
                    onClick={() => navigate(`/devices/${device.id}`)}
                    className="cursor-pointer transition-colors"
                    style={{ borderBottom: "1px solid var(--border-secondary)", backgroundColor: index % 2 === 1 ? "var(--bg-row-alt)" : "transparent" }}
                    onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "var(--bg-card-hover)")}
                    onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = index % 2 === 1 ? "var(--bg-row-alt)" : "transparent")}
                  >
                    {activeColumns.map((col) => (
                      <td
                        key={col.key}
                        className={`px-4 py-3 ${col.key === "status" ? "w-10" : ""}`}
                        style={{ color: "var(--text-primary)" }}
                      >
                        {renderCellValue(col.key, device)}
                      </td>
                    ))}
                    {canEdit && (
                      <td className="px-4 py-3">
                        <div
                          className="flex gap-2"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <button
                            onClick={() => setDeleteTarget(device)}
                            className="hover:opacity-80 text-xs cursor-pointer"
                            style={{ color: "var(--danger)" }}
                          >
                            Delete
                          </button>
                        </div>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {pageSize > 0 && totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t" style={{ borderColor: "var(--border-primary)" }}>
            <span className="text-xs" style={{ color: "var(--text-muted)" }}>
              Page {safePage} of {totalPages} — {filteredDevices.length} total
            </span>
            <div className="flex items-center gap-1">
              <button
                onClick={() => setPage(1)}
                disabled={safePage === 1}
                className="px-2 py-1 text-xs rounded disabled:opacity-40 cursor-pointer"
                style={{ color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
              >«</button>
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={safePage === 1}
                className="px-2 py-1 text-xs rounded disabled:opacity-40 cursor-pointer"
                style={{ color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
              >‹</button>
              {Array.from({ length: totalPages }, (_, i) => i + 1)
                .filter((p) => p === 1 || p === totalPages || Math.abs(p - safePage) <= 2)
                .reduce((acc, p, idx, arr) => {
                  if (idx > 0 && p - arr[idx - 1] > 1) acc.push("…");
                  acc.push(p);
                  return acc;
                }, [])
                .map((p, idx) =>
                  p === "…" ? (
                    <span key={`ellipsis-${idx}`} className="px-1 text-xs" style={{ color: "var(--text-muted)" }}>…</span>
                  ) : (
                    <button
                      key={p}
                      onClick={() => setPage(p)}
                      className="px-2 py-1 text-xs rounded cursor-pointer"
                      style={{
                        backgroundColor: p === safePage ? "var(--accent)" : "var(--bg-card-hover)",
                        color: p === safePage ? "var(--bg-primary)" : "var(--text-secondary)",
                        fontWeight: p === safePage ? 700 : 400,
                      }}
                    >{p}</button>
                  )
                )}
              <button
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={safePage === totalPages}
                className="px-2 py-1 text-xs rounded disabled:opacity-40 cursor-pointer"
                style={{ color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
              >›</button>
              <button
                onClick={() => setPage(totalPages)}
                disabled={safePage === totalPages}
                className="px-2 py-1 text-xs rounded disabled:opacity-40 cursor-pointer"
                style={{ color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
              >»</button>
            </div>
          </div>
          )}
        </div>
      )}

      <ConfirmDialog
        open={!!deleteTarget}
        title="Delete Device"
        message={`Are you sure you want to delete "${deleteTarget?.device_name || "this device"}" (${deleteTarget?.serial_number || deleteTarget?.device_id || ""})? This action cannot be undone.`}
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
