/**
 * 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)
 * 
 * Replicates the Frappe "active-map" page functionality
 */

import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
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;

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;
}

// 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 navigate = useNavigate();
  const [selectedHospital, setSelectedHospital] = useState<string>('');
  const [locations, setLocations] = useState<LocationData[]>([]);
  const [loading, setLoading] = useState(true);
  const markersRef = useRef<Record<string, L.Marker>>({});

  // Fetch locations and their counts
  const fetchAndRenderData = async () => {
    setLoading(true);
    try {
      // Build filters
      const filters: Record<string, any> = {
        latitude: ['!=', ''],
        longitude: ['!=', '']
      };

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

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

      const locationList = locationsResponse?.data || [];

      // For each location, fetch counts
      const locationPromises = locationList.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
        };

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

          // Fetch Normal Work Orders
          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']]
            }))}&fields=["name"]`
          );
          counts.normal_work_orders = normalWOResponse?.data?.length || 0;

          // Fetch Urgent Work Orders
          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']]
            }))}&fields=["name"]`
          );
          counts.urgent_work_orders = urgentWOResponse?.data?.length || 0;

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

          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.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 ${location.name}:`, err);
        }

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

      const results = await Promise.all(locationPromises);
      setLocations(results.filter(l => !isNaN(l.latitude) && !isNaN(l.longitude)));
    } catch (error) {
      console.error('Error fetching map data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAndRenderData();
  }, [selectedHospital]);

  // Navigate to list view with filters
  const navigateToWorkOrders = (hospital: string, priority?: string, status?: string) => {
    const params = new URLSearchParams();
    if (hospital) params.set('company', hospital);
    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 with modern UI matching the application
  const createPopupContent = (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">
          <h3 className="text-lg font-bold text-gray-900 dark:text-white">
            {location.name}
          </h3>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Total Assets: <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">
            Work Order Status
          </h4>
          <div className="flex gap-2 mb-3">
            <button
              onClick={() => navigateToWorkOrders(location.name, '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"
            >
              Normal: {location.normal_work_orders}
            </button>
            <button
              onClick={() => navigateToWorkOrders(location.name, '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"
            >
              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">Status</th>
                  <th className="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-300">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">Open</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 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">Work In Progress</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 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">Pending Review</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, 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">Completed</td>
                  <td className="px-3 py-2">
                    <button
                      onClick={() => navigateToWorkOrders(location.name, undefined, 'Completed')}
                      className="text-green-700 dark:text-green-400 font-bold hover:underline cursor-pointer"
                    >
                      {location.wo_completed}
                    </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">
            Preventive Maintenance
          </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"
            >
              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"
            >
              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"
            >
              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"
          >
            View Assets
          </button>
          <button
            onClick={() => navigateToWorkOrders(location.name)}
            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"
          >
            View Work Orders
          </button>
        </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">Active Map</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="max-w-md relative z-[1000]">
          <LinkField
            label="Hospital"
            doctype="Location"
            value={selectedHospital}
            onChange={setSelectedHospital}
            filters={{ custom_is_hospital: 1 }}
            placeholder="Select hospital (leave empty for all)"
          />
        </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">Loading map data...</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 urgentIndicator = location.urgent_work_orders > 0 ? '🚨 URGENT! ' : '';
            const markerKey = `${location.latitude}-${location.longitude}`;
            
            return (
              <Marker
                key={markerKey}
                position={[location.latitude, location.longitude]}
                ref={(ref) => {
                  if (ref) {
                    markersRef.current[markerKey] = ref;
                    // Apply urgent marker styling
                    if (location.urgent_work_orders > 0) {
                      setTimeout(() => {
                        const markerElement = ref.getElement();
                        if (markerElement) {
                          markerElement.classList.add('urgent-marker', 'red-marker');
                        }
                      }, 100);
                    }
                  }
                }}
              >
                <Tooltip
                  permanent={false}
                  direction="right"
                  className="hospital-tooltip-modern"
                >
                  <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">
                      <h4 className="text-sm font-bold text-gray-900 dark:text-white">
                        {urgentIndicator}{location.name}
                      </h4>
                      <p className="text-xs text-gray-600 dark:text-gray-400 mt-0.5">
                        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">Normal WOs:</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">Urgent WOs:</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">Planned PMs:</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">Completed PMs:</span>
                        <span className="font-semibold text-green-700 dark:text-green-300">{location.completed_maintenance}</span>
                      </div>
                    </div>
                  </div>
                </Tooltip>
                <Popup
                  className="hospital-popup-container"
                  maxWidth={300}
                  maxHeight={410}
                  autoPan={true}
                  keepInView={true}
                  closeButton={true}
                  autoClose={false}
                >
                  {createPopupContent(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);
          }
        }
        
        .red-marker {
          filter: hue-rotate(120deg) saturate(2) brightness(0.8);
        }
        
        .leaflet-popup {
          z-index: 2000 !important;
        }
        
        .leaflet-tooltip {
          z-index: 2000 !important;
        }
      `}</style>
    </div>
  );
};

export default ActiveMap;

