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

// ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CFG = {
  manufactured:   { color: "#9ca3af", glow: "rgba(156,163,175,0.15)", label: "Manufactured" },
  flashed:        { color: "#63b3ed", glow: "rgba(99,179,237,0.15)",  label: "Flashed" },
  provisioned:    { color: "#4dd6c8", glow: "rgba(77,214,200,0.15)",  label: "Provisioned" },
  sold:           { color: "#c084fc", glow: "rgba(192,132,252,0.15)", label: "Sold" },
  claimed:        { color: "#fb923c", glow: "rgba(251,146,60,0.15)",  label: "Claimed" },
  decommissioned: { color: "#f34b4b", glow: "rgba(243,75,75,0.15)",   label: "Decommissioned" },
};

const STATUS_ORDER = ["manufactured", "flashed", "provisioned", "sold", "claimed", "decommissioned"];

const ACTION_LABELS = {
  batch_created:   "Batch Created",
  device_flashed:  "NVS Downloaded",
  device_assigned: "Device Assigned",
  status_updated:  "Status Updated",
};

// ─── Module nav tiles ─────────────────────────────────────────────────────────
const MODULE_TILES = [
  {
    key: "devices",
    label: "Fleet",
    sublabel: "Deployed Devices",
    to: "/devices",
    permission: "devices",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="3" width="20" height="14" rx="2" />
        <path d="M8 21h8M12 17v4" />
        <circle cx="12" cy="10" r="3" />
      </svg>
    ),
    accent: "#4dd6c8",
  },
  {
    key: "melodies",
    label: "Melodies",
    sublabel: "Library & Composer",
    to: "/melodies",
    permission: "melodies",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
        <path d="M9 18V5l12-2v13" />
        <circle cx="6" cy="18" r="3" />
        <circle cx="18" cy="16" r="3" />
      </svg>
    ),
    accent: "#c084fc",
  },
  {
    key: "crm",
    label: "Customers",
    sublabel: "CRM & Orders",
    to: "/crm/customers",
    permission: "crm",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
        <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" />
        <circle cx="9" cy="7" r="4" />
        <path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" />
      </svg>
    ),
    accent: "#fb923c",
  },
  {
    key: "manufacturing",
    label: "Manufacturing",
    sublabel: "Inventory & Provisioning",
    to: "/manufacturing",
    permission: "manufacturing",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
      </svg>
    ),
    accent: "#74b816",
  },
  {
    key: "firmware",
    label: "Firmware",
    sublabel: "OTA Manager",
    to: "/firmware",
    permission: "manufacturing",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
        <polyline points="16 18 22 12 16 6" />
        <polyline points="8 6 2 12 8 18" />
        <line x1="19" y1="12" x2="5" y2="12" />
      </svg>
    ),
    accent: "#63b3ed",
  },
  {
    key: "mqtt",
    label: "Command Center",
    sublabel: "MQTT & Control",
    to: "/mqtt/commands",
    permission: "mqtt",
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
        <path d="M18.36 6.64a9 9 0 010 12.72M5.64 6.64a9 9 0 000 12.72M12 18a6 6 0 010-12M12 18v.01" />
        <circle cx="12" cy="12" r="1" fill="currentColor" />
      </svg>
    ),
    accent: "#f34b4b",
  },
];

// ─── Utility: format timestamp ────────────────────────────────────────────────
function formatTs(ts) {
  if (!ts) return "—";
  try {
    const d = new Date(ts);
    const now = new Date();
    const diff = now - d;
    if (diff < 60_000) return "just now";
    if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
    if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  } catch {
    return ts;
  }
}

// ─── Animated counter ─────────────────────────────────────────────────────────
function AnimatedCount({ value }) {
  const [display, setDisplay] = useState(0);
  useEffect(() => {
    if (value === 0) { setDisplay(0); return; }
    const duration = 600;
    const start = Date.now();
    const tick = () => {
      const elapsed = Date.now() - start;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setDisplay(Math.round(eased * value));
      if (progress < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [value]);
  return <>{display}</>;
}

// ─── Status Pill ──────────────────────────────────────────────────────────────
function StatusPill({ status }) {
  const cfg = STATUS_CFG[status];
  if (!cfg) return <span style={{ color: "var(--text-muted)", fontSize: 11 }}>{status}</span>;
  return (
    <span
      style={{
        display: "inline-block",
        fontSize: 10,
        fontWeight: 700,
        letterSpacing: "0.06em",
        textTransform: "uppercase",
        padding: "2px 8px",
        borderRadius: 3,
        backgroundColor: cfg.glow,
        color: cfg.color,
        border: `1px solid ${cfg.color}33`,
      }}
    >
      {cfg.label}
    </span>
  );
}

// ─── Background grid texture ──────────────────────────────────────────────────
const BG_GRID = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40'%3E%3Cpath d='M 40 0 L 0 0 0 40' fill='none' stroke='%23374151' stroke-width='0.4' opacity='0.5'/%3E%3C/svg%3E")`;

// ─── Main Dashboard ───────────────────────────────────────────────────────────
export default function DashboardPage() {
  const { user, hasPermission } = useAuth();
  const navigate = useNavigate();

  const canViewMfg = hasPermission("manufacturing", "view");

  const [stats, setStats]             = useState(null);
  const [auditLog, setAuditLog]       = useState([]);
  const [loadingStats, setLoadingStats] = useState(false);
  const [loadingAudit, setLoadingAudit] = useState(false);
  const [now, setNow]                 = useState(new Date());

  // Live clock
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  useEffect(() => {
    if (!canViewMfg) return;
    setLoadingStats(true);
    api.get("/manufacturing/stats")
      .then(setStats)
      .catch(() => {})
      .finally(() => setLoadingStats(false));

    setLoadingAudit(true);
    api.get("/manufacturing/audit-log?limit=12")
      .then((data) => setAuditLog(data.entries || []))
      .catch(() => {})
      .finally(() => setLoadingAudit(false));
  }, [canViewMfg]);

  const totalDevices = stats
    ? STATUS_ORDER.reduce((s, k) => s + (stats.counts[k] ?? 0), 0)
    : null;

  const accessibleModules = MODULE_TILES.filter((m) =>
    !m.permission || hasPermission(m.permission, "view")
  );

  const clockStr = now.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
  const dateStr  = now.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" });

  return (
    <div style={{ minHeight: "100%", position: "relative" }}>
      {/* Subtle grid background */}
      <div
        style={{
          position: "absolute", inset: 0, pointerEvents: "none", zIndex: 0,
          backgroundImage: BG_GRID,
          opacity: 0.4,
        }}
      />

      <div style={{ position: "relative", zIndex: 1 }}>

        {/* ── Hero header ─────────────────────────────────────────────────────── */}
        <div
          style={{
            display: "flex",
            alignItems: "flex-start",
            justifyContent: "space-between",
            marginBottom: "2rem",
            paddingBottom: "1.5rem",
            borderBottom: "1px solid var(--border-primary)",
          }}
        >
          <div>
            <div
              style={{
                fontSize: 11,
                fontWeight: 700,
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                color: "var(--accent)",
                marginBottom: 8,
              }}
            >
              BellSystems · Control Panel
            </div>
            <h1
              style={{
                fontSize: "clamp(1.6rem, 3vw, 2.4rem)",
                fontWeight: 800,
                letterSpacing: "-0.03em",
                color: "var(--text-heading)",
                margin: 0,
                lineHeight: 1.1,
              }}
            >
              Good {getGreeting()},{" "}
              <span style={{ color: "var(--accent)" }}>{user?.name?.split(" ")[0]}</span>.
            </h1>
            <p style={{ fontSize: 13, color: "var(--text-muted)", marginTop: 6 }}>
              <span
                style={{
                  display: "inline-block",
                  fontSize: 10,
                  fontWeight: 700,
                  letterSpacing: "0.06em",
                  textTransform: "uppercase",
                  padding: "2px 7px",
                  borderRadius: 3,
                  backgroundColor: "var(--badge-blue-bg)",
                  color: "var(--badge-blue-text)",
                  marginRight: 8,
                }}
              >
                {user?.role}
              </span>
              {dateStr}
            </p>
          </div>

          {/* Live clock */}
          <div style={{ textAlign: "right", flexShrink: 0, marginLeft: 24 }}>
            <div
              style={{
                fontFamily: "'Courier New', Courier, monospace",
                fontSize: "clamp(1.4rem, 2.5vw, 2rem)",
                fontWeight: 700,
                letterSpacing: "0.06em",
                color: "var(--accent)",
                lineHeight: 1,
              }}
            >
              {clockStr}
            </div>
            <div style={{ fontSize: 10, color: "var(--text-muted)", marginTop: 4, letterSpacing: "0.04em" }}>
              LOCAL TIME
            </div>
          </div>
        </div>

        {/* ── Device inventory stats (mfg permission) ──────────────────────────── */}
        {canViewMfg && (
          <section style={{ marginBottom: "2rem" }}>
            <SectionLabel label="Device Inventory" action="View all" onAction={() => navigate("/manufacturing")} />

            {loadingStats ? (
              <LoadingRow />
            ) : stats ? (
              <>
                {/* Big total + per-status bars */}
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: "auto 1fr",
                    gap: 16,
                    alignItems: "center",
                    padding: "20px 24px",
                    borderRadius: 8,
                    border: "1px solid var(--border-primary)",
                    backgroundColor: "var(--bg-card)",
                    marginBottom: 12,
                  }}
                >
                  {/* Total */}
                  <div style={{ paddingRight: 28, borderRight: "1px solid var(--border-primary)" }}>
                    <div
                      style={{
                        fontFamily: "'Courier New', Courier, monospace",
                        fontSize: "3rem",
                        fontWeight: 900,
                        lineHeight: 1,
                        color: "var(--accent)",
                        textShadow: "0 0 30px rgba(116,184,22,0.3)",
                      }}
                    >
                      <AnimatedCount value={totalDevices ?? 0} />
                    </div>
                    <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)", marginTop: 4 }}>
                      Total Units
                    </div>
                  </div>

                  {/* Per-status grid */}
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "repeat(auto-fill, minmax(110px, 1fr))",
                      gap: 10,
                    }}
                  >
                    {STATUS_ORDER.map((s) => {
                      const cfg = STATUS_CFG[s];
                      const count = stats.counts[s] ?? 0;
                      const pct = totalDevices ? Math.round((count / totalDevices) * 100) : 0;
                      return (
                        <button
                          key={s}
                          onClick={() => navigate(`/manufacturing?status=${s}`)}
                          style={{
                            background: "none",
                            border: "none",
                            padding: 0,
                            cursor: "pointer",
                            textAlign: "left",
                          }}
                          title={`View ${cfg.label} devices`}
                        >
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
                            <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: cfg.color }}>
                              {cfg.label}
                            </span>
                            <span
                              style={{
                                fontFamily: "'Courier New', Courier, monospace",
                                fontSize: 16,
                                fontWeight: 700,
                                color: cfg.color,
                              }}
                            >
                              {count}
                            </span>
                          </div>
                          {/* Progress bar */}
                          <div
                            style={{
                              height: 3,
                              borderRadius: 2,
                              backgroundColor: "var(--border-primary)",
                              overflow: "hidden",
                            }}
                          >
                            <div
                              style={{
                                height: "100%",
                                width: `${pct}%`,
                                backgroundColor: cfg.color,
                                boxShadow: `0 0 6px ${cfg.color}`,
                                borderRadius: 2,
                                transition: "width 0.8s cubic-bezier(0.16, 1, 0.3, 1)",
                              }}
                            />
                          </div>
                        </button>
                      );
                    })}
                  </div>
                </div>
              </>
            ) : null}
          </section>
        )}

        {/* ── Module navigation tiles ───────────────────────────────────────────── */}
        <section style={{ marginBottom: "2rem" }}>
          <SectionLabel label="Modules" />
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))",
              gap: 10,
            }}
          >
            {accessibleModules.map((m) => (
              <ModuleTile key={m.key} {...m} onClick={() => navigate(m.to)} />
            ))}
          </div>
        </section>

        {/* ── Bottom two-column: Recent Activity + Audit Log ────────────────────── */}
        {canViewMfg && (
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 16,
            }}
          >
            {/* Recent Activity */}
            <section>
              <SectionLabel label="Recent Device Activity" action="All devices" onAction={() => navigate("/manufacturing")} />
              <div
                style={{
                  border: "1px solid var(--border-primary)",
                  borderRadius: 8,
                  backgroundColor: "var(--bg-card)",
                  overflow: "hidden",
                }}
              >
                {!stats?.recent_activity?.length ? (
                  <EmptyState text="No recent activity" />
                ) : (
                  <table style={{ width: "100%", borderCollapse: "collapse" }}>
                    <thead>
                      <tr style={{ borderBottom: "1px solid var(--border-secondary)" }}>
                        <TH>Serial</TH>
                        <TH>Status</TH>
                        <TH>Owner</TH>
                        <TH>When</TH>
                      </tr>
                    </thead>
                    <tbody>
                      {stats.recent_activity.map((item, i) => (
                        <ActivityRow
                          key={i}
                          item={item}
                          onClick={() => navigate(`/manufacturing/devices/${item.serial_number}`)}
                        />
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </section>

            {/* Audit Log */}
            <section>
              <SectionLabel label="Audit Log" />
              <div
                style={{
                  border: "1px solid var(--border-primary)",
                  borderRadius: 8,
                  backgroundColor: "var(--bg-card)",
                  overflow: "hidden",
                }}
              >
                {loadingAudit ? (
                  <LoadingRow />
                ) : !auditLog.length ? (
                  <EmptyState text="No audit entries yet" />
                ) : (
                  <table style={{ width: "100%", borderCollapse: "collapse" }}>
                    <thead>
                      <tr style={{ borderBottom: "1px solid var(--border-secondary)" }}>
                        <TH>Time</TH>
                        <TH>User</TH>
                        <TH>Action</TH>
                        <TH>Device</TH>
                      </tr>
                    </thead>
                    <tbody>
                      {auditLog.map((entry) => (
                        <AuditRow
                          key={entry.id}
                          entry={entry}
                          onDeviceClick={(sn) => navigate(`/manufacturing/devices/${sn}`)}
                        />
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </section>
          </div>
        )}

        {!canViewMfg && (
          <div
            style={{
              padding: "40px 0",
              textAlign: "center",
              color: "var(--text-muted)",
              fontSize: 14,
            }}
          >
            Select a module above to get started.
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function getGreeting() {
  const h = new Date().getHours();
  if (h < 12) return "Good morning";
  if (h < 17) return "Good afternoon";
  return "Good evening";
}

function SectionLabel({ label, action, onAction }) {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        marginBottom: 10,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div
          style={{
            width: 3,
            height: 14,
            borderRadius: 2,
            backgroundColor: "var(--accent)",
          }}
        />
        <span
          style={{
            fontSize: 10,
            fontWeight: 800,
            letterSpacing: "0.1em",
            textTransform: "uppercase",
            color: "var(--text-muted)",
          }}
        >
          {label}
        </span>
      </div>
      {action && (
        <button
          onClick={onAction}
          style={{
            background: "none",
            border: "none",
            fontSize: 11,
            color: "var(--text-link)",
            cursor: "pointer",
            padding: 0,
          }}
        >
          {action} →
        </button>
      )}
    </div>
  );
}

function ModuleTile({ label, sublabel, accent, icon, onClick }) {
  const [hovered, setHovered] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        background: hovered
          ? `linear-gradient(135deg, ${accent}14 0%, ${accent}08 100%)`
          : "var(--bg-card)",
        border: `1px solid ${hovered ? accent + "55" : "var(--border-primary)"}`,
        borderRadius: 8,
        padding: "16px 16px 14px",
        cursor: "pointer",
        textAlign: "left",
        transition: "all 0.2s ease",
        transform: hovered ? "translateY(-1px)" : "none",
        boxShadow: hovered ? `0 4px 20px ${accent}22` : "none",
        display: "flex",
        flexDirection: "column",
        gap: 10,
      }}
    >
      <div
        style={{
          width: 32,
          height: 32,
          color: hovered ? accent : "var(--text-muted)",
          transition: "color 0.2s ease",
        }}
      >
        {icon}
      </div>
      <div>
        <div
          style={{
            fontSize: 13,
            fontWeight: 700,
            color: hovered ? "var(--text-heading)" : "var(--text-primary)",
            transition: "color 0.2s ease",
            letterSpacing: "-0.01em",
          }}
        >
          {label}
        </div>
        <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2 }}>
          {sublabel}
        </div>
      </div>
    </button>
  );
}

function TH({ children }) {
  return (
    <th
      style={{
        padding: "8px 14px",
        textAlign: "left",
        fontSize: 10,
        fontWeight: 700,
        letterSpacing: "0.07em",
        textTransform: "uppercase",
        color: "var(--text-muted)",
        backgroundColor: "var(--bg-secondary)",
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </th>
  );
}

function ActivityRow({ item, onClick }) {
  const [hovered, setHovered] = useState(false);
  return (
    <tr
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        borderBottom: "1px solid var(--border-secondary)",
        cursor: "pointer",
        backgroundColor: hovered ? "var(--bg-card-hover)" : "transparent",
        transition: "background-color 0.1s ease",
      }}
    >
      <td style={{ padding: "8px 14px" }}>
        <span
          style={{
            fontFamily: "'Courier New', Courier, monospace",
            fontSize: 11,
            color: "var(--text-link)",
            letterSpacing: "0.04em",
          }}
        >
          {item.serial_number}
        </span>
      </td>
      <td style={{ padding: "8px 14px" }}>
        <StatusPill status={item.mfg_status} />
      </td>
      <td style={{ padding: "8px 14px", fontSize: 12, color: "var(--text-muted)", maxWidth: 100, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
        {item.owner || "—"}
      </td>
      <td style={{ padding: "8px 14px", fontSize: 11, color: "var(--text-muted)", whiteSpace: "nowrap" }}>
        {formatTs(item.updated_at)}
      </td>
    </tr>
  );
}

function AuditRow({ entry, onDeviceClick }) {
  const parseDetail = (detail) => {
    if (!detail) return "—";
    try {
      const d = JSON.parse(detail);
      return Object.entries(d)
        .filter(([, v]) => v !== null && v !== undefined)
        .map(([k, v]) => `${k}: ${v}`)
        .join(", ");
    } catch {
      return detail;
    }
  };

  return (
    <tr
      style={{
        borderBottom: "1px solid var(--border-secondary)",
      }}
    >
      <td style={{ padding: "8px 14px", fontSize: 11, color: "var(--text-muted)", whiteSpace: "nowrap" }}>
        {formatTs(entry.timestamp)}
      </td>
      <td style={{ padding: "8px 14px", fontSize: 12, color: "var(--text-secondary)", whiteSpace: "nowrap" }}>
        {entry.admin_user}
      </td>
      <td style={{ padding: "8px 14px" }}>
        <span
          style={{
            fontSize: 10,
            fontWeight: 700,
            letterSpacing: "0.06em",
            textTransform: "uppercase",
            color: "var(--accent)",
          }}
        >
          {ACTION_LABELS[entry.action] || entry.action}
        </span>
      </td>
      <td style={{ padding: "8px 14px" }}>
        {entry.serial_number ? (
          <button
            onClick={() => onDeviceClick(entry.serial_number)}
            style={{
              background: "none",
              border: "none",
              padding: 0,
              fontFamily: "'Courier New', Courier, monospace",
              fontSize: 11,
              color: "var(--text-link)",
              cursor: "pointer",
              letterSpacing: "0.04em",
            }}
          >
            {entry.serial_number}
          </button>
        ) : (
          <span style={{ fontSize: 12, color: "var(--text-muted)" }}>—</span>
        )}
      </td>
    </tr>
  );
}

function LoadingRow() {
  return (
    <div style={{ padding: "24px 16px", textAlign: "center" }}>
      <div
        style={{
          display: "inline-block",
          width: 16,
          height: 16,
          border: "2px solid var(--border-primary)",
          borderTopColor: "var(--accent)",
          borderRadius: "50%",
          animation: "spin 0.7s linear infinite",
        }}
      />
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

function EmptyState({ text }) {
  return (
    <div style={{ padding: "28px 16px", textAlign: "center", color: "var(--text-muted)", fontSize: 13 }}>
      {text}
    </div>
  );
}
