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 {
  Building2,
  MapPin,
  Layers,
  DoorOpen,
  Plus,
  Pencil,
  Trash2,
  Search,
  ChevronRight,
  ChevronDown,
  X,
  Check,
  Clock,
  Home,
  DoorClosed,
} from "lucide-react";

export default function Organization({ onMenuClick }) {
  const { rows: organizations, loading: orgLoading, update: updateOrg } = useLiveRows("organizations");
  const { rows: branches, loading: branchLoading, add: addBranch, update: updateBranch, remove: removeBranch } = useLiveRows("branches");
  const { rows: buildings, loading: buildingLoading } = useLiveRows("buildings");
  const { rows: floors, loading: floorLoading } = useLiveRows("floors");
  const { rows: doors, loading: doorLoading } = useLiveRows("doors");

  const org = organizations[0];
  const [orgName, setOrgName] = useState("");
  const [orgIndustry, setOrgIndustry] = useState("");
  const [toastMessage, setToastMessage] = useState("");

  React.useEffect(() => {
    if (org) {
      setOrgName(org.name || "EyeRexUs Technologies");
      setOrgIndustry(org.industry || "IT Services & IoT");
    }
  }, [org]);

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

  const [search, setSearch] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const [newBranchName, setNewBranchName] = useState("");
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [editBranchId, setEditBranchId] = useState(null);
  const [editBranchName, setEditBranchName] = useState("");
  const [expanded, setExpanded] = useState({});

  const loading = orgLoading || branchLoading || buildingLoading || floorLoading || doorLoading;

  const hierarchy = useMemo(() => {
    return branches.map((b) => {
      const branchBuildings = buildings.filter((bl) => bl.branchId === b.id || bl.branch === b.name);
      return {
        branch: b.name,
        branchId: b.id,
        buildings: branchBuildings.map((bl) => {
          const bFloors = floors.filter((f) => f.buildingId === bl.id || f.building === bl.name);
          return {
            name: bl.name,
            floors: bFloors.map((f) => {
              const doorCount = doors.filter((d) => d.floorId === f.id || d.floor === f.name).length;
              return `${f.name || f.label || "Floor"} - ${doorCount || f.doors || 0} doors`;
            }),
          };
        }),
      };
    });
  }, [branches, buildings, floors, doors]);

  const filteredBranches = branches.filter((b) =>
    b.name.toLowerCase().includes(search.toLowerCase())
  );

  const openEditModal = (branch) => {
    setEditBranchId(branch.id);
    setEditBranchName(branch.name);
    setEditModalOpen(true);
  };

  const handleSaveEdit = async () => {
    if (!editBranchName.trim() || !editBranchId) return;
    const row = branches.find((b) => b.id === editBranchId);
    if (row) await updateBranch(editBranchId, { ...row, name: editBranchName.trim() });
    setEditModalOpen(false);
    showToast("Branch updated");
  };

  const toggleExpand = (key) =>
    setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));

  const handleSaveProfile = async () => {
    if (org?.id) {
      await updateOrg(org.id, { ...org, name: orgName, industry: orgIndustry });
    }
    showToast("Organization profile saved");
  };

  const handleAddBranch = async () => {
    if (!newBranchName.trim()) return;
    const name = newBranchName.trim();
    await addBranch({ name, buildings: 0, devices: 0, status: "Setup" });
    setNewBranchName("");
    setModalOpen(false);
    showToast(`${name} added`);
  };

  const handleDeleteBranch = async (id) => {
    const branch = branches.find((b) => b.id === id);
    await removeBranch(id);
    if (branch) showToast(`${branch.name} removed`);
  };

  const floorsMapped = floors.length;
  const doorsRegistered = doors.length;

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

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

      <div className="max-w-[1600px] mx-auto px-8 py-8">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-xl font-semibold text-gray-900">Organization</h1>
            <p className="text-sm text-gray-500 mt-1">
              Manage your organization profile and location hierarchy
            </p>
          </div>
        </div>

        {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="bg-white border border-gray-200 rounded-xl p-6 mb-6">
          <div className="flex items-center gap-2 mb-5">
            <Building2 className="w-4 h-4 text-red-600" />
            <h2 className="text-sm font-semibold text-gray-900">Organization profile</h2>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
            <div className="lg:col-span-2">
              <label className="block text-sm font-medium text-gray-900 mb-1.5">
                Organization name
              </label>
              <input
                value={orgName}
                onChange={(e) => setOrgName(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg border border-gray-200 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500"
              />
            </div>
            <div className="lg:col-span-2">
              <label className="block text-sm font-medium text-gray-900 mb-1.5">Industry</label>
              <input
                value={orgIndustry}
                onChange={(e) => setOrgIndustry(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg border border-gray-200 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500"
              />
            </div>
          </div>

          <div className="flex justify-end mt-5">
            <button
              onClick={handleSaveProfile}
              className="bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
            >
              Save changes
            </button>
          </div>
        </div>

        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
          {[
            { label: "Branches", value: branches.length, icon: MapPin },
            { label: "Buildings", value: buildings.length, icon: Building2 },
            { label: "Floors mapped", value: floorsMapped, icon: Layers },
            { label: "Doors registered", value: doorsRegistered, icon: DoorOpen },
          ].map(({ label, value, icon: Icon }) => (
            <div key={label} className="bg-white border border-gray-200 rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <Icon className="w-4 h-4 text-red-600" />
                <span className="text-xs text-gray-500">{label}</span>
              </div>
              <p className="text-2xl font-semibold text-gray-900">{value}</p>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
          <div className="xl:col-span-2 flex flex-col gap-6">
            <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 px-5 py-4 border-b border-gray-200">
                <h2 className="text-sm font-semibold text-gray-900">Branches</h2>
                <div className="flex items-center gap-3">
                  <div className="relative flex-1 sm:flex-none">
                    <Search className="w-3.5 h-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
                    <input
                      value={search}
                      onChange={(e) => setSearch(e.target.value)}
                      placeholder="Search branches"
                      className="pl-8 pr-3 py-1.5 text-sm rounded-lg border border-gray-200 outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500 w-full sm:w-48"
                    />
                  </div>
                  <button
                    onClick={() => setModalOpen(true)}
                    className="flex items-center gap-1.5 bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-3 py-1.5 rounded-lg transition-colors"
                  >
                    <Plus className="w-3.5 h-3.5" />
                    Add branch
                  </button>
                </div>
              </div>

              <div className="overflow-x-auto">
              <table className="w-full text-sm min-w-[600px]">
                <thead>
                  <tr className="text-left text-gray-500 border-b border-gray-200">
                    <th className="px-5 py-3 font-medium">Branch</th>
                    <th className="px-5 py-3 font-medium">Buildings</th>
                    <th className="px-5 py-3 font-medium">Devices</th>
                    <th className="px-5 py-3 font-medium">Status</th>
                    <th className="px-5 py-3 font-medium text-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredBranches.map((b) => (
                    <tr
                      key={b.id}
                      className="border-b border-gray-200 last:border-0 hover:bg-gray-100 transition-colors"
                    >
                      <td className="px-5 py-3">
                        <div className="flex items-center gap-2 text-gray-900 font-medium">
                          <MapPin className="w-3.5 h-3.5 text-gray-400" />
                          {b.name}
                        </div>
                      </td>
                      <td className="px-5 py-3 text-gray-600">{b.buildings ?? buildings.filter((bl) => bl.branchId === b.id).length}</td>
                      <td className="px-5 py-3 text-gray-600">{b.devices ?? 0}</td>
                      <td className="px-5 py-3">
                        <span
                          className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                            b.status === "Active"
                              ? "bg-red-50 text-red-600 border border-red-200"
                              : "bg-gray-100 text-gray-500 border border-gray-200"
                          }`}
                        >
                          {b.status || "Setup"}
                        </span>
                      </td>
                      <td className="px-5 py-3">
                        <div className="flex items-center justify-end gap-3 text-gray-400">
                          <button
                            onClick={() => openEditModal(b)}
                            className="hover:text-red-600"
                            aria-label={`Edit ${b.name}`}
                          >
                            <Pencil className="w-3.5 h-3.5" />
                          </button>
                          <button onClick={() => handleDeleteBranch(b.id)} className="hover:text-red-600">
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                          <ChevronRight className="w-3.5 h-3.5" />
                        </div>
                      </td>
                    </tr>
                  ))}
                  {filteredBranches.length === 0 && (
                    <tr>
                      <td colSpan={5} className="px-5 py-8 text-center text-gray-500 text-sm">
                        No branches match "{search}"
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
              </div>
            </div>

            <div className="bg-white border border-gray-200 rounded-xl overflow-hidden flex-1">
              <div className="px-5 py-4 border-b border-gray-200 flex items-center gap-2">
                <Layers className="w-4 h-4 text-red-600" />
                <h2 className="text-sm font-semibold text-gray-900">Location hierarchy</h2>
              </div>
              <div className="p-2">
                {hierarchy.length === 0 && (
                  <p className="text-sm text-gray-400 text-center py-8">No hierarchy data yet.</p>
                )}
                {hierarchy.map((h) => (
                  <div key={h.branchId || h.branch} className="mb-1 last:mb-0">
                    <button
                      onClick={() => toggleExpand(h.branch)}
                      className="w-full flex items-center gap-2 px-3 py-2.5 rounded-lg hover:bg-gray-100 transition-colors"
                    >
                      {expanded[h.branch] ? (
                        <ChevronDown className="w-3.5 h-3.5 text-gray-400" />
                      ) : (
                        <ChevronRight className="w-3.5 h-3.5 text-gray-400" />
                      )}
                      <MapPin className="w-3.5 h-3.5 text-red-600" />
                      <span className="text-sm font-medium text-gray-900">{h.branch}</span>
                    </button>
                    {expanded[h.branch] && (
                      <div className="ml-8 border-l border-gray-200 pl-4 mb-1">
                        {h.buildings.map((bld) => (
                          <div key={bld.name} className="py-1.5">
                            <div className="flex items-center gap-2">
                              <Home className="w-3.5 h-3.5 text-gray-400" />
                              <span className="text-sm text-gray-800 font-medium">{bld.name}</span>
                            </div>
                            <div className="ml-6 mt-1 flex flex-col gap-1">
                              {bld.floors.map((f) => (
                                <div key={f} className="flex items-center gap-2 text-xs text-gray-500">
                                  <DoorClosed className="w-3 h-3 text-gray-300" />
                                  {f}
                                </div>
                              ))}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="xl:col-span-1">
            <div className="bg-white border border-gray-200 rounded-xl overflow-hidden h-full">
              <div className="px-5 py-4 border-b border-gray-200 flex items-center gap-2">
                <Clock className="w-4 h-4 text-red-600" />
                <h2 className="text-sm font-semibold text-gray-900">Recent activity</h2>
              </div>
              <div className="divide-y divide-gray-200">
                {[
                  { text: `${branches.length} branches configured`, time: "Live" },
                  { text: `${doorsRegistered} doors registered`, time: "Live" },
                ].map((a, i) => (
                  <div key={i} className="px-5 py-4 flex gap-3">
                    <div className="w-1.5 h-1.5 rounded-full bg-red-600 mt-1.5 shrink-0" />
                    <div>
                      <p className="text-sm text-gray-900 leading-snug">{a.text}</p>
                      <p className="text-xs text-gray-400 mt-1">{a.time}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      {modalOpen && (
        <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 branch</h3>
              <button onClick={() => setModalOpen(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">Branch name</label>
            <input
              value={newBranchName}
              onChange={(e) => setNewBranchName(e.target.value)}
              placeholder="e.g. Pune Office"
              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={() => setModalOpen(false)}
                className="text-sm font-medium text-gray-600 hover:text-gray-900 px-3 py-2"
              >
                Cancel
              </button>
              <button
                onClick={handleAddBranch}
                className="bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
              >
                Add branch
              </button>
            </div>
          </div>
        </div>
      )}

      {editModalOpen && (
        <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">Edit branch</h3>
              <button
                onClick={() => setEditModalOpen(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">
              Branch name
            </label>
            <input
              value={editBranchName}
              onChange={(e) => setEditBranchName(e.target.value)}
              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={() => setEditModalOpen(false)}
                className="text-sm font-medium text-gray-600 hover:text-gray-900 px-3 py-2"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveEdit}
                className="bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
              >
                Save changes
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
