"use client";

import { useState, useEffect, useMemo, useRef } from "react";
import axios from "axios";
import { toast } from "react-toastify";
import {
  MapPin,
  Navigation,
  Trash2,
  Edit,
  X,
  Power,
  PowerOff,
} from "lucide-react";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import { useMapEvents } from "react-leaflet";
import Swal from "sweetalert2";

// Fix for default marker icon issue in Leaflet
if (typeof window !== "undefined") {
  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",
  });
}

const MapContainer = dynamic(
  () => import("react-leaflet").then((mod) => mod.MapContainer),
  { ssr: false }
);
const TileLayer = dynamic(
  () => import("react-leaflet").then((mod) => mod.TileLayer),
  { ssr: false }
);
const Marker = dynamic(
  () => import("react-leaflet").then((mod) => mod.Marker),
  { ssr: false }
);

const containerStyle = {
  width: "100%",
  height: "400px",
};

const defaultZoom = 2; // Fallback zoom level for when no location is selected

// Conversion constants
const METERS_TO_FEET = 3.28084;
const FEET_TO_METERS = 1 / METERS_TO_FEET;

// Decode JWT payload
const decodeJwt = (token) => {
  try {
    const base64Url = token.split(".")[1]; // Get the payload part
    if (!base64Url) return {};
    const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split("")
        .map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
        .join("")
    );
    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error("Error decoding JWT:", error);
    return {};
  }
};

const OfficeLocationsAdmin = () => {
  const router = useRouter();
  const mapRef = useRef(null);
  const [locations, setLocations] = useState([]);
  const [formData, setFormData] = useState({
    name: "",
    latitude: "",
    longitude: "",
    max_distance: 50, // Stored in meters
    is_active: true,
  });
  const [distanceUnit, setDistanceUnit] = useState("meters"); // Track unit (meters or feet)
  const [lastInputValue, setLastInputValue] = useState(""); // Track raw input value for feet mode
  const [editingId, setEditingId] = useState(null);
  const [loading, setLoading] = useState(false);
  const [showMapModal, setShowMapModal] = useState(false);
  const [selectedLocation, setSelectedLocation] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [geolocating, setGeolocating] = useState(false);
  const [mapReady, setMapReady] = useState(false);
  const [isFirstModalOpen, setIsFirstModalOpen] = useState(true); // Track first modal open

  const { hasCreatePermission, hasEditPermission, hasDeletePermission } =
    useMemo(() => {
      const token = localStorage.getItem("adminToken");
      const session = token ? decodeJwt(token) : {};
      const roles = session.roles || [];
      const permissions = Array.from(
        new Set(roles.flatMap((role) => role.permissions || []))
      );

      return {
        hasCreatePermission: permissions.includes("create"),
        hasEditPermission: permissions.includes("update"),
        hasDeletePermission: permissions.includes("delete"),
      };
    }, []);

  useEffect(() => {
    const token = localStorage.getItem("adminToken");
    if (!token) {
      toast.error("Please log in to view office locations");
      setLoading(false);
      router.push("/");
      return;
    }

    fetchLocations();
  }, [router]);

  const fetchLocations = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem("adminToken");
      const response = await axios.get(
        "https://eammsapi.old.bluai.ai/api/office-locations",
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      const data = response.data;
      const locations = Array.isArray(data.office_locations)
        ? data.office_locations
        : [];
      setLocations(locations);
    } catch (error) {
      toast.error(
        error.response?.status === 401
          ? "Unauthorized: Please log in again"
          : "Failed to fetch locations"
      );
      console.error("Fetch locations error:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    if (name === "max_distance") {
      // Store raw input value for feet mode
      setLastInputValue(value);
      // Handle empty input as empty string
      if (value === "") {
        setFormData((prev) => ({
          ...prev,
          max_distance: "",
        }));
      } else {
        // Ensure only whole numbers
        const numericValue = parseInt(value);
        if (!isNaN(numericValue)) {
          setFormData((prev) => ({
            ...prev,
            max_distance:
              distanceUnit === "feet"
                ? Math.round(numericValue * FEET_TO_METERS)
                : numericValue,
          }));
        }
      }
    } else {
      setFormData((prev) => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  const handleUnitToggle = () => {
    setDistanceUnit((prev) => (prev === "meters" ? "feet" : "meters"));
    setLastInputValue(""); // Clear last input value on unit toggle
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (editingId && !hasEditPermission) {
      toast.error("You do not have permission to edit locations");
      return;
    }
    if (!editingId && !hasCreatePermission) {
      toast.error("You do not have permission to create locations");
      return;
    }

    // Validate max_distance
    if (formData.max_distance === "") {
      toast.error("Max Distance is required");
      return;
    }

    setLoading(true);
    try {
      const token = localStorage.getItem("adminToken");
      if (editingId) {
        await axios.post(
          `https://eammsapi.old.bluai.ai/api/office-locations/update/${editingId}`,
          formData,
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        );
        toast.success("Location updated successfully");
      } else {
        await axios.post(
          "https://eammsapi.old.bluai.ai/api/office-locations/create",
          formData,
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        );
        toast.success("Location created successfully");
      }
      resetForm();
      fetchLocations();
    } catch (error) {
      toast.error(error.response?.data?.message || "Operation failed");
      console.error("Submit error:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (location) => {
    if (!hasEditPermission) {
      toast.error("You do not have permission to edit locations");
      return;
    }
    setFormData({
      name: location.name,
      latitude: location.latitude,
      longitude: location.longitude,
      max_distance: location.max_distance, // Stored in meters
      is_active: location.is_active,
    });
    setLastInputValue(
      distanceUnit === "feet"
        ? Math.round(location.max_distance * METERS_TO_FEET).toString()
        : location.max_distance.toString()
    );
    setEditingId(location.id);
    setSelectedLocation([
      parseFloat(location.latitude),
      parseFloat(location.longitude),
    ]);
    setShowMapModal(true);
    setShowForm(true);
    setIsFirstModalOpen(false); // No geolocation for edit
    setDistanceUnit("meters"); // Reset to meters when editing
  };

  const handleDelete = async (id) => {
    if (!hasDeletePermission) {
      toast.error("You do not have permission to delete locations");
      return;
    }

    const result = await Swal.fire({
      title: "Are you sure?",
      text: "This location will be permanently deleted!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#d33",
      cancelButtonColor: "#3085d6",
      confirmButtonText: "Yes, delete it!",
      cancelButtonText: "Cancel",
    });

    if (!result.isConfirmed) return;

    setLoading(true);
    try {
      const token = localStorage.getItem("adminToken");
      await axios.delete(
        `https://eammsapi.old.bluai.ai/api/office-locations/delete/${id}`,
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );
      toast.success("Location deleted permanently");
      fetchLocations();
    } catch (error) {
      toast.error("Failed to delete location");
      console.error("Delete error:", error);
    } finally {
      setLoading(false);
    }
  };

  const toggleActiveStatus = async (id, currentStatus) => {
    if (!hasEditPermission) {
      toast.error("You do not have permission to toggle location status");
      return;
    }
    setLoading(true);
    try {
      const token = localStorage.getItem("adminToken");
      await axios.post(
        `https://eammsapi.old.bluai.ai/api/office-locations/toggle-status/${id}`,
        { is_active: !currentStatus },
        { headers: { Authorization: `Bearer ${token}` } }
      );
      toast.success(
        `Location ${currentStatus ? "disabled" : "enabled"} successfully`
      );
      fetchLocations();
    } catch (error) {
      toast.error(`Failed to ${currentStatus ? "disable" : "enable"} location`);
      console.error("Toggle status error:", error);
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setFormData({
      name: "",
      latitude: "",
      longitude: "",
      max_distance: 50,
      is_active: true,
    });
    setLastInputValue("");
    setEditingId(null);
    setShowMapModal(false);
    setSelectedLocation(null);
    setShowForm(false);
    setGeolocating(false);
    setMapReady(false);
    setIsFirstModalOpen(true); // Reset for next "Add Location"
    setDistanceUnit("meters"); // Reset to meters
  };

  const MapClickHandler = () => {
    const map = useMapEvents({
      click: (e) => {
        console.log("Map clicked:", e.latlng);
        const { lat, lng } = e.latlng;
        setSelectedLocation([lat, lng]);
        setFormData((prev) => ({
          ...prev,
          latitude: lat.toFixed(8).toString(),
          longitude: lng.toFixed(8).toString(),
        }));
        map.flyTo([lat, lng], 15);
      },
    });
    return null;
  };

  const handleAddLocationClick = () => {
    console.log("Add Location clicked");
    setShowMapModal(true);
    setFormData({
      name: "",
      latitude: "",
      longitude: "",
      max_distance: 50,
      is_active: true,
    });
    setLastInputValue("");
    setSelectedLocation(null);
    setShowForm(false);
    setGeolocating(true);
    setMapReady(false);
    setDistanceUnit("meters"); // Start with meters
  };

  const handleModalConfirm = () => {
    console.log(
      "Confirm clicked, formData:",
      formData,
      "selectedLocation:",
      selectedLocation
    );
    if (!formData.latitude || !formData.longitude) {
      toast.error("Please select a location on the map");
      return;
    }
    setShowMapModal(false);
    setShowForm(true);
    setIsFirstModalOpen(false); // Prevent geolocation on next modal open
  };

  // Automatically fetch user's current location
  const fetchUserLocation = () => {
    console.log("Attempting to fetch user location");
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
          console.log("Geolocation success:", { latitude, longitude });
          setSelectedLocation([latitude, longitude]);
          setFormData((prev) => ({
            ...prev,
            latitude: latitude.toFixed(8).toString(),
            longitude: longitude.toFixed(8).toString(),
          }));
          if (mapRef.current) {
            console.log("Flying to user location:", [latitude, longitude]);
            mapRef.current.flyTo([latitude, longitude], 15);
          } else {
            console.warn(
              "mapRef.current is not set during geolocation success"
            );
          }
          setGeolocating(false);
        },
        (error) => {
          console.error("Geolocation error:", error.message, error);
          toast.error(
            "Unable to retrieve location. Please allow geolocation access or select a location manually."
          );
          setSelectedLocation(); // Fallback: London coordinates
          if (mapRef.current) {
            mapRef.current.flyTo(defaultZoom);
          } else {
            console.warn("mapRef.current is not set on geolocation error");
          }
          setGeolocating(false);
        },
        { enableHighAccuracy: true, maximumAge: 0 }
      );
    } else {
      console.error("Geolocation not supported by browser");
      toast.error(
        "Geolocation is not supported by your browser. Please select a location manually."
      );
      setSelectedLocation(); // Fallback: London coordinates
      if (mapRef.current) {
        mapRef.current.flyTo(defaultZoom);
      } else {
        console.warn("mapRef.current is not set for non-supported geolocation");
      }
      setGeolocating(false);
    }
  };

  // Handle map initialization and geolocation
  useEffect(() => {
    if (showMapModal) {
      console.log("Map modal opened, waiting for mapRef.current");
      // Trigger geolocation only on first modal open for adding a location
      if (!editingId && isFirstModalOpen) {
        fetchUserLocation();
      } else if (editingId) {
        console.log("Editing mode, skipping geolocation");
        setGeolocating(false);
      } else {
        console.log("Not first modal open, skipping geolocation");
        setGeolocating(false);
        setSelectedLocation(); // Fallback: London coordinates
      }

      // Wait for mapRef.current to be set
      const checkMapReady = setInterval(() => {
        if (mapRef.current) {
          console.log("mapRef.current is set, invalidating size");
          mapRef.current.invalidateSize();
          setMapReady(true);
          if (selectedLocation) {
            console.log(
              "Flying to selected location after map ready:",
              selectedLocation
            );
            mapRef.current.flyTo(selectedLocation, 15);
          } else {
            mapRef.current.flyTo(defaultZoom);
          }
          clearInterval(checkMapReady);
        } else {
          console.log("mapRef.current still not set, waiting...");
        }
      }, 100);

      return () => {
        clearInterval(checkMapReady);
      };
    }
  }, [showMapModal, editingId, isFirstModalOpen]);

  // Convert max_distance for display
  const displayedMaxDistance = useMemo(() => {
    if (formData.max_distance === "") return "";
    if (distanceUnit === "feet") {
      // Use lastInputValue if available and valid, otherwise convert from meters
      const numericInput = parseInt(lastInputValue);
      if (!isNaN(numericInput)) {
        return numericInput.toString();
      }
      return Math.round(formData.max_distance * METERS_TO_FEET).toString();
    }
    return Math.round(formData.max_distance).toString();
  }, [formData.max_distance, distanceUnit, lastInputValue]);

  return (
    <div className="min-h-screen p-4 md:p-8">
      <div className="container bg-white p-8 rounded-xl shadow-lg overflow-hidden mx-auto max-w-6xl">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center space-x-2">
            <MapPin className="text-gray-800" size={24} />
            <h2 className="text-xl font-bold text-gray-800">
              Office Locations
            </h2>
          </div>
        </div>

        {!editingId && !showMapModal && hasCreatePermission && (
          <div className="mb-8">
            <button
              onClick={handleAddLocationClick}
              className="px-6 py-3 bg-purple-600 text-white font-medium rounded-full hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 transition-colors duration-200 flex items-center justify-center cursor-pointer"
            >
              <Navigation size={16} className="mr-2" />
              Add Location
            </button>
          </div>
        )}

        {(editingId || showForm) && (
          <div className="mb-8">
            <h3 className="text-lg font-semibold text-gray-800 flex items-center mb-4">
              <Navigation size={20} className="mr-2 text-gray-500" />
              {editingId ? "Edit Location" : "Add New Location"}
            </h3>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Location Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  name="name"
                  value={formData.name}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-600 text-gray-800"
                  required
                />
              </div>

              <div className="flex space-x-4">
                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Latitude <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="number"
                    name="latitude"
                    value={formData.latitude}
                    onChange={handleInputChange}
                    step="0.00000001"
                    min="-90"
                    max="90"
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-600 text-gray-800"
                    required
                  />
                </div>
                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Longitude <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="number"
                    name="longitude"
                    value={formData.longitude}
                    onChange={handleInputChange}
                    step="0.00000001"
                    min="-180"
                    max="180"
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-600 text-gray-800"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Max Distance ({distanceUnit}){" "}
                  <span className="text-red-500">*</span>
                </label>
                <div className="flex items-center space-x-2">
                  <div className="relative flex-1">
                    <input
                      type="number"
                      name="max_distance"
                      value={displayedMaxDistance}
                      onChange={handleInputChange}
                      min="0"
                      max={distanceUnit === "meters" ? 15000 : 49213}
                      step="1"
                      className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-purple-600 text-gray-800 pr-16 ${
                        distanceUnit === "meters"
                          ? "border-blue-500"
                          : "border-green-500"
                      }`}
                      required
                    />
                    <span className="absolute right-2 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">
                      {distanceUnit}
                    </span>
                  </div>
                  <button
                    type="button"
                    onClick={handleUnitToggle}
                    className="px-3 py-2 bg-gray-200 text-gray-700 font-medium rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 transition-colors duration-200 cursor-pointer"
                  >
                    {distanceUnit === "meters" ? "Feet" : "Meters"}
                  </button>
                </div>
              </div>

              <div className="flex items-center">
                <label className="block text-sm font-medium text-gray-700">
                  Status
                </label>
                <input
                  type="checkbox"
                  name="is_active"
                  checked={formData.is_active}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      is_active: e.target.checked,
                    }))
                  }
                  className="ml-2 h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded cursor-pointer"
                />
                <span className="ml-2 text-sm text-gray-700">
                  {formData.is_active ? "Active" : "Inactive"}
                </span>
              </div>

              <div className="flex space-x-4 pt-2">
                {hasCreatePermission && (
                  <button
                    type="submit"
                    disabled={loading}
                    className="w-full px-6 py-3 bg-purple-600 text-white font-medium rounded-full hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 transition-colors duration-200 disabled:opacity-50 flex items-center justify-center cursor-pointer"
                  >
                    <Navigation size={16} className="mr-2" />
                    {loading
                      ? "Processing..."
                      : editingId
                      ? "Update Location"
                      : "Add Location"}
                  </button>
                )}
                <button
                  type="button"
                  onClick={resetForm}
                  className="px-4 py-3 bg-gray-200 text-gray-700 font-medium rounded-full hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 transition-colors duration-200 flex items-center justify-center cursor-pointer"
                >
                  <X size={16} className="mr-2" />
                  Cancel
                </button>
              </div>
            </form>
          </div>
        )}

        {showMapModal && (
          <div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <div className="bg-white p-6 rounded-lg max-w-4xl w-full">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold text-gray-800">
                  Select Location
                </h3>
                <button
                  onClick={() => setShowMapModal(false)}
                  className="text-gray-600 hover:text-gray-800 cursor-pointer"
                >
                  <X size={24} />
                </button>
              </div>
              {geolocating && !mapReady ? (
                <div className="flex justify-center items-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
                  <p className="ml-2 text-gray-600">Locating...</p>
                </div>
              ) : (
                <MapContainer
                  center={selectedLocation}
                  zoom={selectedLocation ? 15 : defaultZoom}
                  style={containerStyle}
                  attributionControl={false} // disables default attribution
                  whenCreated={(map) => {
                    mapRef.current = map;
                    map.invalidateSize();
                    setMapReady(true);
                    if (selectedLocation) {
                      map.flyTo(selectedLocation, 15);
                    }
                  }}
                >
                  <TileLayer
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    attribution="" // optional: override any attribution from the tile layer
                  />
                  <MapClickHandler />
                  {selectedLocation && (
                    <>
                      <Marker position={selectedLocation} />
                    </>
                  )}
                </MapContainer>
              )}
              <div className="flex justify-end mt-4">
                <button
                  onClick={handleModalConfirm}
                  className="px-4 py-2 bg-purple-600 text-white font-medium rounded-full hover:bg-purple-700 cursor-pointer"
                >
                  Confirm Location
                </button>
              </div>
            </div>
          </div>
        )}

        <div>
          <h3 className="text-lg font-semibold text-gray-800 flex items-center mb-4">
            <MapPin size={20} className="mr-2 text-gray-500" />
            Office Locations
          </h3>
          <div className="space-y-4">
            {loading && locations.length === 0 ? (
              <div className="flex justify-center items-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
              </div>
            ) : locations.length === 0 ? (
              <div className="flex justify-center items-center py-8">
                <p className="text-gray-500">No office locations found.</p>
              </div>
            ) : (
              locations.map((location) => (
                <div
                  key={location.id}
                  className={`border rounded-lg p-4 transition-all ${
                    location.is_active
                      ? "border-gray-200 bg-white"
                      : "border-gray-100 bg-gray-50 opacity-75"
                  }`}
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="flex items-center">
                        <h6
                          className={`font-bold text-base ${
                            location.is_active
                              ? "text-gray-900"
                              : "text-gray-500"
                          }`}
                        >
                          {location.name}
                        </h6>
                        {!location.is_active && (
                          <span className="ml-2 px-2 py-0.5 text-xs bg-gray-200 text-gray-600 rounded">
                            Disabled
                          </span>
                        )}
                      </div>
                      <div className="grid grid-cols-2 gap-x-4 gap-y-1 mt-2 text-sm">
                        <p
                          className={
                            location.is_active
                              ? "text-gray-600"
                              : "text-gray-400"
                          }
                        >
                          <span className="font-semibold">Latitude:</span>{" "}
                          {location.latitude}
                        </p>
                        <p
                          className={
                            location.is_active
                              ? "text-gray-600"
                              : "text-gray-400"
                          }
                        >
                          <span className="font-semibold">Longitude:</span>{" "}
                          {location.longitude}
                        </p>
                        <p
                          className={`col-span-2 ${
                            location.is_active
                              ? "text-gray-600"
                              : "text-gray-400"
                          }`}
                        >
                          <span className="font-semibold">Radius:</span>{" "}
                          {`${Math.round(location.max_distance)}m/${Math.round(
                            location.max_distance * METERS_TO_FEET
                          )}ft`}
                        </p>
                      </div>
                    </div>
                    <div className="flex space-x-2">
                      {hasEditPermission && (
                        <button
                          onClick={() =>
                            toggleActiveStatus(location.id, location.is_active)
                          }
                          className={`p-2 rounded-full cursor-pointer ${
                            location.is_active
                              ? "text-yellow-600 hover:bg-yellow-100"
                              : "text-green-600 hover:bg-green-100"
                          } transition-colors duration-200`}
                          title={location.is_active ? "Disable" : "Enable"}
                          disabled={loading}
                        >
                          {location.is_active ? (
                            <PowerOff size={20} />
                          ) : (
                            <Power size={20} />
                          )}
                        </button>
                      )}
                      {hasEditPermission && (
                        <button
                          onClick={() => handleEdit(location)}
                          className="p-2 text-blue-600 hover:bg-blue-100 rounded-full transition-colors duration-200 cursor-pointer"
                          title="Edit"
                          disabled={loading}
                        >
                          <Edit size={20} />
                        </button>
                      )}
                      {hasDeletePermission && (
                        <button
                          onClick={() => handleDelete(location.id)}
                          className="p-2 text-red-600 hover:bg-red-100 rounded-full transition-colors duration-200 cursor-pointer"
                          title="Delete"
                          disabled={loading}
                        >
                          <Trash2 size={20} />
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default OfficeLocationsAdmin;
