"use client";

import { useEffect, useState, useRef } from "react";
import { api } from "@/lib/api";
import {
  MapPin,
  RefreshCw,
  Thermometer,
  Droplets,
  Wifi,
  WifiOff,
  Layers,
  ZoomIn,
  ZoomOut,
  Maximize2,
} from "lucide-react";

interface DeviceLocation {
  id: string;
  name: string;
  lat: number;
  lng: number;
  is_online: boolean;
  device_type: string;
  readings?: {
    temperature?: number;
    humidity?: number;
    battery?: number;
  };
}

export default function MapPage() {
  const [devices, setDevices] = useState<DeviceLocation[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedDevice, setSelectedDevice] = useState<DeviceLocation | null>(null);
  const [mapView, setMapView] = useState({ zoom: 12, center: { lat: 24.7136, lng: 46.6753 } }); // الرياض
  const mapRef = useRef<HTMLDivElement>(null);

  const fetchDevices = async () => {
    try {
      api.loadToken();
      const response = await api.getDevices({ page_size: 100 });
      
      // دالة لتوليد موقع ثابت من device id
      const hashCode = (str: string): number => {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
          const char = str.charCodeAt(i);
          hash = ((hash << 5) - hash) + char;
          hash = hash & hash;
        }
        return Math.abs(hash);
      };
      
      // تحويل الأجهزة لتشمل الموقع
      const devicesWithLocation: DeviceLocation[] = (response.items || []).map((device: any, index: number) => {
        // استخراج الموقع من metadata أو توليد موقع ثابت من device id
        const metadata = device.device_metadata || {};
        const location = metadata.location || {};
        
        // توليد موقع ثابت إذا لم يكن موجود
        const hash = hashCode(device.id);
        const latOffset = ((hash % 1000) / 10000) - 0.05;
        const lngOffset = (((hash >> 10) % 1000) / 10000) - 0.05;
        
        return {
          id: device.id,
          name: device.name,
          lat: location.lat || 24.7136 + latOffset,
          lng: location.lng || 46.6753 + lngOffset,
          is_online: device.is_online,
          device_type: device.device_type,
          readings: metadata.readings,
        };
      });
      
      setDevices(devicesWithLocation);
    } catch (error) {
      console.error("Failed to fetch devices:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDevices();
    const interval = setInterval(fetchDevices, 30000);
    return () => clearInterval(interval);
  }, []);

  const handleZoomIn = () => {
    setMapView(prev => ({ ...prev, zoom: Math.min(prev.zoom + 1, 18) }));
  };

  const handleZoomOut = () => {
    setMapView(prev => ({ ...prev, zoom: Math.max(prev.zoom - 1, 3) }));
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  const onlineDevices = devices.filter(d => d.is_online);
  const offlineDevices = devices.filter(d => !d.is_online);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">خريطة الأجهزة</h1>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            عرض مواقع الأجهزة على الخريطة التفاعلية
          </p>
        </div>
        <button
          onClick={fetchDevices}
          className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50"
        >
          <RefreshCw className="w-4 h-4" />
          تحديث
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
              <MapPin className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">إجمالي الأجهزة</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">{devices.length}</p>
            </div>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-green-100 dark:bg-green-900/30 rounded-lg">
              <Wifi className="w-6 h-6 text-green-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">أجهزة متصلة</p>
              <p className="text-2xl font-bold text-green-600">{onlineDevices.length}</p>
            </div>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-red-100 dark:bg-red-900/30 rounded-lg">
              <WifiOff className="w-6 h-6 text-red-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">أجهزة غير متصلة</p>
              <p className="text-2xl font-bold text-red-600">{offlineDevices.length}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Map Container */}
      <div className="relative bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        {/* Map Controls */}
        <div className="absolute top-4 right-4 z-10 flex flex-col gap-2">
          <button
            onClick={handleZoomIn}
            className="p-2 bg-white dark:bg-gray-700 rounded-lg shadow-lg hover:bg-gray-50 dark:hover:bg-gray-600"
          >
            <ZoomIn className="w-5 h-5" />
          </button>
          <button
            onClick={handleZoomOut}
            className="p-2 bg-white dark:bg-gray-700 rounded-lg shadow-lg hover:bg-gray-50 dark:hover:bg-gray-600"
          >
            <ZoomOut className="w-5 h-5" />
          </button>
          <button className="p-2 bg-white dark:bg-gray-700 rounded-lg shadow-lg hover:bg-gray-50 dark:hover:bg-gray-600">
            <Layers className="w-5 h-5" />
          </button>
          <button className="p-2 bg-white dark:bg-gray-700 rounded-lg shadow-lg hover:bg-gray-50 dark:hover:bg-gray-600">
            <Maximize2 className="w-5 h-5" />
          </button>
        </div>

        {/* Interactive Map Area */}
        <div
          ref={mapRef}
          className="relative h-[500px] bg-gradient-to-br from-blue-50 to-green-50 dark:from-gray-900 dark:to-gray-800"
          style={{
            backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%239C92AC' fill-opacity='0.1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
          }}
        >
          {/* Device Markers */}
          {devices.map((device, index) => {
            // حساب موقع العلامة على الخريطة (محاكاة)
            const x = ((device.lng - 46.5) / 0.3) * 100;
            const y = ((24.85 - device.lat) / 0.3) * 100;
            
            return (
              <div
                key={device.id}
                className="absolute transform -translate-x-1/2 -translate-y-1/2 cursor-pointer transition-transform hover:scale-110"
                style={{
                  left: `${Math.min(Math.max(x, 5), 95)}%`,
                  top: `${Math.min(Math.max(y, 5), 95)}%`,
                }}
                onClick={() => setSelectedDevice(device)}
              >
                <div className={`relative p-2 rounded-full shadow-lg ${
                  device.is_online 
                    ? 'bg-green-500' 
                    : 'bg-red-500'
                }`}>
                  <MapPin className="w-5 h-5 text-white" />
                  {device.is_online && (
                    <span className="absolute -top-1 -right-1 w-3 h-3 bg-green-400 rounded-full animate-ping" />
                  )}
                </div>
                <div className="absolute top-full left-1/2 transform -translate-x-1/2 mt-1 whitespace-nowrap">
                  <span className="text-xs bg-white dark:bg-gray-800 px-2 py-1 rounded shadow text-gray-700 dark:text-gray-300">
                    {device.name}
                  </span>
                </div>
              </div>
            );
          })}

          {/* Selected Device Info */}
          {selectedDevice && (
            <div className="absolute bottom-4 left-4 right-4 md:left-auto md:w-80 bg-white dark:bg-gray-800 rounded-xl shadow-xl p-4 z-20">
              <div className="flex items-start justify-between mb-3">
                <div>
                  <h3 className="font-semibold text-gray-900 dark:text-white">{selectedDevice.name}</h3>
                  <p className="text-sm text-gray-500">{selectedDevice.device_type}</p>
                </div>
                <button
                  onClick={() => setSelectedDevice(null)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  ✕
                </button>
              </div>
              
              <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs mb-3 ${
                selectedDevice.is_online
                  ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
                  : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
              }`}>
                {selectedDevice.is_online ? <Wifi className="w-3 h-3" /> : <WifiOff className="w-3 h-3" />}
                {selectedDevice.is_online ? 'متصل' : 'غير متصل'}
              </div>
              
              {selectedDevice.readings && (
                <div className="grid grid-cols-2 gap-3 pt-3 border-t border-gray-200 dark:border-gray-700">
                  {selectedDevice.readings.temperature !== undefined && (
                    <div className="flex items-center gap-2">
                      <Thermometer className="w-4 h-4 text-orange-500" />
                      <span className="text-sm text-gray-600 dark:text-gray-400">
                        {selectedDevice.readings.temperature}°C
                      </span>
                    </div>
                  )}
                  {selectedDevice.readings.humidity !== undefined && (
                    <div className="flex items-center gap-2">
                      <Droplets className="w-4 h-4 text-blue-500" />
                      <span className="text-sm text-gray-600 dark:text-gray-400">
                        {selectedDevice.readings.humidity}%
                      </span>
                    </div>
                  )}
                </div>
              )}
              
              <div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500">
                الموقع: {selectedDevice.lat.toFixed(4)}, {selectedDevice.lng.toFixed(4)}
              </div>
            </div>
          )}
        </div>

        {/* Legend */}
        <div className="absolute bottom-4 left-4 bg-white/90 dark:bg-gray-800/90 backdrop-blur-sm rounded-lg px-4 py-2 shadow-lg">
          <div className="flex items-center gap-4 text-sm">
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 bg-green-500 rounded-full"></div>
              <span className="text-gray-600 dark:text-gray-400">متصل</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 bg-red-500 rounded-full"></div>
              <span className="text-gray-600 dark:text-gray-400">غير متصل</span>
            </div>
          </div>
        </div>
      </div>

      {/* Devices List */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
        <div className="p-4 border-b border-gray-200 dark:border-gray-700">
          <h2 className="font-semibold text-gray-900 dark:text-white">قائمة الأجهزة</h2>
        </div>
        <div className="divide-y divide-gray-200 dark:divide-gray-700 max-h-64 overflow-y-auto">
          {devices.map(device => (
            <div
              key={device.id}
              className="p-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer transition-colors"
              onClick={() => setSelectedDevice(device)}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className={`w-2 h-2 rounded-full ${device.is_online ? 'bg-green-500' : 'bg-red-500'}`} />
                  <div>
                    <p className="font-medium text-gray-900 dark:text-white">{device.name}</p>
                    <p className="text-xs text-gray-500">{device.device_type}</p>
                  </div>
                </div>
                <div className="text-xs text-gray-500">
                  {device.lat.toFixed(2)}, {device.lng.toFixed(2)}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
