import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { MapContainer, TileLayer, Marker } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import ConfirmDialog from "../components/ConfirmDialog";
import NotesPanel from "../equipment/NotesPanel";

// Fix default Leaflet marker icon
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
  iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
  shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
});

// --- Helper components ---

function Field({ label, children }) {
  return (
    <div>
      <dt className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>
        {label}
      </dt>
      <dd className="mt-1 text-sm" style={{ color: "var(--text-primary)" }}>
        {children || "-"}
      </dd>
    </div>
  );
}

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 SectionCard({ title, children }) {
  return (
    <section className="rounded-lg border p-6" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}>
      <h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>{title}</h2>
      {children}
    </section>
  );
}

function Subsection({ title, children, isFirst = false }) {
  return (
    <div className={isFirst ? "" : "mt-4 pt-4 border-t"} style={isFirst ? {} : { borderColor: "var(--border-secondary)" }}>
      <h3 className="text-sm font-semibold mb-3" style={{ color: "var(--text-primary)" }}>{title}</h3>
      <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">{children}</dl>
    </div>
  );
}

// --- Date / time helpers ---

function parseFirestoreDate(str) {
  if (!str) return null;
  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;
}

function formatDate(str) {
  const d = parseFirestoreDate(str);
  if (!d) return str || "-";
  const day = d.getUTCDate().toString().padStart(2, "0");
  const month = (d.getUTCMonth() + 1).toString().padStart(2, "0");
  const year = d.getUTCFullYear();
  return `${day}-${month}-${year}`;
}

function addDays(date, days) {
  return new Date(date.getTime() + days * 86400000);
}

function formatDateNice(d) {
  if (!d) return "-";
  const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
  return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
}

function daysUntil(targetDate) {
  const now = new Date();
  const diff = targetDate.getTime() - now.getTime();
  return Math.ceil(diff / 86400000);
}

function formatRelativeTime(days) {
  if (days < 0) return null;
  if (days === 0) return "today";
  if (days === 1) return "in 1 day";
  if (days < 30) return `in ${days} days`;
  const months = Math.floor(days / 30);
  const remainDays = days % 30;
  if (remainDays === 0) return `in ${months} month${months > 1 ? "s" : ""}`;
  return `in ${months} month${months > 1 ? "s" : ""} and ${remainDays} day${remainDays > 1 ? "s" : ""}`;
}

function daysToDisplay(days) {
  if (days >= 365 && days % 365 === 0) return `${days / 365} year${days / 365 > 1 ? "s" : ""} (${days} days)`;
  if (days >= 30) {
    const months = Math.floor(days / 30);
    const rem = days % 30;
    if (rem === 0) return `${months} month${months > 1 ? "s" : ""} (${days} days)`;
    return `${days} days (~${months} month${months > 1 ? "s" : ""})`;
  }
  return `${days} days`;
}

function formatTimestamp(str) {
  // Try to parse as a Firestore timestamp and return HH:MM
  if (!str) return "-";
  const d = parseFirestoreDate(str);
  if (d) {
    return `${d.getUTCHours().toString().padStart(2, "0")}:${d.getUTCMinutes().toString().padStart(2, "0")}`;
  }
  // Maybe it's already a time string like "14:00"
  if (/^\d{1,2}:\d{2}/.test(str)) return str;
  // Try to extract time from the string
  const match = str.match(/(\d{1,2}):(\d{2})/);
  if (match) return `${match[1].padStart(2, "0")}:${match[2]}`;
  return str;
}

function msToSeconds(ms) {
  if (ms == null) return "-";
  return `${(ms / 1000).toFixed(1)}s`;
}

// --- Coordinates helpers ---

function parseCoordinates(coordStr) {
  if (!coordStr) return null;
  // Handle "lat,lng" or "lat° N, lng° E" or similar
  const cleaned = coordStr.replace(/°\s*[NSEW]/gi, "").trim();
  const parts = cleaned.split(",").map((s) => parseFloat(s.trim()));
  if (parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1])) {
    return { lat: parts[0], lng: parts[1] };
  }
  return null;
}

function formatCoordinates(coords) {
  if (!coords) return "-";
  const latDir = coords.lat >= 0 ? "N" : "S";
  const lngDir = coords.lng >= 0 ? "E" : "W";
  return `${Math.abs(coords.lat).toFixed(7)}° ${latDir}, ${Math.abs(coords.lng).toFixed(7)}° ${lngDir}`;
}

// --- Main component ---

export default function DeviceDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { hasRole } = useAuth();
  const canEdit = hasRole("superadmin", "device_manager");

  const [device, setDevice] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showDelete, setShowDelete] = useState(false);
  const [mqttStatus, setMqttStatus] = useState(null);
  const [locationName, setLocationName] = useState(null);
  const [deviceUsers, setDeviceUsers] = useState([]);
  const [usersLoading, setUsersLoading] = useState(false);

  useEffect(() => {
    loadData();
  }, [id]);

  const loadData = async () => {
    setLoading(true);
    try {
      const [d, mqttData] = await Promise.all([
        api.get(`/devices/${id}`),
        api.get("/mqtt/status").catch(() => null),
      ]);
      setDevice(d);

      // Match MQTT status by serial number
      if (mqttData?.devices && d.device_id) {
        const match = mqttData.devices.find((s) => s.device_serial === d.device_id);
        setMqttStatus(match || null);
      }

      // Load device users
      setUsersLoading(true);
      api.get(`/devices/${id}/users`).then((data) => {
        setDeviceUsers(data.users || []);
      }).catch(() => {
        setDeviceUsers([]);
      }).finally(() => setUsersLoading(false));

      // Reverse geocode
      const coords = parseCoordinates(d.device_location_coordinates);
      if (coords) {
        fetch(`https://nominatim.openstreetmap.org/reverse?lat=${coords.lat}&lon=${coords.lng}&format=json&zoom=10`)
          .then((r) => r.json())
          .then((data) => {
            const addr = data.address || {};
            const name = addr.city || addr.town || addr.village || addr.hamlet || addr.municipality || data.display_name?.split(",")[0] || "";
            const region = addr.state || addr.county || "";
            const country = addr.country || "";
            const parts = [name, region, country].filter(Boolean);
            setLocationName(parts.join(", "));
          })
          .catch(() => setLocationName(null));
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    try {
      await api.delete(`/devices/${id}`);
      navigate("/devices");
    } catch (err) {
      setError(err.message);
      setShowDelete(false);
    }
  };

  if (loading) return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
  if (error) return (
    <div className="text-sm rounded-md p-3 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
      {error}
    </div>
  );
  if (!device) return null;

  const attr = device.device_attributes || {};
  const clock = attr.clockSettings || {};
  const net = attr.networkSettings || {};
  const sub = device.device_subscription || {};
  const stats = device.device_stats || {};
  const coords = parseCoordinates(device.device_location_coordinates);
  const isOnline = mqttStatus ? mqttStatus.online : device.is_Online;

  // Subscription computed fields
  const subscrStart = parseFirestoreDate(sub.subscrStart);
  const subscrEnd = subscrStart && sub.subscrDuration ? addDays(subscrStart, sub.subscrDuration) : null;
  const subscrDaysLeft = subscrEnd ? daysUntil(subscrEnd) : null;

  // Warranty computed fields
  const warrantyStart = parseFirestoreDate(stats.warrantyStart);
  const warrantyEnd = warrantyStart && stats.warrantyPeriod ? addDays(warrantyStart, stats.warrantyPeriod) : null;
  const warrantyDaysLeft = warrantyEnd ? daysUntil(warrantyEnd) : null;

  // Maintenance computed fields
  const maintainedOn = parseFirestoreDate(stats.maintainedOn);
  const nextMaintenance = maintainedOn && stats.maintainancePeriod ? addDays(maintainedOn, stats.maintainancePeriod) : null;
  const maintenanceDaysLeft = nextMaintenance ? daysUntil(nextMaintenance) : null;

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <button onClick={() => navigate("/devices")} className="text-sm hover:underline mb-2 inline-block" style={{ color: "var(--accent)" }}>
            &larr; Back to Devices
          </button>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
              {device.device_name || "Unnamed Device"}
            </h1>
            <span
              className={`inline-block w-3 h-3 rounded-full ${isOnline ? "bg-green-500" : ""}`}
              style={!isOnline ? { backgroundColor: "var(--border-primary)" } : undefined}
              title={isOnline ? "Online" : "Offline"}
            />
          </div>
        </div>
        {canEdit && (
          <div className="flex gap-2">
            <button onClick={() => navigate(`/devices/${id}/edit`)} className="px-4 py-2 text-sm rounded-md transition-colors" style={{ backgroundColor: "var(--text-link)", color: "var(--text-white)" }}>
              Edit
            </button>
            <button onClick={() => setShowDelete(true)} className="px-4 py-2 text-sm rounded-md transition-colors" style={{ backgroundColor: "var(--danger)", color: "var(--text-white)" }}>
              Delete
            </button>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        {/* Left column */}
        <div className="space-y-6">
          {/* Basic Information */}
          <SectionCard title="Basic Information">
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Serial Number">
                <span className="font-mono">{device.device_id}</span>
              </Field>
              <Field label="Status">
                <BoolBadge value={isOnline} yesLabel="Online" noLabel="Offline" />
                {mqttStatus && (
                  <span className="ml-2 text-xs" style={{ color: "var(--text-muted)" }}>
                    (MQTT {mqttStatus.seconds_since_heartbeat}s ago)
                  </span>
                )}
              </Field>
              <Field label="Events On">
                <BoolBadge value={device.events_on} />
              </Field>
              <Field label="Document ID">
                <span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>{device.id}</span>
              </Field>
            </dl>
          </SectionCard>

          {/* Location */}
          <SectionCard title="Location">
            <dl className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <Field label="Location">{device.device_location}</Field>
              <Field label="Coordinates">
                <div>
                  {coords ? formatCoordinates(coords) : device.device_location_coordinates || "-"}
                  {coords && (
                    <a
                      href={`https://www.google.com/maps?q=${coords.lat},${coords.lng}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="ml-2 px-2 py-0.5 text-xs rounded-md inline-block"
                      style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
                      onClick={(e) => e.stopPropagation()}
                    >
                      Open in Maps
                    </a>
                  )}
                </div>
              </Field>
              {locationName && (
                <Field label="Nearest Place">{locationName}</Field>
              )}
            </dl>
            {coords && (
              <div className="rounded-md overflow-hidden border" style={{ borderColor: "var(--border-primary)", height: 200 }}>
                <MapContainer center={[coords.lat, coords.lng]} zoom={13} style={{ height: "100%", width: "100%" }} scrollWheelZoom={false}>
                  <TileLayer
                    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                  />
                  <Marker position={[coords.lat, coords.lng]} />
                </MapContainer>
              </div>
            )}
          </SectionCard>

          {/* Subscription */}
          <SectionCard title="Subscription">
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Tier">
                <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}
                </span>
              </Field>
              <Field label="Start Date">{formatDate(sub.subscrStart)}</Field>
              <Field label="Duration">{sub.subscrDuration ? daysToDisplay(sub.subscrDuration) : "-"}</Field>
              <Field label="Expiration Date">{subscrEnd ? formatDateNice(subscrEnd) : "-"}</Field>
              <Field label="Time Left">
                {subscrDaysLeft === null ? "-" : subscrDaysLeft <= 0 ? (
                  <span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>
                    Subscription Expired
                  </span>
                ) : (
                  <span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>
                    {subscrDaysLeft} days left
                  </span>
                )}
              </Field>
              <Field label="Max Users">{sub.maxUsers}</Field>
              <Field label="Max Outputs">{sub.maxOutputs}</Field>
            </dl>
          </SectionCard>

          {/* Device Settings (combined) */}
          <SectionCard title="Device Settings">
            {/* Subsection 1: Basic Attributes */}
            <Subsection title="Basic Attributes" isFirst>
              <Field label="Bell Guard"><BoolBadge value={attr.bellGuardOn} /></Field>
              <Field label="Warnings On"><BoolBadge value={attr.warningsOn} /></Field>
              <Field label="Bell Guard Safety"><BoolBadge value={attr.bellGuardSafetyOn} /></Field>
            </Subsection>

            {/* Subsection 2: Bell Settings */}
            <Subsection title="Bell Settings">
              <Field label="Has Bells"><BoolBadge value={attr.hasBells} /></Field>
              <Field label="Total Bells">{attr.totalBells}</Field>
              <Field label="Bell Outputs">{attr.bellOutputs?.length > 0 ? attr.bellOutputs.join(", ") : "-"}</Field>
              <Field label="Hammer Timings">{attr.hammerTimings?.length > 0 ? attr.hammerTimings.join(", ") : "-"}</Field>
            </Subsection>

            {/* Subsection 3.1: Clock Settings */}
            <Subsection title="Clock Settings">
              <Field label="Has Clock"><BoolBadge value={attr.hasClock} /></Field>
              <Field label="Odd Output">{clock.clockOutputs?.[0] ?? "-"}</Field>
              <Field label="Even Output">{clock.clockOutputs?.[1] ?? "-"}</Field>
              <Field label="Run Pulse">{clock.clockTimings?.[0] != null ? msToSeconds(clock.clockTimings[0]) : "-"}</Field>
              <Field label="Pause Pulse">{clock.clockTimings?.[1] != null ? msToSeconds(clock.clockTimings[1]) : "-"}</Field>
              <Field label="Alerts Status"><BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" /></Field>
              <Field label="Alerts Type"><span className="capitalize">{clock.ringAlerts || "-"}</span></Field>
              <Field label="Ring Intervals">{clock.ringIntervals}</Field>
              <Field label="Hour Bell">{clock.hourAlertsBell}</Field>
              <Field label="Half-Hour Bell">{clock.halfhourAlertsBell}</Field>
              <Field label="Quarter Bell">{clock.quarterAlertsBell}</Field>
              <Field label="Daytime Silence"><BoolBadge value={clock.isDaySilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
              {clock.isDaySilenceOn && (
                <Field label="Daytime Period">
                  {formatTimestamp(clock.daySilenceFrom)} - {formatTimestamp(clock.daySilenceTo)}
                </Field>
              )}
              <Field label="Nighttime Silence"><BoolBadge value={clock.isNightSilenceOn} yesLabel="ON" noLabel="OFF" /></Field>
              {clock.isNightSilenceOn && (
                <Field label="Nighttime Period">
                  {formatTimestamp(clock.nightSilenceFrom)} - {formatTimestamp(clock.nightSilenceTo)}
                </Field>
              )}
            </Subsection>

            {/* Subsection 3.2: Backlight Settings */}
            <Subsection title="Backlight Settings">
              <Field label="Auto Backlight"><BoolBadge value={clock.isBacklightAutomationOn} yesLabel="ON" noLabel="OFF" /></Field>
              <Field label="Backlight Output">{clock.backlightOutput}</Field>
              <Field label="On Time">{formatTimestamp(clock.backlightTurnOnTime)}</Field>
              <Field label="Off Time">{formatTimestamp(clock.backlightTurnOffTime)}</Field>
            </Subsection>

            {/* Subsection 4: Network */}
            <Subsection title="Network">
              <Field label="Hostname">{net.hostname}</Field>
              <Field label="Has Static IP"><BoolBadge value={net.useStaticIP} /></Field>
            </Subsection>

            {/* Subsection 5: Logging */}
            <Subsection title="Logging">
              <Field label="Serial Log Level">{attr.serialLogLevel}</Field>
              <Field label="SD Log Level">{attr.sdLogLevel}</Field>
              <Field label="MQTT Log Level">{attr.mqttLogLevel ?? 0}</Field>
            </Subsection>
          </SectionCard>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Misc */}
          <SectionCard title="Misc">
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Device Locale"><span className="capitalize">{attr.deviceLocale || "-"}</span></Field>
              <Field label="WebSocket URL">{device.websocket_url}</Field>
              <Field label="Has Assistant"><BoolBadge value={attr.hasAssistant} /></Field>
              <div className="col-span-2 md:col-span-3">
                <Field label="Church Assistant URL">{device.churchAssistantURL}</Field>
              </div>
            </dl>
          </SectionCard>

          {/* Warranty & Maintenance & Statistics */}
          <SectionCard title="Warranty, Maintenance & Statistics">
            {/* Subsection 1: Warranty */}
            <Subsection title="Warranty Information" isFirst>
              <Field label="Warranty Status">
                {warrantyDaysLeft !== null ? (
                  warrantyDaysLeft > 0 ? (
                    <span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>Active</span>
                  ) : (
                    <span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}>Expired</span>
                  )
                ) : (
                  <BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />
                )}
              </Field>
              <Field label="Start Date">{formatDate(stats.warrantyStart)}</Field>
              <Field label="Warranty Period">{stats.warrantyPeriod ? daysToDisplay(stats.warrantyPeriod) : "-"}</Field>
              <Field label="Expiration Date">{warrantyEnd ? formatDateNice(warrantyEnd) : "-"}</Field>
              <Field label="Remaining">
                {warrantyDaysLeft === null ? "-" : warrantyDaysLeft <= 0 ? (
                  <span style={{ color: "var(--danger-text)" }}>Expired</span>
                ) : (
                  `${warrantyDaysLeft} days`
                )}
              </Field>
            </Subsection>

            {/* Subsection 2: Maintenance */}
            <Subsection title="Maintenance">
              <Field label="Last Maintained On">{formatDate(stats.maintainedOn)}</Field>
              <Field label="Maintenance Period">{stats.maintainancePeriod ? daysToDisplay(stats.maintainancePeriod) : "-"}</Field>
              <Field label="Next Scheduled">
                {nextMaintenance ? (
                  <span>
                    {formatDateNice(nextMaintenance)}
                    {maintenanceDaysLeft !== null && (
                      <span className="ml-1 text-xs" style={{ color: maintenanceDaysLeft <= 0 ? "var(--danger-text)" : "var(--text-muted)" }}>
                        ({maintenanceDaysLeft <= 0 ? "overdue" : formatRelativeTime(maintenanceDaysLeft)})
                      </span>
                    )}
                  </span>
                ) : "-"}
              </Field>
            </Subsection>

            {/* Subsection 3: Statistics */}
            <Subsection title="Statistics">
              <Field label="Total Playbacks">{stats.totalPlaybacks}</Field>
              <Field label="Total Hammer Strikes">{stats.totalHammerStrikes}</Field>
              <Field label="Total Warnings Given">{stats.totalWarningsGiven}</Field>
              <Field label="Total Melodies">{device.device_melodies_all?.length ?? 0}</Field>
              <Field label="Favorite Melodies">{device.device_melodies_favorites?.length ?? 0}</Field>
              {stats.perBellStrikes?.length > 0 && (
                <div className="col-span-2 md:col-span-3">
                  <Field label="Per Bell Strikes">
                    <div className="flex flex-wrap gap-2 mt-1">
                      {stats.perBellStrikes.slice(0, attr.totalBells || stats.perBellStrikes.length).map((count, i) => (
                        <span key={i} className="px-2 py-1 text-xs rounded-md border" style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}>
                          Bell {i + 1}: {count}
                        </span>
                      ))}
                    </div>
                  </Field>
                </div>
              )}
            </Subsection>
          </SectionCard>

          {/* Users */}
          <SectionCard title={`Users (${deviceUsers.length})`}>
            {usersLoading ? (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>Loading users...</p>
            ) : deviceUsers.length === 0 ? (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>No users assigned to this device.</p>
            ) : (
              <div className="space-y-2">
                {deviceUsers.map((user, i) => (
                  <div
                    key={user.user_id || i}
                    className="p-3 rounded-md border cursor-pointer hover:opacity-90 transition-colors"
                    style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
                    onClick={() => user.user_id && navigate(`/users/${user.user_id}`)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="min-w-0">
                        <p className="text-sm font-medium truncate" style={{ color: "var(--text-heading)" }}>
                          {user.display_name || user.email || "Unknown User"}
                        </p>
                        {user.email && user.display_name && (
                          <p className="text-xs truncate" style={{ color: "var(--text-muted)" }}>{user.email}</p>
                        )}
                        {user.user_id && (
                          <p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>{user.user_id}</p>
                        )}
                      </div>
                      {user.role && (
                        <span className="px-2 py-0.5 text-xs rounded-full capitalize shrink-0 ml-2" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>
                          {user.role}
                        </span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </SectionCard>

          {/* Equipment Notes */}
          <NotesPanel deviceId={id} />
        </div>
      </div>

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