import React, { useState } from 'react';
import { Radio, Clock, AlertTriangle, CheckCircle, Filter, Search, RefreshCw, User, Truck, MapPin, DollarSign, Calendar, X, ChevronRight, FileText } from 'lucide-react';
import { useMonitoring } from '../hooks/useMonitoring';

const Modal = ({ isOpen, onClose, title, children }) => {
  if (!isOpen) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-in fade-in duration-300">
      <div className="bg-white dark:bg-[#1b1b1b] w-full max-w-2xl rounded-[32px] border border-slate-200 dark:border-white/5 shadow-2xl overflow-hidden animate-in zoom-in-95 duration-300">
        <div className="flex items-center justify-between p-6 border-b border-slate-100 dark:border-white/5">
          <h3 className="text-xl font-bold text-slate-800 dark:text-white">{title}</h3>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-full transition-colors text-slate-400">
            <X size={20} />
          </button>
        </div>
        <div className="p-8 max-h-[80vh] overflow-y-auto">
          {children}
        </div>
      </div>
    </div>
  );
};

const GrMonitoringView = () => {
  const [activeTab, setActiveTab] = useState('PENDING');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedRequest, setSelectedRequest] = useState(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  
  const { requests, stats, loading, error, refresh, attendRequest, approveRequest } = useMonitoring({ 
    status: activeTab === 'ALL' ? undefined : activeTab 
  });

  const filteredRequests = requests.filter(req => 
    req.driverName.toLowerCase().includes(searchTerm.toLowerCase()) ||
    req.plate.toLowerCase().includes(searchTerm.toLowerCase()) ||
    req.operation.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const getRiskColor = (level) => {
    switch (level) {
      case 'HIGH': return 'bg-red-500/10 text-red-600 border-red-500/20';
      case 'MEDIUM': return 'bg-yellow-500/10 text-yellow-600 border-yellow-500/20';
      case 'LOW': return 'bg-green-500/10 text-green-600 border-green-500/20';
      default: return 'bg-slate-500/10 text-slate-600 border-slate-500/20';
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'PENDING': return 'bg-orange-500/10 text-orange-600';
      case 'LIBERADO': return 'bg-green-500/10 text-green-600';
      case 'EM_ROTA': return 'bg-blue-500/10 text-blue-600';
      case 'FINALIZADO': return 'bg-slate-500/10 text-slate-600';
      default: return 'bg-slate-500/10 text-slate-600';
    }
  };

  const handleAttend = async (id) => {
    try {
      await attendRequest(id, 'Operador Atual');
      alert('Solicitação atendida com sucesso!');
    } catch (err) {
      alert(err.message);
    }
  };

  const openDetails = (request) => {
    setSelectedRequest(request);
    setIsDetailModalOpen(true);
  };

  const tabs = [
    { id: 'ALL', label: 'Todos', count: stats?.pending + stats?.approved + stats?.inRoute || 0 },
    { id: 'PENDING', label: 'Pendentes', count: stats?.pending || 0 },
    { id: 'LIBERADO', label: 'Aprovados', count: stats?.approved || 0 },
    { id: 'EM_ROTA', label: 'Em Rota', count: stats?.inRoute || 0 },
    { id: 'FINALIZADO', label: 'Finalizados', count: stats?.finished || 0 }
  ];

  return (
    <div className="flex flex-col gap-8 p-6 md:p-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      {/* Header */}
      <header className="flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div className="space-y-2">
          <h1 className="text-4xl md:text-6xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
            Monitoramento <span className="text-[var(--gr-primary)]">em Tempo Real</span>
          </h1>
          <p className="text-slate-400 dark:text-slate-500 text-base md:text-lg font-medium italic opacity-80">
            Painel de solicitações de liberação e acompanhamento de viagens
          </p>
        </div>
        
        <button
          onClick={refresh}
          disabled={loading}
          className="flex items-center gap-2 px-6 py-3 bg-[var(--gr-primary)] text-white rounded-full font-bold text-[10px] uppercase tracking-widest hover:bg-[var(--gr-primary)]/90 transition-all disabled:opacity-50"
        >
          <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
          Atualizar
        </button>
      </header>

      {/* Stats Cards */}
      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          {tabs.map(tab => (
            <div key={tab.id} className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
              <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">{tab.label}</div>
              <div className="text-3xl font-bold text-slate-800 dark:text-white">{tab.count}</div>
            </div>
          ))}
        </div>
      )}

      {/* Tabs e Filtros */}
      <div className="flex flex-wrap gap-4 items-center justify-between">
        <div className="flex p-2 bg-slate-100 dark:bg-[#141414] rounded-[24px] border border-slate-200 dark:border-white/5 shadow-inner">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`px-6 py-2 rounded-[18px] text-[10px] font-bold uppercase tracking-widest transition-all ${
                activeTab === tab.id
                  ? 'bg-white dark:bg-[#1b1b1b] text-slate-900 dark:text-white shadow-md'
                  : 'text-slate-500 hover:text-slate-700'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        <div className="flex items-center gap-4">
          <div className="relative group">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-colors" size={16} />
            <input 
              type="text" 
              placeholder="PESQUISAR..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 pr-4 py-2 bg-white dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-full text-[10px] font-bold focus:outline-none focus:ring-4 focus:ring-[var(--gr-primary)]/10 transition-all uppercase outline-none"
            />
          </div>
        </div>
      </div>

      {/* Lista de Solicitações */}
      {error && (
        <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-2xl text-red-600">
          <p className="font-bold">Erro ao carregar solicitações:</p>
          <p className="text-sm">{error}</p>
        </div>
      )}

      {loading ? (
        <div className="flex items-center justify-center py-20">
          <RefreshCw size={48} className="text-[var(--gr-primary)] animate-spin" />
        </div>
      ) : filteredRequests.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 gap-6">
          <div className="w-24 h-24 bg-[var(--gr-primary)]/10 rounded-full flex items-center justify-center">
            <Radio size={48} className="text-[var(--gr-primary)]" />
          </div>
          <div className="text-center space-y-2">
            <h3 className="text-2xl font-bold text-slate-800 dark:text-white">
              Nenhuma solicitação encontrada
            </h3>
            <p className="text-slate-500 dark:text-slate-400">
              {searchTerm ? 'Tente ajustar os filtros de busca' : 'Não há solicitações neste status'}
            </p>
          </div>
        </div>
      ) : (
        <div className="grid gap-4">
          {filteredRequests.map((request) => (
            <div
              key={request.id}
              className="p-6 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5 hover:border-[var(--gr-primary)]/20 transition-all"
            >
              <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                {/* Info Principal */}
                <div className="flex-1 space-y-3">
                  <div className="flex items-center gap-3 flex-wrap">
                    <span className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest ${getStatusColor(request.status)}`}>
                      {request.status}
                    </span>
                    <span className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest border ${getRiskColor(request.riskLevel)}`}>
                      Risco: {request.riskLevel}
                    </span>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                      <User size={16} />
                      <span className="font-bold text-slate-800 dark:text-white">{request.driverName}</span>
                      <span className="text-xs">({request.driverCpf})</span>
                    </div>
                    <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                      <Truck size={16} />
                      <span className="font-bold text-slate-800 dark:text-white">{request.plate}</span>
                      <span className="text-xs">• {request.operation}</span>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                      <MapPin size={16} />
                      <span className="text-sm">{request.origin} → {request.destination}</span>
                    </div>
                    <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400">
                      <DollarSign size={16} />
                      <span className="text-sm font-bold">R$ {request.cargoValue.toLocaleString('pt-BR')}</span>
                    </div>
                  </div>
                </div>

                {/* Ações */}
                <div className="flex flex-col gap-2 min-w-[140px]">
                  <button 
                    onClick={() => openDetails(request)}
                    className="px-4 py-2 bg-[var(--gr-primary)] text-white rounded-full text-[10px] font-bold uppercase tracking-widest hover:bg-[var(--gr-primary)]/90 transition-all flex items-center justify-center gap-2"
                  >
                    Ver Detalhes
                    <ChevronRight size={14} />
                  </button>
                  {request.status === 'PENDING' && !request.processedBy && (
                    <button 
                      onClick={() => handleAttend(request.id)}
                      className="px-4 py-2 bg-slate-100 dark:bg-[#141414] text-slate-800 dark:text-white rounded-full text-[10px] font-bold uppercase tracking-widest hover:bg-slate-200 dark:hover:bg-[#1f1f1f] transition-all"
                    >
                      Atender
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal de Detalhes */}
      <Modal 
        isOpen={isDetailModalOpen} 
        onClose={() => setIsDetailModalOpen(false)}
        title="Detalhes da Solicitação"
      >
        {selectedRequest && (
          <div className="space-y-8">
            <div className="grid grid-cols-2 gap-6">
              <div className="space-y-1">
                <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Motorista</span>
                <p className="text-lg font-bold text-slate-800 dark:text-white">{selectedRequest.driverName}</p>
                <p className="text-sm text-slate-500 font-medium">{selectedRequest.driverCpf}</p>
              </div>
              <div className="space-y-1">
                <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Veículo</span>
                <p className="text-lg font-bold text-slate-800 dark:text-white">{selectedRequest.plate}</p>
                <p className="text-sm text-slate-500 font-medium">{selectedRequest.operation}</p>
              </div>
            </div>

            <div className="p-6 bg-slate-50 dark:bg-[#141414] rounded-3xl space-y-6">
              <div className="flex items-center justify-between">
                <div className="space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Origem</span>
                  <p className="font-bold text-slate-800 dark:text-white">{selectedRequest.origin}</p>
                </div>
                <ChevronRight className="text-slate-300" />
                <div className="space-y-1 text-right">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Destino</span>
                  <p className="font-bold text-slate-800 dark:text-white">{selectedRequest.destination}</p>
                </div>
              </div>

              <div className="pt-6 border-t border-slate-200 dark:border-white/5 grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Valor da Carga</span>
                  <p className="font-bold text-slate-800 dark:text-white">R$ {selectedRequest.cargoValue.toLocaleString('pt-BR')}</p>
                </div>
                <div className="space-y-1 text-right">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Nível de Risco</span>
                  <span className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-bold uppercase ${getRiskColor(selectedRequest.riskLevel)}`}>
                    {selectedRequest.riskLevel}
                  </span>
                </div>
              </div>
            </div>

            {selectedRequest.processedBy && (
              <div className="space-y-3">
                <h4 className="text-xs font-bold text-slate-800 dark:text-white uppercase tracking-wider flex items-center gap-2">
                  <Clock size={14} className="text-[var(--gr-primary)]" />
                  Histórico de Atendimento
                </h4>
                <div className="p-4 bg-slate-100 dark:bg-[#141414] rounded-2xl border border-slate-200 dark:border-white/5">
                  <p className="text-sm font-medium text-slate-700 dark:text-slate-300">
                    Atendido por <span className="font-bold">{selectedRequest.processedBy}</span> em {new Date(selectedRequest.processedAt).toLocaleString('pt-BR')}
                  </p>
                </div>
              </div>
            )}

            <div className="flex gap-4 pt-4">
              <button 
                onClick={() => setIsDetailModalOpen(false)}
                className="flex-1 py-4 bg-slate-100 dark:bg-[#141414] text-slate-800 dark:text-white rounded-2xl font-bold text-xs uppercase tracking-widest hover:bg-slate-200 dark:hover:bg-[#1f1f1f] transition-all"
              >
                Fechar
              </button>
              {selectedRequest.status === 'PENDING' && (
                <button 
                  className="flex-2 py-4 bg-[var(--gr-primary)] text-white rounded-2xl font-bold text-xs uppercase tracking-widest hover:bg-[var(--gr-primary)]/90 transition-all px-12"
                >
                  Liberar Viagem
                </button>
              )}
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default GrMonitoringView;
