/**
 * Active Map Page
 * 
 * Displays hospitals/locations on an interactive map with markers showing:
 * - Asset counts
 * - Work Order counts (Normal/Urgent, by status)
 * - Maintenance Log counts (Planned/Completed/Overdue)
 * 
 * Also displays Department locations (custom_is_wo_type == 1) which show:
 * - Only Work Order counts (filtered by work_order_type field)
 * - Filtered by User Permission (allow = "Issue Type", for_value = Location name)
 * 
 * Permission Logic for Departments:
 * - If user has User Permission entries for "Issue Type" → only show matching departments
 * - If user has NO User Permission entries for "Issue Type" → show ALL departments
 * 
 * Replicates the Frappe "active-map" page functionality
 */

import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { MapContainer, TileLayer, Marker, Popup, Tooltip, useMap } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import apiService from '../services/apiService';
import LinkField from '../components/LinkField';

// Fix for default marker icons in React-Leaflet
import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';

const DefaultIcon = L.icon({
  iconUrl: icon,
  shadowUrl: iconShadow,
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  tooltipAnchor: [16, -28],
  shadowSize: [41, 41]
});

L.Marker.prototype.options.icon = DefaultIcon;

// Create a different colored icon for departments
const DepartmentIcon = L.icon({
  iconUrl: icon,
  shadowUrl: iconShadow,
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  tooltipAnchor: [16, -28],
  shadowSize: [41, 41],
  className: 'department-marker-icon'
});

interface LocationData {
  name: string;
  latitude: number;
  longitude: number;
  assets: number;
  normal_work_orders: number;
  urgent_work_orders: number;
  planned_maintenance: number;
  completed_maintenance: number;
  overdue_maintenance: number;
  wo_open: number;
  wo_progress: number;
  wo_review: number;
  wo_completed: number;
  wo_closed: number;
  locationType: 'hospital' | 'department'; // To distinguish between hospital and department locations
}

// Component to handle map bounds fitting
const MapBounds: React.FC<{ locations: LocationData[] }> = ({ locations }) => {
  const map = useMap();
  
  useEffect(() => {
    if (locations.length > 0 && locations.some(l => l.latitude && l.longitude)) {
      const bounds = L.latLngBounds(
        locations
          .filter(l => l.latitude && l.longitude)
          .map(l => [l.latitude, l.longitude] as [number, number])
      );
      map.fitBounds(bounds, { padding: [30, 30], maxZoom: 8 });
    } else {
      // Fallback: show Saudi Arabia center
      map.setView([24.8, 45.5], 6);
    }
  }, [locations, map]);
  
  return null;
};

const ActiveMap: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [selectedHospital, setSelectedHospital] = useState<string>('');
  const [selectedDepartment, setSelectedDepartment] = useState<string>('');
  const [locations, setLocations] = useState<LocationData[]>([]);
  const [loading, setLoading] = useState(true);
  const markersRef = useRef<Record<string, L.Marker>>({});

  // ✅ NEW: User Permission state for Issue Type
  const [permittedDepartments, setPermittedDepartments] = useState<string[] | null>(null); // null = not loaded yet
  const [permissionsLoaded, setPermissionsLoaded] = useState(false);

  // ✅ NEW: Fetch User Permissions for "Issue Type" on mount
  useEffect(() => {
    const fetchUserPermissions = async () => {
      try {
        // Step 1: Get logged-in user using fetch directly
        const userRes = await fetch('/api/method/frappe.auth.get_logged_user');
        const userData = await userRes.json();
        const loggedInUser = userData?.message;

        if (!loggedInUser) {
          console.warn('[ActiveMap] Could not determine logged-in user, response:', userData);
          setPermittedDepartments(null);
          setPermissionsLoaded(true);
          return;
        }

        console.log('[ActiveMap] Logged-in user:', loggedInUser);

        // Step 2: Fetch User Permission entries where allow = "Issue Type"
        const permRes = await fetch(
          `/api/resource/User Permission?filters=${encodeURIComponent(JSON.stringify({
            user: loggedInUser,
            allow: 'Issue Type'
          }))}&fields=["for_value"]&limit_page_length=0`
        );
        const permData = await permRes.json();
        const permEntries = permData?.data || [];

        if (permEntries.length > 0) {
          const allowedValues = permEntries.map((p: any) => p.for_value).filter(Boolean);
          console.log('[ActiveMap] Allowed departments:', allowedValues);
          setPermittedDepartments(allowedValues);
        } else {
          console.log('[ActiveMap] No Issue Type permissions → showing all departments');
          setPermittedDepartments(null);
        }
      } catch (err) {
        console.error('[ActiveMap] Error fetching User Permissions:', err);
        setPermittedDepartments(null);
      } finally {
        setPermissionsLoaded(true);
      }
    };

    fetchUserPermissions();
  }, []);

  // Fetch locations and their counts
  const fetchAndRenderData = async () => {
    // ✅ Wait for permissions to load before fetching data
    if (!permissionsLoaded) return;

    setLoading(true);
    try {
      const allLocations: LocationData[] = [];

      // ============== FETCH HOSPITAL LOCATIONS ==============
      if (!selectedDepartment) {
        // Only fetch hospitals if no department is selected (or both can be shown)
        const hospitalFilters: Record<string, any> = {
          latitude: ['!=', ''],
          longitude: ['!=', ''],
          custom_is_hospital: 1
        };

        if (selectedHospital) {
          hospitalFilters.name = selectedHospital;
        }

        const hospitalsResponse = await apiService.apiCall<any>(
          `/api/resource/Location?filters=${encodeURIComponent(JSON.stringify(hospitalFilters))}&fields=["name","latitude","longitude"]&limit_page_length=0`
        );

        const hospitalList = hospitalsResponse?.data || [];

        // For each hospital, fetch counts
        const hospitalPromises = hospitalList.map(async (location: any) => {
          const counts: Partial<LocationData> = {
            assets: 0,
            normal_work_orders: 0,
            urgent_work_orders: 0,
            planned_maintenance: 0,
            completed_maintenance: 0,
            overdue_maintenance: 0,
            wo_open: 0,
            wo_progress: 0,
            wo_review: 0,
            wo_completed: 0,
            wo_closed: 0,
            locationType: 'hospital'
          };

          try {
            // Fetch Asset count
            const assetsResponse = await apiService.apiCall<any>(
              `/api/resource/Asset?filters=${encodeURIComponent(JSON.stringify({ company: location.name }))}&fields=["name"]&limit_page_length=0`
            );
            counts.assets = assetsResponse?.data?.length || 0;

            // Fetch Normal Work Orders - including Closed status
            const normalWOResponse = await apiService.apiCall<any>(
              `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                company: location.name,
                custom_priority_: 'Normal',
                repair_status: ['in', ['Open', 'Work In Progress', 'Closed']]
              }))}&fields=["name"]&limit_page_length=0`
            );
            counts.normal_work_orders = normalWOResponse?.data?.length || 0;

            // Fetch Urgent Work Orders - including Closed status
            const urgentWOResponse = await apiService.apiCall<any>(
              `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                company: location.name,
                custom_priority_: 'Urgent',
                repair_status: ['in', ['Open', 'Work In Progress', 'Closed']]
              }))}&fields=["name"]&limit_page_length=0`
            );
            counts.urgent_work_orders = urgentWOResponse?.data?.length || 0;

            // Fetch WO Status counts and Maintenance counts
            const [woOpen, woProgress, woReview, woCompleted, woClosed, plannedPM, completedPM, overduePM] = await Promise.all([
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  company: location.name,
                  repair_status: 'Open'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  company: location.name,
                  repair_status: 'Work In Progress'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  company: location.name,
                  repair_status: 'Pending Review'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  company: location.name,
                  repair_status: 'Completed'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  company: location.name,
                  repair_status: 'Closed'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Asset Maintenance Log?filters=${encodeURIComponent(JSON.stringify({
                  custom_hospital_name: location.name,
                  maintenance_status: 'Planned'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Asset Maintenance Log?filters=${encodeURIComponent(JSON.stringify({
                  custom_hospital_name: location.name,
                  maintenance_status: 'Completed'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Asset Maintenance Log?filters=${encodeURIComponent(JSON.stringify({
                  custom_hospital_name: location.name,
                  maintenance_status: 'Overdue'
                }))}&fields=["name"]&limit_page_length=0`
              )
            ]);

            counts.wo_open = woOpen?.data?.length || 0;
            counts.wo_progress = woProgress?.data?.length || 0;
            counts.wo_review = woReview?.data?.length || 0;
            counts.wo_completed = woCompleted?.data?.length || 0;
            counts.wo_closed = woClosed?.data?.length || 0;
            counts.planned_maintenance = plannedPM?.data?.length || 0;
            counts.completed_maintenance = completedPM?.data?.length || 0;
            counts.overdue_maintenance = overduePM?.data?.length || 0;
          } catch (err) {
            console.error(`Error fetching counts for hospital ${location.name}:`, err);
          }

          return {
            name: location.name,
            latitude: parseFloat(location.latitude),
            longitude: parseFloat(location.longitude),
            ...counts
          } as LocationData;
        });

        const hospitalResults = await Promise.all(hospitalPromises);
        allLocations.push(...hospitalResults.filter(l => !isNaN(l.latitude) && !isNaN(l.longitude)));
      }

      // ============== FETCH DEPARTMENT LOCATIONS (custom_is_wo_type == 1) ==============
      if (!selectedHospital) {
        // Only fetch departments if no hospital is selected (or both can be shown)
        const departmentFilters: Record<string, any> = {
          latitude: ['!=', ''],
          longitude: ['!=', ''],
          custom_is_wo_type: 1
        };

        if (selectedDepartment) {
          departmentFilters.name = selectedDepartment;
        }

        // ✅ NEW: If user has Issue Type permissions, restrict to only permitted department names
        if (permittedDepartments !== null && permittedDepartments.length > 0 && !selectedDepartment) {
          // Only fetch locations whose name is in the user's permitted list
          departmentFilters.name = ['in', permittedDepartments];
        } else if (permittedDepartments !== null && permittedDepartments.length === 0) {
          // User has permission entries but none matched — show nothing
          console.log('[ActiveMap] User has Issue Type permissions but no matching values — skipping departments');
          // Skip fetching departments entirely
          setLocations(allLocations);
          setLoading(false);
          return;
        }
        // If permittedDepartments is null → no restriction, fetch all

        console.log('[ActiveMap] Department filters:', departmentFilters);

        const departmentsResponse = await apiService.apiCall<any>(
          `/api/resource/Location?filters=${encodeURIComponent(JSON.stringify(departmentFilters))}&fields=["name","latitude","longitude"]&limit_page_length=0`
        );

        const departmentList = departmentsResponse?.data || [];

        console.log('[ActiveMap] Departments to show on map:', departmentList.map((d: any) => d.name));

        // For each department, fetch ONLY Work Order counts (filtered by work_order_type)
        const departmentPromises = departmentList.map(async (location: any) => {
          const counts: Partial<LocationData> = {
            assets: 0, // Not applicable for departments
            normal_work_orders: 0,
            urgent_work_orders: 0,
            planned_maintenance: 0, // Not applicable for departments
            completed_maintenance: 0, // Not applicable for departments
            overdue_maintenance: 0, // Not applicable for departments
            wo_open: 0,
            wo_progress: 0,
            wo_review: 0,
            wo_completed: 0,
            wo_closed: 0,
            locationType: 'department'
          };

          try {
            // For departments, filter Work Orders by work_order_type field (not company)
            // The location name matches the work_order_type value in Work_Order doctype

            // Fetch Normal Work Orders by work_order_type
            const normalWOResponse = await apiService.apiCall<any>(
              `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                work_order_type: location.name,
                custom_priority_: 'Normal',
                repair_status: ['in', ['Open', 'Work In Progress', 'Closed']]
              }))}&fields=["name"]&limit_page_length=0`
            );
            counts.normal_work_orders = normalWOResponse?.data?.length || 0;

            // Fetch Urgent Work Orders by work_order_type
            const urgentWOResponse = await apiService.apiCall<any>(
              `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                work_order_type: location.name,
                custom_priority_: 'Urgent',
                repair_status: ['in', ['Open', 'Work In Progress', 'Closed']]
              }))}&fields=["name"]&limit_page_length=0`
            );
            counts.urgent_work_orders = urgentWOResponse?.data?.length || 0;

            // Fetch WO Status counts by work_order_type
            const [woOpen, woProgress, woReview, woCompleted, woClosed] = await Promise.all([
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  work_order_type: location.name,
                  repair_status: 'Open'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  work_order_type: location.name,
                  repair_status: 'Work In Progress'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  work_order_type: location.name,
                  repair_status: 'Pending Review'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  work_order_type: location.name,
                  repair_status: 'Completed'
                }))}&fields=["name"]&limit_page_length=0`
              ),
              apiService.apiCall<any>(
                `/api/resource/Work_Order?filters=${encodeURIComponent(JSON.stringify({
                  work_order_type: location.name,
                  repair_status: 'Closed'
                }))}&fields=["name"]&limit_page_length=0`
              )
            ]);

            counts.wo_open = woOpen?.data?.length || 0;
            counts.wo_progress = woProgress?.data?.length || 0;
            counts.wo_review = woReview?.data?.length || 0;
            counts.wo_completed = woCompleted?.data?.length || 0;
            counts.wo_closed = woClosed?.data?.length || 0;
          } catch (err) {
            console.error(`Error fetching counts for department ${location.name}:`, err);
          }

          return {
            name: location.name,
            latitude: parseFloat(location.latitude),
            longitude: parseFloat(location.longitude),
            ...counts
          } as LocationData;
        });

        const departmentResults = await Promise.all(departmentPromises);
        allLocations.push(...departmentResults.filter(l => !isNaN(l.latitude) && !isNaN(l.longitude)));
      }

      setLocations(allLocations);
    } catch (error) {
      console.error('Error fetching map data:', error);
    } finally {
      setLoading(false);
    }
  };

  // ✅ UPDATED: Add permissionsLoaded as dependency so data fetches after permissions are resolved
  useEffect(() => {
    fetchAndRenderData();
  }, [selectedHospital, selectedDepartment, permissionsLoaded]);

  // Handle filter changes - clear the other filter when one is selected
  const handleHospitalChange = (value: string) => {
    setSelectedHospital(value);
    if (value) {
      setSelectedDepartment(''); // Clear department when hospital is selected
    }
  };

  const handleDepartmentChange = (value: string) => {
    setSelectedDepartment(value);
    if (value) {
      setSelectedHospital(''); // Clear hospital when department is selected
    }
  };

  // Navigate to list view with filters
  const navigateToWorkOrders = (locationName: string, locationType: 'hospital' | 'department', priority?: string, status?: string) => {
    const params = new URLSearchParams();
    
    if (locationType === 'hospital') {
      if (locationName) params.set('company', locationName);
    } else {
      // For departments, filter by work_order_type
      if (locationName) params.set('work_order_type', locationName);
    }
    
    if (priority) params.set('priority', priority);
    if (status) params.set('status', status);
    navigate(`/work-orders?${params.toString()}`);
  };

  const navigateToAssets = (hospital: string) => {
    const params = new URLSearchParams();
    if (hospital) params.set('company', hospital);
    navigate(`/assets?${params.toString()}`);
  };

  const navigateToMaintenanceCalendar = (hospital: string, status?: string) => {
    const params = new URLSearchParams();
    if (hospital) params.set('hospital', hospital);
    if (status) params.set('status', status);
    navigate(`/maintenance-calendar?${params.toString()}`);
  };

  // Create popup content for HOSPITAL locations (full data)
  const createHospitalPopupContent = (location: LocationData) => {
    return (
      <div className="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg min-w-[280px] max-w-[320px]">
        {/* Hospital Name Header */}
        <div className="mb-4 pb-3 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2">
            <span className="px-2 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded text-xs font-medium">
              {t('activeMap.hospital')}
            </span>
          </div>
          <h3 className="text-lg font-bold text-gray-900 dark:text-white mt-1">
            {location.name}
          </h3>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            {t('activeMap.totalAssets')}: <span className="font-semibold text-gray-900 dark:text-white">{location.assets}</span>
          </p>
        </div>

        {/* Work Order Status Section */}
        <div className="mb-4">
          <h4 className="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-2">
            {t('activeMap.workOrderStatus')}
          </h4>
          <div className="flex gap-2 mb-3">
            <button
              onClick={() => navigateToWorkOrders(location.name, 'hospital', 'Normal')}
              className="px-3 py-1.5 bg-blue-100 dark:bg-blue-900/30 hover:bg-blue-200 dark:hover:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              {t('activeMap.normal')}: {location.normal_work_orders}
            </button>
            <button
              onClick={() => navigateToWorkOrders(location.name, 'hospital', 'Urgent')}
              className="px-3 py-1.5 bg-red-100 dark:bg-red-900/30 hover:bg-red-200 dark:hover:bg-red-900/50 text-red-700 dark:text-red-300 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              {t('activeMap.urgent')}: {location.urgent_work_orders}
            </button>
          </div>
          
          {/* Status Table */}
          <div className="overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700">
            <table className="w-full text-xs">
              <thead className="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th className="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-300">{t('activeMap.status')}</th>
                  <th className="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-300">{t('activeMap.count')}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                <tr className="bg-red-50 dark:bg-red-900/20 hover:bg-red-100 dark:hover:bg-red-900/30 transition-colors">
                  <td className="px-3 py-2 text-red-800 dark:text-red-300 font-medium">{t('activeMap.open')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'hospital', undefined, 'Open')}
                      className="text-red-700 dark:text-red-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_open}
                    </button>
                  </td>
                </tr>
                <tr className="bg-yellow-50 dark:bg-yellow-900/20 hover:bg-yellow-100 dark:hover:bg-yellow-900/30 transition-colors">
                  <td className="px-3 py-2 text-yellow-800 dark:text-yellow-300 font-medium">{t('activeMap.workInProgress')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'hospital', undefined, 'Work In Progress')}
                      className="text-yellow-700 dark:text-yellow-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_progress}
                    </button>
                  </td>
                </tr>
                <tr className="bg-blue-50 dark:bg-blue-900/20 hover:bg-blue-100 dark:hover:bg-blue-900/30 transition-colors">
                  <td className="px-3 py-2 text-blue-800 dark:text-blue-300 font-medium">{t('activeMap.pendingReview')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'hospital', undefined, 'Pending Review')}
                      className="text-blue-700 dark:text-blue-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_review}
                    </button>
                  </td>
                </tr>
                <tr className="bg-green-50 dark:bg-green-900/20 hover:bg-green-100 dark:hover:bg-green-900/30 transition-colors">
                  <td className="px-3 py-2 text-green-800 dark:text-green-300 font-medium">{t('activeMap.completed')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'hospital', undefined, 'Completed')}
                      className="text-green-700 dark:text-green-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_completed}
                    </button>
                  </td>
                </tr>
                <tr className="bg-gray-50 dark:bg-gray-900/20 hover:bg-gray-100 dark:hover:bg-gray-900/30 transition-colors">
                  <td className="px-3 py-2 text-gray-800 dark:text-gray-300 font-medium">{t('activeMap.closed')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'hospital', undefined, 'Closed')}
                      className="text-gray-700 dark:text-gray-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_closed}
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        {/* Preventive Maintenance Section */}
        <div className="mb-4">
          <h4 className="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-2">
            {t('activeMap.preventiveMaintenance')}
          </h4>
          <div className="flex flex-wrap gap-2">
            <button
              onClick={() => navigateToMaintenanceCalendar(location.name, 'Planned')}
              className="px-3 py-1.5 bg-orange-100 dark:bg-orange-900/30 hover:bg-orange-200 dark:hover:bg-orange-900/50 text-orange-700 dark:text-orange-300 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              {t('activeMap.planned')}: {location.planned_maintenance}
            </button>
            <button
              onClick={() => navigateToMaintenanceCalendar(location.name, 'Completed')}
              className="px-3 py-1.5 bg-green-100 dark:bg-green-900/30 hover:bg-green-200 dark:hover:bg-green-900/50 text-green-700 dark:text-green-300 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              {t('activeMap.completed')}: {location.completed_maintenance}
            </button>
            <button
              onClick={() => navigateToMaintenanceCalendar(location.name, 'Overdue')}
              className="px-3 py-1.5 bg-red-100 dark:bg-red-900/30 hover:bg-red-200 dark:hover:bg-red-900/50 text-red-700 dark:text-red-300 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              {t('activeMap.overdue')}: {location.overdue_maintenance}
            </button>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex gap-2 pt-3 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={() => navigateToAssets(location.name)}
            className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600 text-white rounded-lg text-sm font-medium transition-colors cursor-pointer"
          >
            {t('activeMap.viewAssets')}
          </button>
          <button
            onClick={() => navigateToWorkOrders(location.name, 'hospital')}
            className="flex-1 px-4 py-2 bg-purple-600 hover:bg-purple-700 dark:bg-purple-700 dark:hover:bg-purple-600 text-white rounded-lg text-sm font-medium transition-colors cursor-pointer"
          >
            {t('activeMap.viewWorkOrders')}
          </button>
        </div>
      </div>
    );
  };

  // Create popup content for DEPARTMENT locations (Work Orders only)
  const createDepartmentPopupContent = (location: LocationData) => {
    return (
      <div className="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg min-w-[280px] max-w-[320px]">
        {/* Department Name Header */}
        <div className="mb-4 pb-3 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2">
            <span className="px-2 py-0.5 bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded text-xs font-medium">
              {t('activeMap.deptWoType')}
            </span>
          </div>
          <h3 className="text-lg font-bold text-gray-900 dark:text-white mt-1">
            {location.name}
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1 italic">
            {t('activeMap.showingWorkOrdersByType')}
          </p>
        </div>

        {/* Work Order Status Section */}
        <div className="mb-4">
          <h4 className="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-2">
            {t('activeMap.workOrderStatus')}
          </h4>
          <div className="flex gap-2 mb-3">
            <button
              onClick={() => navigateToWorkOrders(location.name, 'department', 'Normal')}
              className="px-3 py-1.5 bg-blue-100 dark:bg-blue-900/30 hover:bg-blue-200 dark:hover:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              {t('activeMap.normal')}: {location.normal_work_orders}
            </button>
            <button
              onClick={() => navigateToWorkOrders(location.name, 'department', 'Urgent')}
              className="px-3 py-1.5 bg-red-100 dark:bg-red-900/30 hover:bg-red-200 dark:hover:bg-red-900/50 text-red-700 dark:text-red-300 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
            >
              {t('activeMap.urgent')}: {location.urgent_work_orders}
            </button>
          </div>
          
          {/* Status Table */}
          <div className="overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700">
            <table className="w-full text-xs">
              <thead className="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th className="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-300">{t('activeMap.status')}</th>
                  <th className="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-300">{t('activeMap.count')}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                <tr className="bg-red-50 dark:bg-red-900/20 hover:bg-red-100 dark:hover:bg-red-900/30 transition-colors">
                  <td className="px-3 py-2 text-red-800 dark:text-red-300 font-medium">{t('activeMap.open')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'department', undefined, 'Open')}
                      className="text-red-700 dark:text-red-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_open}
                    </button>
                  </td>
                </tr>
                <tr className="bg-yellow-50 dark:bg-yellow-900/20 hover:bg-yellow-100 dark:hover:bg-yellow-900/30 transition-colors">
                  <td className="px-3 py-2 text-yellow-800 dark:text-yellow-300 font-medium">{t('activeMap.workInProgress')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'department', undefined, 'Work In Progress')}
                      className="text-yellow-700 dark:text-yellow-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_progress}
                    </button>
                  </td>
                </tr>
                <tr className="bg-blue-50 dark:bg-blue-900/20 hover:bg-blue-100 dark:hover:bg-blue-900/30 transition-colors">
                  <td className="px-3 py-2 text-blue-800 dark:text-blue-300 font-medium">{t('activeMap.pendingReview')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'department', undefined, 'Pending Review')}
                      className="text-blue-700 dark:text-blue-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_review}
                    </button>
                  </td>
                </tr>
                <tr className="bg-green-50 dark:bg-green-900/20 hover:bg-green-100 dark:hover:bg-green-900/30 transition-colors">
                  <td className="px-3 py-2 text-green-800 dark:text-green-300 font-medium">{t('activeMap.completed')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'department', undefined, 'Completed')}
                      className="text-green-700 dark:text-green-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_completed}
                    </button>
                  </td>
                </tr>
                <tr className="bg-gray-50 dark:bg-gray-900/20 hover:bg-gray-100 dark:hover:bg-gray-900/30 transition-colors">
                  <td className="px-3 py-2 text-gray-800 dark:text-gray-300 font-medium">{t('activeMap.closed')}</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 'department', undefined, 'Closed')}
                      className="text-gray-700 dark:text-gray-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_closed}
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        {/* Action Button */}
        <div className="pt-3 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={() => navigateToWorkOrders(location.name, 'department')}
            className="w-full px-4 py-2 bg-purple-600 hover:bg-purple-700 dark:bg-purple-700 dark:hover:bg-purple-600 text-white rounded-lg text-sm font-medium transition-colors cursor-pointer"
          >
            {t('activeMap.viewAllWorkOrders')}
          </button>
        </div>
      </div>
    );
  };

  // Create tooltip content based on location type
  const createTooltipContent = (location: LocationData) => {
    const urgentIndicator = location.urgent_work_orders > 0 ? `🚨 ${t('activeMap.tooltipUrgent')}` : '';
    const typeLabel = location.locationType === 'department' ? `📋 ${t('activeMap.tooltipDept')}` : `🏥 ${t('activeMap.tooltipHospital')}`;
    
    return (
      <div className="p-2 bg-white dark:bg-gray-800 rounded-lg shadow-lg min-w-[200px]">
        <div className="mb-2 pb-2 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-1 mb-1">
            <span className={`text-[10px] px-1.5 py-0.5 rounded ${
              location.locationType === 'department' 
                ? 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300'
                : 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300'
            }`}>
              {typeLabel}
            </span>
          </div>
          <h4 className="text-sm font-bold text-gray-900 dark:text-white">
            {urgentIndicator}{location.name}
          </h4>
          {location.locationType === 'hospital' && (
            <p className="text-xs text-gray-600 dark:text-gray-400 mt-0.5">
              {t('activeMap.assets')}: <span className="font-semibold text-gray-900 dark:text-white">{location.assets}</span>
            </p>
          )}
        </div>
        <div className="space-y-1 text-xs">
          <div className="flex items-center justify-between">
            <span className="text-gray-600 dark:text-gray-400">{t('activeMap.normalWos')}</span>
            <span className="font-semibold text-blue-700 dark:text-blue-300">{location.normal_work_orders}</span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-gray-600 dark:text-gray-400">{t('activeMap.urgentWos')}</span>
            <span className="font-semibold text-red-700 dark:text-red-300">{location.urgent_work_orders}</span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-gray-600 dark:text-gray-400">{t('activeMap.closedWos')}</span>
            <span className="font-semibold text-gray-700 dark:text-gray-300">{location.wo_closed}</span>
          </div>
          {location.locationType === 'hospital' && (
            <>
              <div className="flex items-center justify-between">
                <span className="text-gray-600 dark:text-gray-400">{t('activeMap.plannedPms')}</span>
                <span className="font-semibold text-orange-700 dark:text-orange-300">{location.planned_maintenance}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-gray-600 dark:text-gray-400">{t('activeMap.completedPms')}</span>
                <span className="font-semibold text-green-700 dark:text-green-300">{location.completed_maintenance}</span>
              </div>
            </>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="h-screen flex flex-col bg-gray-50 dark:bg-gray-900">
      <div className="flex-shrink-0 bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700 px-4 py-3">
        <h1 className="text-xl font-semibold text-gray-800 dark:text-white">{t('activeMap.title')}</h1>
      </div>

      {/* Filter Container */}
      <div className="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3 relative z-[1000]">
        <div className="flex flex-wrap gap-4">
          {/* Hospital Filter */}
          <div className="w-64 relative z-[1000]">
            <LinkField
              label={t('activeMap.hospital')}
              doctype="Location"
              value={selectedHospital}
              onChange={handleHospitalChange}
              filters={{ custom_is_hospital: 1 }}
              placeholder={t('activeMap.selectHospital')}
              disabled={!!selectedDepartment}
            />
            {selectedDepartment && (
              <p className="text-xs text-gray-500 mt-1">{t('activeMap.clearDepartmentHint')}</p>
            )}
          </div>

          {/* Department Filter (Work Order Type locations) */}
          {/* ✅ NEW: Only show departments the user has permission for in the dropdown too */}
          <div className="w-64 relative z-[1000]">
            <LinkField
              label={t('activeMap.departmentWoType')}
              doctype="Location"
              value={selectedDepartment}
              onChange={handleDepartmentChange}
              filters={
                permittedDepartments !== null && permittedDepartments.length > 0
                  ? { custom_is_wo_type: 1, name: ['in', permittedDepartments] }
                  : { custom_is_wo_type: 1 }
              }
              placeholder={t('activeMap.selectDepartment')}
              disabled={!!selectedHospital}
            />
            {selectedHospital && (
              <p className="text-xs text-gray-500 mt-1">{t('activeMap.clearHospitalHint')}</p>
            )}
          </div>

          {/* Clear All Button */}
          {(selectedHospital || selectedDepartment) && (
            <div className="flex items-end">
              <button
                onClick={() => {
                  setSelectedHospital('');
                  setSelectedDepartment('');
                }}
                className="px-4 py-2 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg text-sm font-medium transition-colors"
              >
                {t('activeMap.clearFilters')}
              </button>
            </div>
          )}
        </div>

        {/* Legend */}
        <div className="flex gap-4 mt-3 text-xs">
          <div className="flex items-center gap-1.5">
            <span className="w-3 h-3 bg-blue-500 rounded-full"></span>
            <span className="text-gray-600 dark:text-gray-400">{t('activeMap.legendHospital')}</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="w-3 h-3 bg-green-500 rounded-full"></span>
            <span className="text-gray-600 dark:text-gray-400">{t('activeMap.legendDepartment')}</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="w-3 h-3 bg-red-500 rounded-full animate-pulse"></span>
            <span className="text-gray-600 dark:text-gray-400">{t('activeMap.legendHasUrgent')}</span>
          </div>
        </div>
      </div>

      {/* Map Container */}
      <div className="flex-1 relative" style={{ zIndex: 1 }}>
        {loading && (
          <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-75 z-[1000]">
            <div className="text-gray-600 dark:text-gray-300">{t('activeMap.loading')}</div>
          </div>
        )}
        <MapContainer
          center={[24.8, 45.5]}
          zoom={6}
          style={{ height: '100%', width: '100%' }}
          zoomControl={true}
        >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <MapBounds locations={locations} />
          {locations.map((location) => {
            const markerKey = `${location.locationType}-${location.latitude}-${location.longitude}`;
            const isDepartment = location.locationType === 'department';
            
            return (
              <Marker
                key={markerKey}
                position={[location.latitude, location.longitude]}
                icon={isDepartment ? DepartmentIcon : DefaultIcon}
                ref={(ref) => {
                  if (ref) {
                    markersRef.current[markerKey] = ref;
                    setTimeout(() => {
                      const markerElement = ref.getElement();
                      if (markerElement) {
                        // Apply urgent marker styling
                        if (location.urgent_work_orders > 0) {
                          markerElement.classList.add('urgent-marker');
                        }
                        // Apply department marker styling
                        if (isDepartment) {
                          markerElement.classList.add('department-marker');
                        }
                      }
                    }, 100);
                  }
                }}
              >
                <Tooltip
                  permanent={false}
                  direction="right"
                  className="hospital-tooltip-modern"
                >
                  {createTooltipContent(location)}
                </Tooltip>
                <Popup
                  className="hospital-popup-container"
                  maxWidth={300}
                  maxHeight={450}
                  autoPan={true}
                  keepInView={true}
                  closeButton={true}
                  autoClose={false}
                >
                  {isDepartment 
                    ? createDepartmentPopupContent(location)
                    : createHospitalPopupContent(location)
                  }
                </Popup>
              </Marker>
            );
          })}
        </MapContainer>
      </div>

      {/* Custom Styles */}
      <style>{`
        /* Ensure filter container and dropdowns stay above map */
        .leaflet-container {
          z-index: 1 !important;
        }
        
        /* LinkField dropdown z-index - ensure it's above everything */
        [data-linkfield-dropdown],
        .linkfield-dropdown,
        .react-select__menu,
        .react-select__menu-portal,
        .select2-container,
        .select2-dropdown {
          z-index: 1050 !important;
        }
        
        /* Any dropdown menu from LinkField */
        div[role="listbox"],
        ul[role="listbox"],
        .dropdown-menu,
        .autocomplete-dropdown {
          z-index: 1050 !important;
        }
        
        .hospital-tooltip-modern {
          background: transparent !important;
          border: none !important;
          box-shadow: none !important;
        }
        
        .hospital-tooltip-modern .leaflet-tooltip-content-wrapper {
          background: transparent !important;
          border: none !important;
          box-shadow: none !important;
          padding: 0 !important;
        }
        
        .hospital-tooltip-modern .leaflet-tooltip-content {
          margin: 0 !important;
        }
        
        .hospital-popup-container .leaflet-popup-content-wrapper {
          padding: 0;
          border-radius: 8px;
          box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        
        .hospital-popup-container .leaflet-popup-content {
          margin: 0;
          width: auto !important;
        }
        
        .urgent-marker {
          animation: urgent-flash 2s infinite;
        }
        
        @keyframes urgent-flash {
          0%, 50% {
            filter: hue-rotate(0deg) brightness(1) saturate(1);
          }
          25%, 75% {
            filter: hue-rotate(0deg) brightness(1.5) saturate(2) drop-shadow(0 0 10px red);
          }
        }
        
        /* Department marker - purple tint */
        .department-marker {
          filter: hue-rotate(270deg) saturate(1.5) brightness(1);
        }
        
        /* When department marker has urgent */
        .department-marker.urgent-marker {
          animation: department-urgent-flash 2s infinite;
        }
        
        @keyframes department-urgent-flash {
          0%, 50% {
            filter: hue-rotate(270deg) saturate(1.5) brightness(1);
          }
          25%, 75% {
            filter: hue-rotate(270deg) brightness(1.5) saturate(2) drop-shadow(0 0 10px red);
          }
        }
        
        .leaflet-popup {
          z-index: 2000 !important;
        }
        
        .leaflet-tooltip {
          z-index: 2000 !important;
        }
      `}</style>
    </div>
  );
};

export default ActiveMap;