import { useState, useEffect } from 'react';
import { emergencyApi, Incident, EmergencyAlert, Officer, SecurityStats } from '@/services/emergencyApi';
import { useAuth } from '@/contexts/AuthContext';

export const useEmergencyData = () => {
  const { user, isAuthenticated } = useAuth();
  const [stats, setStats] = useState<SecurityStats | null>(null);
  const [incidents, setIncidents] = useState<Incident[]>([]);
  const [emergencyAlerts, setEmergencyAlerts] = useState<EmergencyAlert[]>([]);
  const [officers, setOfficers] = useState<Officer[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Check if user has emergency permissions
  const isOfficer = user?.role === 'politur' || user?.role === 'admin' || user?.role === 'super_admin';
  const isAdmin = user?.role === 'admin' || user?.role === 'super_admin';

  const loadEmergencyData = async () => {
    if (!isAuthenticated) {
      console.log('Emergency system: User not authenticated');
      setError('Usuario no autenticado');
      setLoading(false);
      return;
    }

    try {
      console.log('Emergency system: Loading data for user role:', user?.role);
      setLoading(true);
      setError(null);
      
      if (isOfficer) {
        // Load data for officers and admins
        console.log('Emergency system: Loading officer/admin data');
        const [incidentsData, alertsData, officersData, statsData] = await Promise.all([
          isAdmin ? emergencyApi.getAllIncidents({ page: 1, limit: 50 }) : emergencyApi.getMyIncidents(),
          emergencyApi.getActiveEmergencyAlerts(),
          emergencyApi.getAvailableOfficers(),
          emergencyApi.getSecurityStats(),
        ]);
        
        console.log('Emergency system: Data loaded successfully', {
          incidents: incidentsData,
          alerts: alertsData,
          officers: officersData,
          stats: statsData
        });
        
        setIncidents(isAdmin ? (incidentsData as any)?.incidents || incidentsData || [] : incidentsData as Incident[]);
        setEmergencyAlerts(alertsData || []);
        setOfficers(officersData || []);
        setStats(statsData);
      } else {
        // Regular users can only see their own reported incidents
        console.log('Emergency system: Loading user incidents');
        const myIncidents = await emergencyApi.getMyIncidents();
        console.log('Emergency system: User incidents loaded', myIncidents);
        setIncidents(myIncidents || []);
      }
      
    } catch (error: any) {
      console.error('Emergency system: Error loading data:', error);
      setError(`Error de conexión: ${error.message}`);
      
      // Use comprehensive mock data for development/testing
      console.log('Emergency system: Using mock data due to API error');
      setStats({
        totalIncidents: 15,
        activeIncidents: 3,
        resolvedToday: 8,
        averageResponseTime: 12,
        activeAlerts: 1,
        availableOfficers: 5,
        incidentsByType: {
          theft: 4,
          assault: 2,
          accident: 3,
          medical: 2,
          other: 4
        },
        incidentsByPriority: {
          critical: 1,
          high: 3,
          medium: 6,
          low: 5
        }
      });

      // Mock incidents data
      const mockIncidents: Incident[] = [
        {
          id: '1',
          type: 'theft',
          priority: 'high',
          status: 'pending',
          title: 'Robo en Plaza Central',
          description: 'Reporte de robo a turista en la plaza principal',
          location: {
            latitude: 18.4861,
            longitude: -69.9312,
            address: 'Plaza Central, Punta Cana'
          },
          reportedBy: {
            id: '1',
            name: 'María González',
            phone: '+1809-555-0123'
          },
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        },
        {
          id: '2',
          type: 'medical',
          priority: 'critical',
          status: 'assigned',
          title: 'Emergencia Médica en Hotel',
          description: 'Turista con problemas cardíacos',
          location: {
            latitude: 18.4856,
            longitude: -69.9289,
            address: 'Hotel Paradise, Punta Cana'
          },
          reportedBy: {
            id: '2',
            name: 'Hotel Paradise Staff',
            phone: '+1809-555-0456'
          },
          assignedOfficer: {
            id: 'off1',
            name: 'Sgt. Carlos Medina',
            badge: 'POL-001'
          },
          createdAt: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
          updatedAt: new Date(Date.now() - 15 * 60 * 1000).toISOString()
        }
      ];

      // Mock emergency alerts
      const mockAlerts: EmergencyAlert[] = [
        {
          id: 'alert1',
          type: 'panic',
          priority: 'critical',
          status: 'active',
          location: {
            latitude: 18.4870,
            longitude: -69.9320,
            address: 'Bavaro Beach'
          },
          user: {
            id: '3',
            name: 'Ana Pérez',
            phone: '+1809-555-0789'
          },
          createdAt: new Date(Date.now() - 5 * 60 * 1000).toISOString()
        }
      ];

      // Mock officers
      const mockOfficers: Officer[] = [
        {
          id: 'off1',
          name: 'Sgt. Carlos Medina',
          badge: 'POL-001',
          rank: 'Sargento',
          status: 'busy',
          location: {
            latitude: 18.4856,
            longitude: -69.9289
          },
          phone: '+1809-555-1001',
          assignedIncidents: 1
        },
        {
          id: 'off2',
          name: 'Of. María Rodríguez',
          badge: 'POL-002',
          rank: 'Oficial',
          status: 'available',
          location: {
            latitude: 18.4861,
            longitude: -69.9312
          },
          phone: '+1809-555-1002',
          assignedIncidents: 0
        }
      ];

      setIncidents(mockIncidents);
      setEmergencyAlerts(mockAlerts);
      setOfficers(mockOfficers);
      
    } finally {
      setLoading(false);
    }
  };

  // Create incident
  const createIncident = async (incidentData: {
    type: string;
    priority: string;
    title: string;
    description: string;
    location: {
      latitude: number;
      longitude: number;
      address?: string;
    };
  }) => {
    try {
      const newIncident = await emergencyApi.createIncident(incidentData);
      await loadEmergencyData(); // Refresh data
      return { success: true, incident: newIncident };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Update incident
  const updateIncident = async (id: string, updateData: Partial<Incident>) => {
    try {
      const updatedIncident = await emergencyApi.updateIncident(id, updateData);
      await loadEmergencyData(); // Refresh data
      return { success: true, incident: updatedIncident };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Assign incident to officer
  const assignIncident = async (incidentId: string, officerId: string) => {
    try {
      const assignedIncident = await emergencyApi.assignIncident(incidentId, officerId);
      await loadEmergencyData(); // Refresh data
      return { success: true, incident: assignedIncident };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Create emergency alert (panic button)
  const createEmergencyAlert = async (alertData: {
    type: string;
    location: {
      latitude: number;
      longitude: number;
      address?: string;
    };
    message?: string;
  }) => {
    try {
      const newAlert = await emergencyApi.createEmergencyAlert(alertData);
      await loadEmergencyData(); // Refresh data
      return { success: true, alert: newAlert };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Activate panic button
  const activatePanicButton = async (type: 'panic' | 'medical' | 'security' = 'panic') => {
    try {
      const alert = await emergencyApi.activatePanicButton(type);
      await loadEmergencyData(); // Refresh data
      return { success: true, alert };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Deactivate emergency alert
  const deactivateEmergencyAlert = async (id: string) => {
    try {
      const deactivatedAlert = await emergencyApi.deactivateEmergencyAlert(id);
      await loadEmergencyData(); // Refresh data
      return { success: true, alert: deactivatedAlert };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Update officer status
  const updateOfficerStatus = async (id: string, status: 'available' | 'busy' | 'off_duty') => {
    try {
      const updatedOfficer = await emergencyApi.updateOfficerStatus(id, status);
      await loadEmergencyData(); // Refresh data
      return { success: true, officer: updatedOfficer };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Get current location
  const getCurrentLocation = async () => {
    try {
      return await emergencyApi.getCurrentLocation();
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  };

  // Initialize data on mount
  useEffect(() => {
    if (isAuthenticated) {
      loadEmergencyData();
    }
  }, [isAuthenticated, isOfficer, isAdmin]);

  const refreshData = () => {
    loadEmergencyData();
  };

  return {
    // Data
    stats,
    incidents,
    emergencyAlerts,
    officers,
    loading,
    error,
    
    // Permissions
    isOfficer,
    isAdmin,
    
    // Actions
    createIncident,
    updateIncident,
    assignIncident,
    createEmergencyAlert,
    activatePanicButton,
    deactivateEmergencyAlert,
    updateOfficerStatus,
    getCurrentLocation,
    
    // Utility
    refreshData,
    loadEmergencyData
  };
};