import React, { useState, useMemo } from "react";
import Topbar from "../../shared/components/Topbar";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { useDeviceAnalytics } from "../../shared/hooks/useLiveApi";
import { PageLoading } from "../../shared/components/PageLoading";
import {
  ResponsiveContainer,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  PieChart,
  Pie,
  Cell,
  BarChart,
  Bar,
} from "recharts";
import {
  Watch,
  Cpu,
  Radio,
  Nfc,
  ScanLine,
  Activity,
  Battery,
  AlertTriangle,
  CheckCircle2,
  ArrowUpRight,
  ArrowDownRight,
  RefreshCw,
  Download,
  ChevronDown,
} from "lucide-react";

const RANGE_OPTIONS = ["24H", "7D", "30D"];

const dataByRange = {
  "24H": [
    { label: "00:00", events: 12, uptime: 98 },
    { label: "04:00", events: 8, uptime: 99 },
    { label: "08:00", events: 34, uptime: 97 },
    { label: "12:00", events: 51, uptime: 99 },
    { label: "16:00", events: 44, uptime: 98 },
    { label: "20:00", events: 27, uptime: 99 },
  ],
  "7D": [
    { label: "Mon", events: 210, uptime: 98 },
    { label: "Tue", events: 184, uptime: 99 },
    { label: "Wed", events: 240, uptime: 97 },
    { label: "Thu", events: 268, uptime: 98 },
    { label: "Fri", events: 302, uptime: 99 },
    { label: "Sat", events: 145, uptime: 99 },
    { label: "Sun", events: 98, uptime: 100 },
  ],
  "30D": Array.from({ length: 10 }, (_, i) => ({
    label: `D${i * 3 + 1}`,
    events: 600 + Math.round(Math.sin(i) * 150 + i * 20),
    uptime: 96 + (i % 4),
  })),
};

const deviceStatusColors = {
  Online: "#dc2626",
  Idle: "#ef4444",
  Offline: "#E5E7EB",
  Active: "#dc2626",
};

const moduleActivity = [
  { name: "NFC", events: 412 },
  { name: "RFID", events: 298 },
  { name: "PIR", events: 654 },
  { name: "LoRa", events: 187 },
  { name: "ESP32", events: 823 },
];

const alerts = [
  { id: 1, level: "critical", text: "LoRa gateway unreachable — Tower B", time: "6 min ago" },
  { id: 2, level: "warning", text: "Battery below 15% on Device #EW-104", time: "22 min ago" },
  { id: 3, level: "info", text: "Firmware OTA completed on 12 devices", time: "1 hour ago" },
  { id: 4, level: "warning", text: "PIR sensor unresponsive — Room 3B", time: "2 hours ago" },
  { id: 5, level: "info", text: "New device paired: EW-171", time: "3 hours ago" },
];

const levelStyles = {
  critical: "bg-red-50 text-red-600 border-red-200",
  warning: "bg-gray-100 text-gray-600 border-gray-200",
  info: "bg-gray-50 text-gray-500 border-gray-200",
};

export default function Dashboard({ onMenuClick }) {
  const { rows: devices, loading: devicesLoading, refresh: refreshDevices } = useLiveRows("devices");
  const { data: deviceAnalytics, loading: analyticsLoading } = useDeviceAnalytics();
  const [range, setRange] = useState("7D");
  const [refreshing, setRefreshing] = useState(false);
  const [rangeMenuOpen, setRangeMenuOpen] = useState(false);

  const chartData = useMemo(() => dataByRange[range], [range]);

  const deviceStatusData = useMemo(() => {
    if (deviceAnalytics?.byStatus?.length) {
      return deviceAnalytics.byStatus.map((s) => ({
        name: s.status || "Unknown",
        value: s.count,
        color: deviceStatusColors[s.status] || "#E5E7EB",
      }));
    }
    const counts = {};
    devices.forEach((d) => {
      const st = d.status || "Offline";
      counts[st] = (counts[st] || 0) + 1;
    });
    return Object.entries(counts).map(([name, value]) => ({
      name,
      value,
      color: deviceStatusColors[name] || "#E5E7EB",
    }));
  }, [deviceAnalytics, devices]);

  const handleRefresh = async () => {
    setRefreshing(true);
    await refreshDevices();
    setRefreshing(false);
  };

  const handleExport = () => {
    const rows = ["label,events,uptime", ...chartData.map((d) => `${d.label},${d.events},${d.uptime}`)];
    const blob = new Blob([rows.join("\n")], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `dashboard-${range}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const totalDevices = deviceAnalytics?.total ?? devices.length ?? deviceStatusData.reduce((s, d) => s + d.value, 0);

  const stats = [
    {
      label: "Total devices",
      value: totalDevices,
      delta: "+6.2%",
      up: true,
      icon: Watch,
    },
    {
      label: "Active ESP32 nodes",
      value: 142,
      delta: "+2.1%",
      up: true,
      icon: Cpu,
    },
    {
      label: "LoRa transmissions",
      value: "3,204",
      delta: "-1.4%",
      up: false,
      icon: Radio,
    },
    {
      label: "NFC/RFID scans",
      value: "1,876",
      delta: "+8.9%",
      up: true,
      icon: Nfc,
    },
  ];

  if (devicesLoading || analyticsLoading) return <PageLoading label="Loading dashboard…" />;

  return (
    <div className="min-h-screen bg-gray-50">
      <Topbar onMenuClick={onMenuClick} />

      <div className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
        {/* Header */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6">
          <div>
            <h1 className="text-xl font-semibold text-gray-900">Dashboard</h1>
            <p className="text-sm text-gray-500 mt-1">
              Platform overview across all hardware modules
            </p>
          </div>

          <div className="flex items-center gap-2 flex-wrap">
            {/* Range selector */}
            <div className="relative">
              <button
                onClick={() => setRangeMenuOpen((o) => !o)}
                className="flex items-center gap-1.5 bg-white border border-gray-200 text-sm font-medium text-gray-700 px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors"
              >
                {range}
                <ChevronDown className="w-3.5 h-3.5 text-gray-400" />
              </button>
              {rangeMenuOpen && (
                <div className="absolute right-0 mt-1 w-28 bg-white border border-gray-200 rounded-lg shadow-lg overflow-hidden z-20">
                  {RANGE_OPTIONS.map((r) => (
                    <button
                      key={r}
                      onClick={() => {
                        setRange(r);
                        setRangeMenuOpen(false);
                      }}
                      className={`w-full text-left px-3 py-2 text-sm transition-colors ${
                        r === range
                          ? "bg-red-50 text-red-600 font-medium"
                          : "text-gray-700 hover:bg-gray-100"
                      }`}
                    >
                      {r}
                    </button>
                  ))}
                </div>
              )}
            </div>

            <button
              onClick={handleRefresh}
              className="flex items-center gap-1.5 bg-white border border-gray-200 text-sm font-medium text-gray-700 px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors"
            >
              <RefreshCw className={`w-3.5 h-3.5 ${refreshing ? "animate-spin" : ""}`} />
              <span className="hidden sm:inline">Refresh</span>
            </button>

            <button
              onClick={handleExport}
              className="flex items-center gap-1.5 bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-3 py-2 rounded-lg transition-colors"
            >
              <Download className="w-3.5 h-3.5" />
              <span className="hidden sm:inline">Export</span>
            </button>
          </div>
        </div>

        {/* Stat cards */}
        <div className="grid grid-cols-1 xs:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          {stats.map(({ label, value, delta, up, icon: Icon }) => (
            <div
              key={label}
              className="bg-white border border-gray-200 rounded-xl p-5 hover:shadow-sm transition-shadow"
            >
              <div className="flex items-center justify-between mb-3">
                <div className="w-9 h-9 rounded-lg bg-red-50 flex items-center justify-center">
                  <Icon className="w-4 h-4 text-red-600" />
                </div>
                <span
                  className={`flex items-center gap-0.5 text-xs font-medium ${
                    up ? "text-red-600" : "text-gray-500"
                  }`}
                >
                  {up ? (
                    <ArrowUpRight className="w-3 h-3" />
                  ) : (
                    <ArrowDownRight className="w-3 h-3" />
                  )}
                  {delta}
                </span>
              </div>
              <p className="text-2xl font-semibold text-gray-900">{value}</p>
              <p className="text-xs text-gray-500 mt-1">{label}</p>
            </div>
          ))}
        </div>

        {/* Main charts row */}
        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 mb-6">
          {/* Events over time */}
          <div className="xl:col-span-2 bg-white border border-gray-200 rounded-xl p-5">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <Activity className="w-4 h-4 text-red-600" />
                <h2 className="text-sm font-semibold text-gray-900">
                  Event volume — {range}
                </h2>
              </div>
            </div>
            <div className="h-64 sm:h-72">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={chartData} margin={{ top: 5, right: 10, left: -20, bottom: 0 }}>
                  <defs>
                    <linearGradient id="eventsGradient" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#dc2626" stopOpacity={0.25} />
                      <stop offset="100%" stopColor="#dc2626" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" vertical={false} />
                  <XAxis dataKey="label" tick={{ fontSize: 11, fill: "#6B7280" }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: "#6B7280" }} axisLine={false} tickLine={false} />
                  <Tooltip
                    contentStyle={{ fontSize: 12, borderRadius: 8, borderColor: "#E5E7EB" }}
                  />
                  <Area
                    type="monotone"
                    dataKey="events"
                    stroke="#dc2626"
                    strokeWidth={2}
                    fill="url(#eventsGradient)"
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Device status donut */}
          <div className="bg-white border border-gray-200 rounded-xl p-5">
            <div className="flex items-center gap-2 mb-4">
              <Battery className="w-4 h-4 text-red-600" />
              <h2 className="text-sm font-semibold text-gray-900">Device status</h2>
            </div>
            <div className="h-48 relative">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={deviceStatusData}
                    dataKey="value"
                    nameKey="name"
                    innerRadius={55}
                    outerRadius={80}
                    paddingAngle={2}
                  >
                    {deviceStatusData.map((entry, i) => (
                      <Cell key={i} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip contentStyle={{ fontSize: 12, borderRadius: 8, borderColor: "#E5E7EB" }} />
                </PieChart>
              </ResponsiveContainer>
              <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
                <span className="text-xl font-semibold text-gray-900">{totalDevices}</span>
                <span className="text-xs text-gray-500">devices</span>
              </div>
            </div>
            <div className="flex flex-col gap-2 mt-3">
              {deviceStatusData.map((d) => (
                <div key={d.name} className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-2">
                    <span className="w-2 h-2 rounded-full" style={{ backgroundColor: d.color }} />
                    <span className="text-gray-600">{d.name}</span>
                  </div>
                  <span className="font-medium text-gray-900">{d.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Bottom row: module activity + alerts */}
        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
          <div className="xl:col-span-2 bg-white border border-gray-200 rounded-xl p-5">
            <div className="flex items-center gap-2 mb-4">
              <ScanLine className="w-4 h-4 text-red-600" />
              <h2 className="text-sm font-semibold text-gray-900">Events by hardware module</h2>
            </div>
            <div className="h-56 sm:h-64">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={moduleActivity} margin={{ top: 5, right: 10, left: -20, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" vertical={false} />
                  <XAxis dataKey="name" tick={{ fontSize: 11, fill: "#6B7280" }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: "#6B7280" }} axisLine={false} tickLine={false} />
                  <Tooltip contentStyle={{ fontSize: 12, borderRadius: 8, borderColor: "#E5E7EB" }} />
                  <Bar dataKey="events" fill="#dc2626" radius={[4, 4, 0, 0]} barSize={32} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Alerts feed */}
          <div className="bg-white border border-gray-200 rounded-xl overflow-hidden flex flex-col">
            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
              <div className="flex items-center gap-2">
                <AlertTriangle className="w-4 h-4 text-red-600" />
                <h2 className="text-sm font-semibold text-gray-900">Recent alerts</h2>
              </div>
              <span className="text-xs font-medium text-red-600 bg-red-50 border border-red-200 rounded-full px-2 py-0.5">
                {alerts.filter((a) => a.level === "critical").length} critical
              </span>
            </div>
            <div className="divide-y divide-gray-200 overflow-y-auto max-h-72">
              {alerts.map((a) => (
                <div key={a.id} className="px-5 py-3.5 flex items-start gap-3">
                  <span
                    className={`shrink-0 mt-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium uppercase border ${levelStyles[a.level]}`}
                  >
                    {a.level}
                  </span>
                  <div className="min-w-0">
                    <p className="text-sm text-gray-900 leading-snug">{a.text}</p>
                    <p className="text-xs text-gray-400 mt-0.5">{a.time}</p>
                  </div>
                </div>
              ))}
            </div>
            <div className="px-5 py-3 border-t border-gray-200 flex items-center gap-1.5 text-xs text-red-600 font-medium">
              <CheckCircle2 className="w-3.5 h-3.5" />
              All other systems operating normally
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}