import React, { useState, useMemo } from "react";
import Topbar from "../../shared/components/Topbar";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { PageLoading } from "../../shared/components/PageLoading";
import {
  Watch,
  Search,
  Filter,
  Plus,
  Download,
  MoreVertical,
  Wifi,
  WifiOff,
  Battery,
  BatteryLow,
  ChevronRight,
  X,
  Check,
  Trash2,
} from "lucide-react";

const STATUS_FILTERS = ["All", "Online", "Idle", "Offline"];

const statusStyles = {
  Online: "bg-red-50 text-red-600 border-red-200",
  Idle: "bg-gray-100 text-gray-600 border-gray-200",
  Offline: "bg-gray-50 text-gray-400 border-gray-200",
};

export default function DeviceList({ onMenuClick, onSelectDevice }) {
  const { rows: devices, loading, add, remove } = useLiveRows("devices");
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("All");
  const [selected, setSelected] = useState([]);
  const [addModalOpen, setAddModalOpen] = useState(false);
  const [newDeviceId, setNewDeviceId] = useState("");
  const [newOwner, setNewOwner] = useState("");
  const [toastMessage, setToastMessage] = useState("");

  const showToast = (msg) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(""), 2200);
  };

  const filtered = useMemo(() => {
    return devices.filter((d) => {
      const matchesSearch =
        d.id.toLowerCase().includes(search.toLowerCase()) ||
        d.owner.toLowerCase().includes(search.toLowerCase()) ||
        d.branch.toLowerCase().includes(search.toLowerCase());
      const matchesStatus = statusFilter === "All" || d.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [devices, search, statusFilter]);

  const allSelected = filtered.length > 0 && selected.length === filtered.length;

  const toggleSelectAll = () => {
    setSelected(allSelected ? [] : filtered.map((d) => d.id));
  };

  const toggleSelectOne = (id) => {
    setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  };

  const handleBulkRemove = async () => {
    await Promise.all(selected.map((id) => remove(id)));
    showToast(`${selected.length} device(s) removed`);
    setSelected([]);
  };

  const handleExport = () => {
    const rows = ["id,owner,branch,status,battery,signal,lastSeen", ...filtered.map((d) =>
      `${d.id},${d.owner},${d.branch},${d.status},${d.battery},${d.signal},${d.lastSeen}`
    )];
    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 = "devices.csv";
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleAddDevice = async () => {
    if (!newDeviceId.trim() || !newOwner.trim()) return;
    const deviceId = newDeviceId.trim();
    await add({
      id: deviceId,
      owner: newOwner.trim(),
      branch: "Lucknow HQ",
      status: "Offline",
      battery: 100,
      signal: "None",
      lastSeen: "Never",
    });
    setNewDeviceId("");
    setNewOwner("");
    setAddModalOpen(false);
    showToast(`${deviceId} registered`);
  };

  const signalIcon = (signal) =>
    signal === "None" ? <WifiOff className="w-3.5 h-3.5 text-gray-300" /> : <Wifi className="w-3.5 h-3.5 text-red-600" />;

  if (loading) return <PageLoading label="Loading devices…" />;

  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">
        {toastMessage && (
          <div className="fixed top-6 right-6 z-50 flex items-center gap-2 bg-white border border-gray-200 shadow-lg rounded-lg px-4 py-3">
            <div className="w-5 h-5 rounded-full bg-red-600 flex items-center justify-center">
              <Check className="w-3 h-3 text-white" />
            </div>
            <span className="text-sm text-gray-900">{toastMessage}</span>
          </div>
        )}

        <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">Devices</h1>
            <p className="text-sm text-gray-500 mt-1">
              {devices.length} wearable devices across your organization
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handleExport}
              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"
            >
              <Download className="w-3.5 h-3.5" />
              <span className="hidden sm:inline">Export</span>
            </button>
            <button
              onClick={() => setAddModalOpen(true)}
              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"
            >
              <Plus className="w-3.5 h-3.5" />
              Add device
            </button>
          </div>
        </div>

        {/* Filters */}
        <div className="flex flex-col sm:flex-row sm:items-center gap-3 mb-4">
          <div className="relative flex-1 sm:max-w-xs">
            <Search className="w-3.5 h-3.5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by ID, owner, or branch"
              className="w-full pl-9 pr-3 py-2 text-sm rounded-lg border border-gray-200 outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500"
            />
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            <Filter className="w-3.5 h-3.5 text-gray-400 hidden sm:block" />
            {STATUS_FILTERS.map((s) => (
              <button
                key={s}
                onClick={() => setStatusFilter(s)}
                className={`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
                  statusFilter === s
                    ? "bg-red-600 border-red-600 text-white"
                    : "bg-white border-gray-200 text-gray-600 hover:bg-gray-100"
                }`}
              >
                {s}
              </button>
            ))}
          </div>
        </div>

        {/* Bulk action bar */}
        {selected.length > 0 && (
          <div className="flex items-center justify-between bg-red-50 border border-red-200 rounded-lg px-4 py-2.5 mb-4">
            <span className="text-sm text-red-600 font-medium">{selected.length} selected</span>
            <button
              onClick={handleBulkRemove}
              className="flex items-center gap-1.5 text-sm font-medium text-red-600 hover:text-red-500"
            >
              <Trash2 className="w-3.5 h-3.5" />
              Remove
            </button>
          </div>
        )}

        {/* Table */}
        <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm min-w-[760px]">
              <thead>
                <tr className="text-left text-gray-500 border-b border-gray-200">
                  <th className="px-5 py-3 w-10">
                    <input
                      type="checkbox"
                      checked={allSelected}
                      onChange={toggleSelectAll}
                      className="w-4 h-4 rounded border-gray-300 text-red-600 focus:ring-red-500"
                    />
                  </th>
                  <th className="px-5 py-3 font-medium">Device</th>
                  <th className="px-5 py-3 font-medium">Owner</th>
                  <th className="px-5 py-3 font-medium">Branch</th>
                  <th className="px-5 py-3 font-medium">Status</th>
                  <th className="px-5 py-3 font-medium">Battery</th>
                  <th className="px-5 py-3 font-medium">Signal</th>
                  <th className="px-5 py-3 font-medium">Last seen</th>
                  <th className="px-5 py-3 font-medium text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((d) => (
                  <tr
                    key={d.id}
                    className="border-b border-gray-200 last:border-0 hover:bg-gray-100 transition-colors"
                  >
                    <td className="px-5 py-3">
                      <input
                        type="checkbox"
                        checked={selected.includes(d.id)}
                        onChange={() => toggleSelectOne(d.id)}
                        className="w-4 h-4 rounded border-gray-300 text-red-600 focus:ring-red-500"
                      />
                    </td>
                    <td className="px-5 py-3">
                      <button
                        onClick={() => onSelectDevice?.(d.id)}
                        className="flex items-center gap-2 text-gray-900 font-medium hover:text-red-600"
                      >
                        <Watch className="w-3.5 h-3.5 text-gray-400" />
                        {d.id}
                      </button>
                    </td>
                    <td className="px-5 py-3 text-gray-600">{d.owner}</td>
                    <td className="px-5 py-3 text-gray-600">{d.branch}</td>
                    <td className="px-5 py-3">
                      <span className={`px-2 py-0.5 rounded-full text-xs font-medium border ${statusStyles[d.status]}`}>
                        {d.status}
                      </span>
                    </td>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-1.5">
                        {d.battery < 20 ? (
                          <BatteryLow className="w-3.5 h-3.5 text-red-600" />
                        ) : (
                          <Battery className="w-3.5 h-3.5 text-gray-400" />
                        )}
                        <span className="text-gray-600">{d.battery}%</span>
                      </div>
                    </td>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-1.5 text-gray-600">
                        {signalIcon(d.signal)}
                        {d.signal}
                      </div>
                    </td>
                    <td className="px-5 py-3 text-gray-500">{d.lastSeen}</td>
                    <td className="px-5 py-3">
                      <div className="flex items-center justify-end gap-3 text-gray-400">
                        <button
                          onClick={() => onSelectDevice?.(d.id)}
                          className="hover:text-red-600"
                          aria-label={`Open ${d.id}`}
                        >
                          <ChevronRight className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 && (
                  <tr>
                    <td colSpan={9} className="px-5 py-10 text-center text-gray-500 text-sm">
                      No devices match your filters
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {addModalOpen && (
        <div className="fixed inset-0 bg-gray-900/40 flex items-center justify-center z-50 px-4">
          <div className="bg-white rounded-xl border border-gray-200 shadow-xl w-full max-w-sm p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-semibold text-gray-900">Add device</h3>
              <button onClick={() => setAddModalOpen(false)} className="text-gray-400 hover:text-gray-600">
                <X className="w-4 h-4" />
              </button>
            </div>
            <label className="block text-sm font-medium text-gray-900 mb-1.5">Device ID</label>
            <input
              value={newDeviceId}
              onChange={(e) => setNewDeviceId(e.target.value)}
              placeholder="e.g. EW-172"
              className="w-full px-3 py-2.5 rounded-lg border border-gray-200 text-sm outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500 mb-4"
            />
            <label className="block text-sm font-medium text-gray-900 mb-1.5">Assigned owner</label>
            <input
              value={newOwner}
              onChange={(e) => setNewOwner(e.target.value)}
              placeholder="e.g. R. Kapoor"
              className="w-full px-3 py-2.5 rounded-lg border border-gray-200 text-sm outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500 mb-5"
            />
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setAddModalOpen(false)}
                className="text-sm font-medium text-gray-600 hover:text-gray-900 px-3 py-2"
              >
                Cancel
              </button>
              <button
                onClick={handleAddDevice}
                className="bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
              >
                Register device
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}