import React, { useState, useEffect } from 'react';
import { AlertTriangle, MapPin, Phone, Video, Clock, CheckCircle, XCircle, Navigation } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import EmergencyMap from '@/components/politur/EmergencyMap';
import IncidentDetails from '@/components/politur/IncidentDetails';
import { Emergency } from '@/types/politur';


const EmergencyDashboard = () => {
  const { toast } = useToast();
  const [emergencies, setEmergencies] = useState<Emergency[]>([
    {
      id: '1',
      touristName: 'John Smith',
      location: { lat: 18.4861, lng: -69.9312 },
      address: 'Zona Colonial, Santo Domingo',
      type: 'security',
      priority: 'high',
      status: 'pending',
      description: 'Robo reportado en la zona',
      timestamp: new Date().toISOString(),
      phone: '+1-555-0123'
    },
    {
      id: '2',
      touristName: 'Maria Garcia',
      location: { lat: 18.4721, lng: -69.8933 },
      address: 'Malecón, Santo Domingo',
      type: 'medical',
      priority: 'critical',
      status: 'assigned',
      description: 'Emergencia médica - dolor de pecho',
      timestamp: new Date(Date.now() - 300000).toISOString(),
      assignedOfficer: 'Oficial Rodriguez',
      phone: '+1-555-0456'
    }
  ]);
  const [selectedEmergency, setSelectedEmergency] = useState<Emergency | null>(null);

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'critical': return 'destructive';
      case 'high': return 'default';
      case 'medium': return 'secondary';
      default: return 'outline';
    }
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'medical': return '🏥';
      case 'security': return '🚨';
      case 'accident': return '🚗';
      default: return '⚠️';
    }
  };

  const handleAssignOfficer = (emergencyId: string) => {
    setEmergencies(prev => prev.map(e => 
      e.id === emergencyId 
        ? { ...e, status: 'assigned', assignedOfficer: 'Tu' }
        : e
    ));
    toast({
      title: "Asignado",
      description: "Te has asignado a esta emergencia",
    });
  };

  const handleResolve = (emergencyId: string) => {
    setEmergencies(prev => prev.map(e => 
      e.id === emergencyId 
        ? { ...e, status: 'resolved' }
        : e
    ));
    toast({
      title: "Resuelto",
      description: "La emergencia ha sido marcada como resuelta",
    });
  };

  const getTimeSince = (timestamp: string) => {
    const minutes = Math.floor((Date.now() - new Date(timestamp).getTime()) / 60000);
    if (minutes < 1) return 'Hace un momento';
    if (minutes < 60) return `Hace ${minutes} min`;
    return `Hace ${Math.floor(minutes / 60)} hrs`;
  };

  return (
    <div className="space-y-6">
      {/* Header Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">
              Emergencias Activas
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-red-600">
              {emergencies.filter(e => e.status !== 'resolved').length}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">
              Críticas
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-orange-600">
              {emergencies.filter(e => e.priority === 'critical').length}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">
              En Progreso
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-blue-600">
              {emergencies.filter(e => e.status === 'in_progress').length}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">
              Resueltas Hoy
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-green-600">
              {emergencies.filter(e => e.status === 'resolved').length}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Map */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="w-5 h-5" />
              Mapa de Emergencias
            </CardTitle>
          </CardHeader>
          <CardContent>
            <EmergencyMap 
              emergencies={emergencies}
              onSelectEmergency={setSelectedEmergency}
            />
          </CardContent>
        </Card>

        {/* Emergency List */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <AlertTriangle className="w-5 h-5" />
              Alertas Activas
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3 max-h-[500px] overflow-y-auto">
              {emergencies
                .filter(e => e.status !== 'resolved')
                .sort((a, b) => {
                  const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
                  return priorityOrder[a.priority] - priorityOrder[b.priority];
                })
                .map((emergency) => (
                  <div 
                    key={emergency.id}
                    className={`border rounded-lg p-4 cursor-pointer transition-all ${
                      selectedEmergency?.id === emergency.id 
                        ? 'ring-2 ring-primary bg-primary/5' 
                        : 'hover:bg-gray-50'
                    }`}
                    onClick={() => setSelectedEmergency(emergency)}
                  >
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <span className="text-2xl">{getTypeIcon(emergency.type)}</span>
                        <div>
                          <h4 className="font-semibold">{emergency.touristName}</h4>
                          <p className="text-sm text-gray-600">{emergency.address}</p>
                        </div>
                      </div>
                      <Badge variant={getPriorityColor(emergency.priority)}>
                        {emergency.priority.toUpperCase()}
                      </Badge>
                    </div>

                    <p className="text-sm text-gray-700 mb-3">{emergency.description}</p>

                    <div className="flex items-center justify-between text-sm">
                      <div className="flex items-center gap-1 text-gray-500">
                        <Clock className="w-4 h-4" />
                        {getTimeSince(emergency.timestamp)}
                      </div>

                      <div className="flex gap-2">
                        {emergency.status === 'pending' && (
                          <Button 
                            size="sm" 
                            onClick={(e) => {
                              e.stopPropagation();
                              handleAssignOfficer(emergency.id);
                            }}
                          >
                            Asignarme
                          </Button>
                        )}
                        {emergency.status === 'assigned' && (
                          <>
                            <Button 
                              size="sm" 
                              variant="outline"
                              onClick={(e) => {
                                e.stopPropagation();
                                window.location.href = `tel:${emergency.phone}`;
                              }}
                            >
                              <Phone className="w-4 h-4" />
                            </Button>
                            <Button 
                              size="sm" 
                              variant="outline"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleResolve(emergency.id);
                              }}
                            >
                              <CheckCircle className="w-4 h-4" />
                            </Button>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Incident Details Modal */}
      {selectedEmergency && (
        <IncidentDetails
          emergency={selectedEmergency}
          onClose={() => setSelectedEmergency(null)}
          onAssign={() => handleAssignOfficer(selectedEmergency.id)}
          onResolve={() => handleResolve(selectedEmergency.id)}
        />
      )}
    </div>
  );
};

export default EmergencyDashboard;
