"use client";

import { useState, useEffect, Fragment } from "react";
import { useRouter } from 'next/navigation';
import Header from "@/components/Header";
import {
  Package,
  Truck,
  MapPin,
  Clock,
  CheckCircle,
  AlertCircle,
  Search,
  Filter,
  ChevronLeft,
  ChevronRight,
  RefreshCw,
  RotateCcw,
  Eye,
  Phone,
  Mail,
  Calendar,
} from "lucide-react";
import { useEntregas } from '@/hooks/useEntregas';
import { EntregaBff, statusConfig } from '@/services/entregasApiService';

const statusIcons = {
  pendente: Clock,
  em_transito: Truck,
  entregue: CheckCircle,
  cancelada: AlertCircle,
};

function EntregasContent() {
  const router = useRouter();
  const [user, setUser] = useState<any>(null);
  const [filtroStatus, setFiltroStatus] = useState<string>("todos");
  const [termoBusca, setTermoBusca] = useState("");
  const [userLoading, setUserLoading] = useState(true);
  const [entregaExpandida, setEntregaExpandida] = useState<string | null>(null);

  const {
    entregas,
    loading,
    error,
    totalEntregas,
    currentPage,
    totalPages,
    listarEntregas,
    atualizarStatusEntrega,
    setCurrentPage,
    limparErro,
    estatisticas,
  } = useEntregas();

  // Verificação de autenticação
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const storedToken = localStorage.getItem('access_token');

        if (!storedToken) {
          router.push("/login");
          return;
        }


        const response = await fetch(`${process.env.NEXT_PUBLIC_BFF_API_URL}/auth/me`, {
          method: "GET",
          headers: {
            "accept": "application/json",
            "Authorization": `Bearer ${storedToken}`,
          },
        });


        if (response.ok) {
          const userData = await response.json();
          setUser(userData);
        } else {
          localStorage.removeItem('access_token');
          router.push("/login");
          return;
        }
      } catch (error) {
        console.error('❌ Erro ao verificar autenticação:', error);
        localStorage.removeItem('access_token');
        router.push('/login');
      } finally {
        setUserLoading(false);
      }
    };

    checkAuth();
  }, [router]);

  // Carregar entregas quando usuário for autenticado
  useEffect(() => {
    if (user && !userLoading) {
      listarEntregas({
        page: 1,
        search: termoBusca.trim() || undefined,
        status: filtroStatus !== "todos" ? filtroStatus : undefined,
      }).then(() => {
      }).catch((error) => {
        console.error("❌ Erro ao carregar entregas:", error);
      });
    }
  }, [user, userLoading, listarEntregas]);

  const handleSearch = async () => {
    limparErro();
    await listarEntregas({
      page: 1,
      search: termoBusca.trim() || undefined,
      status: filtroStatus !== "todos" ? filtroStatus : undefined,
    });
  };

  const handleStatusFilter = async (status: string) => {
    setFiltroStatus(status);
    limparErro();
    await listarEntregas({
      page: 1,
      search: termoBusca.trim() || undefined,
      status: status !== "todos" ? status : undefined,
    });
  };

  const handleStatusChange = async (
    entregaId: string,
    novoStatus: EntregaBff["status"]
  ) => {
    const entregaAtualizada = await atualizarStatusEntrega(entregaId, novoStatus);
    if (entregaAtualizada) {
    }
  };

  const handlePrevPage = async () => {
    if (currentPage > 1) {
      const newPage = currentPage - 1;
      setCurrentPage(newPage);
      await listarEntregas({
        page: newPage,
        search: termoBusca.trim() || undefined,
        status: filtroStatus !== "todos" ? filtroStatus : undefined,
      });
    }
  };

  const handleNextPage = async () => {
    if (currentPage < totalPages) {
      const newPage = currentPage + 1;
      setCurrentPage(newPage);
      await listarEntregas({
        page: newPage,
        search: termoBusca.trim() || undefined,
        status: filtroStatus !== "todos" ? filtroStatus : undefined,
      });
    }
  };

  const handleRefresh = async () => {
    limparErro();
    await listarEntregas({
      page: currentPage,
      search: termoBusca.trim() || undefined,
      status: filtroStatus !== "todos" ? filtroStatus : undefined,
    });
  };

  if (userLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">Verificando autenticação...</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Verificando autenticação...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Header
        user={user}
        title="Entregas"
        subtitle="Gerencie e acompanhe todas as entregas"
      />
      <div className="p-6">
        <div className="max-w-7xl mx-auto">
          {/* Filtros e Busca */}
          <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
            <div className="flex flex-col md:flex-row gap-4">
              {/* Busca */}
              <div className="flex-1">
                <div className="flex">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                      type="text"
                      placeholder="Buscar por número, cliente ou endereço..."
                      value={termoBusca}
                      onChange={(e) => setTermoBusca(e.target.value)}
                      onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                  </div>
                  <button
                    onClick={handleSearch}
                    disabled={loading}
                    className="px-4 py-2 bg-blue-600 text-white border border-blue-600 rounded-r-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
                  >
                    Buscar
                  </button>
                </div>
              </div>

              {/* Filtro por Status */}
              <div className="md:w-48">
                <div className="relative">
                  <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                  <select
                    value={filtroStatus}
                    onChange={(e) => handleStatusFilter(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none"
                  >
                    <option value="todos">Todos os Status</option>
                    <option value="pendente">Pendente</option>
                    <option value="em_transito">Em Trânsito</option>
                    <option value="entregue">Entregue</option>
                    <option value="cancelado">Cancelada</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          {/* Estatísticas */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-6 mb-8">
            <div className="bg-white rounded-lg shadow-sm p-3 sm:p-6">
              <div className="flex items-center gap-3 sm:gap-4">
                <div className="p-2 bg-yellow-100 rounded-lg flex-shrink-0">
                  <Clock className="w-5 sm:w-6 h-5 sm:h-6 text-yellow-600" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs sm:text-sm font-medium text-gray-600">Pendentes</p>
                  <p className="text-lg sm:text-2xl font-bold text-gray-900 break-words">
                    {entregas ? entregas.filter((e) => e && e.status === "pendente").length : 0}
                  </p>
                </div>
              </div>
            </div>

            <div className="bg-white rounded-lg shadow-sm p-3 sm:p-6">
              <div className="flex items-center gap-3 sm:gap-4">
                <div className="p-2 bg-blue-100 rounded-lg flex-shrink-0">
                  <Truck className="w-5 sm:w-6 h-5 sm:h-6 text-blue-600" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs sm:text-sm font-medium text-gray-600">
                    Em Trânsito
                  </p>
                  <p className="text-lg sm:text-2xl font-bold text-gray-900 break-words">
                    {entregas ? entregas.filter((e) => e && e.status === "em_transito").length : 0}
                  </p>
                </div>
              </div>
            </div>

            <div className="bg-white rounded-lg shadow-sm p-3 sm:p-6">
              <div className="flex items-center gap-3 sm:gap-4">
                <div className="p-2 bg-green-100 rounded-lg flex-shrink-0">
                  <CheckCircle className="w-5 sm:w-6 h-5 sm:h-6 text-green-600" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs sm:text-sm font-medium text-gray-600">Entregues</p>
                  <p className="text-lg sm:text-2xl font-bold text-gray-900 break-words">
                    {entregas ? entregas.filter((e) => e && e.status === "entregue").length : 0}
                  </p>
                </div>
              </div>
            </div>

            <div className="bg-white rounded-lg shadow-sm p-3 sm:p-6">
              <div className="flex items-center gap-3 sm:gap-4">
                <div className="p-2 bg-gray-100 rounded-lg flex-shrink-0">
                  <Package className="w-5 sm:w-6 h-5 sm:h-6 text-gray-600" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs sm:text-sm font-medium text-gray-600">Total</p>
                  <p className="text-lg sm:text-2xl font-bold text-gray-900 break-words">
                    {entregas ? entregas.length : 0}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Mensagem de Erro */}
          {error && (
            <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
              <div className="flex">
                <AlertCircle className="w-5 h-5 text-red-400 mr-3 mt-0.5 flex-shrink-0" />
                <div>
                  <h3 className="text-sm font-medium text-red-800">Erro ao carregar entregas</h3>
                  <p className="mt-1 text-sm text-red-700">{error}</p>
                  <button
                    onClick={handleRefresh}
                    className="mt-3 inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-red-700 bg-red-100 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                  >
                    <RotateCcw className="w-4 h-4 mr-2" />
                    Tentar Novamente
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Lista de Entregas */}
          <div className="bg-white rounded-lg shadow-sm overflow-hidden">
            <div className="px-3 sm:px-6 py-4 border-b border-gray-200">
              <h2 className="text-base sm:text-lg font-semibold text-gray-900">
                Entregas ({entregas.length})
              </h2>
            </div>

            <div className="overflow-x-auto">
              {/* Tabela para desktop, cards para mobile */}
              <div className="hidden sm:block">
                <table className="w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Número
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Destinatário
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Endereço
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Status
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Data Est.
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Taxa
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Rastreamento
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Distância
                      </th>
                      <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        Ações
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {entregas && entregas.length > 0 ? entregas.map((entrega: EntregaBff) => {
                      if (!entrega || !entrega.id) return null;

                      const status = entrega.status as keyof typeof statusConfig;
                      const statusInfo = statusConfig[status] || statusConfig.pendente;

                      return (
                        <Fragment key={entrega.id}>
                          <tr className="hover:bg-gray-50">
                            <td className="px-3 sm:px-6 py-4 whitespace-nowrap text-xs sm:text-sm font-medium text-gray-900">
                              {entrega.numeroEntrega || '-'}
                            </td>
                            <td className="px-3 sm:px-6 py-4 whitespace-nowrap text-xs sm:text-sm text-gray-900">
                              {entrega.nomeDestinatario || '-'}
                            </td>
                            <td className="px-3 sm:px-6 py-4 text-xs sm:text-sm text-gray-900">
                              <div className="flex items-center gap-1">
                                <MapPin className="w-3 sm:w-4 h-3 sm:h-4 text-gray-400 flex-shrink-0" />
                                <span className="line-clamp-2">{`${entrega.enderecoEntrega}, ${entrega.bairroEntrega}, ${entrega.cidadeEntrega}/${entrega.estadoEntrega}` || '-'}</span>
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <span
                                className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusInfo.color
                                  }`}
                              >
                                <Clock className="w-3 h-3 mr-1" />
                                {statusInfo.label}
                              </span>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                              {entrega.dataEntregaEstimativa ? new Date(entrega.dataEntregaEstimativa).toLocaleDateString(
                                "pt-BR"
                              ) : '-'}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                              R$ {entrega.taxaEntrega ? Number(entrega.taxaEntrega).toFixed(2) : '0.00'}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                              <span className="font-mono text-xs bg-gray-100 px-2 py-1 rounded">
                                {entrega.codigoRastreamento || '-'}
                              </span>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                              {entrega.distancia ? `${entrega.distancia.toFixed(1)} km` : '-'}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                              <div className="flex items-center space-x-2">
                                <button
                                  onClick={() => setEntregaExpandida(entregaExpandida === entrega.id ? null : entrega.id)}
                                  className="p-1 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded"
                                  title="Ver detalhes"
                                >
                                  <Eye className="w-4 h-4" />
                                </button>
                                <select
                                  value={entrega.status}
                                  onChange={(e) =>
                                    handleStatusChange(
                                      entrega.id,
                                      e.target.value as EntregaBff["status"]
                                    )
                                  }
                                  disabled={loading}
                                  className="text-xs border border-gray-300 rounded px-2 py-1 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                >
                                  <option value="pendente">Pendente</option>
                                  <option value="em_transito">Em Trânsito</option>
                                  <option value="entregue">Entregue</option>
                                  <option value="cancelado">Cancelada</option>
                                </select>
                              </div>
                            </td>
                          </tr>
                          {entregaExpandida === entrega.id && (
                            <tr className="bg-gray-50">
                              <td colSpan={9} className="px-3 sm:px-6 py-4">
                                <div className="bg-white rounded-lg border border-gray-200 p-3 sm:p-4">
                                  <h4 className="text-base sm:text-lg font-medium text-gray-900 mb-4">
                                    Detalhes da Entrega #{entrega.numeroEntrega}
                                  </h4>

                                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                                    {/* Informações do Destinatário */}
                                    <div className="space-y-3">
                                      <h5 className="font-medium text-gray-800 border-b border-gray-200 pb-2">
                                        Destinatário
                                      </h5>
                                      <div className="space-y-2 text-sm">
                                        <div className="flex items-center">
                                          <span className="font-medium text-gray-600 w-20">Nome:</span>
                                          <span className="text-gray-900">{entrega.nomeDestinatario}</span>
                                        </div>
                                        <div className="flex items-center">
                                          <Phone className="w-4 h-4 text-gray-400 mr-1" />
                                          <span className="font-medium text-gray-600 w-16">Telefone:</span>
                                          <span className="text-gray-900">{entrega.telefoneDestinatario}</span>
                                        </div>
                                        <div className="flex items-center">
                                          <Mail className="w-4 h-4 text-gray-400 mr-1" />
                                          <span className="font-medium text-gray-600 w-16">Email:</span>
                                          <span className="text-gray-900 truncate">{entrega.emailDestinatario}</span>
                                        </div>
                                      </div>
                                    </div>

                                    {/* Endereço Completo */}
                                    <div className="space-y-3">
                                      <h5 className="font-medium text-gray-800 border-b border-gray-200 pb-2">
                                        Endereço de Entrega
                                      </h5>
                                      <div className="space-y-2 text-sm">
                                        <div>
                                          <span className="font-medium text-gray-600">Logradouro:</span>
                                          <p className="text-gray-900">{entrega.enderecoEntrega}, {entrega.numeroEntrega}</p>
                                        </div>
                                        <div>
                                          <span className="font-medium text-gray-600">Complemento:</span>
                                          <p className="text-gray-900">{entrega.complementoEntrega || '-'}</p>
                                        </div>
                                        <div>
                                          <span className="font-medium text-gray-600">Bairro:</span>
                                          <p className="text-gray-900">{entrega.bairroEntrega}</p>
                                        </div>
                                        <div>
                                          <span className="font-medium text-gray-600">Cidade/UF:</span>
                                          <p className="text-gray-900">{entrega.cidadeEntrega}/{entrega.estadoEntrega}</p>
                                        </div>
                                        <div>
                                          <span className="font-medium text-gray-600">CEP:</span>
                                          <p className="text-gray-900">{entrega.cepEntrega}</p>
                                        </div>
                                      </div>
                                    </div>

                                    {/* Informações da Entrega */}
                                    <div className="space-y-3">
                                      <h5 className="font-medium text-gray-800 border-b border-gray-200 pb-2">
                                        Informações da Entrega
                                      </h5>
                                      <div className="space-y-2 text-sm">
                                        <div className="flex items-center">
                                          <Calendar className="w-4 h-4 text-gray-400 mr-1" />
                                          <span className="font-medium text-gray-600 w-20">Estimativa:</span>
                                          <span className="text-gray-900">
                                            {entrega.dataEntregaEstimativa ? new Date(entrega.dataEntregaEstimativa).toLocaleString("pt-BR") : '-'}
                                          </span>
                                        </div>
                                        <div className="flex items-center">
                                          <Calendar className="w-4 h-4 text-gray-400 mr-1" />
                                          <span className="font-medium text-gray-600 w-20">Real:</span>
                                          <span className="text-gray-900">
                                            {entrega.dataEntregaReal && entrega.dataEntregaReal !== null ? new Date(entrega.dataEntregaReal).toLocaleString("pt-BR") : 'Não entregue'}
                                          </span>
                                        </div>
                                        <div>
                                          <span className="font-medium text-gray-600">Taxa:</span>
                                          <span className="text-gray-900 ml-2">R$ {entrega.taxaEntrega ? entrega.taxaEntrega.toFixed(2) : '0.00'}</span>
                                        </div>
                                        <div>
                                          <span className="font-medium text-gray-600">Distância:</span>
                                          <span className="text-gray-900 ml-2">{entrega.distancia ? entrega.distancia.toFixed(1) : '0.0'} km</span>
                                        </div>
                                        {entrega.observacoesEntrega && (
                                          <div>
                                            <span className="font-medium text-gray-600">Observações:</span>
                                            <p className="text-gray-900 mt-1">{entrega.observacoesEntrega}</p>
                                          </div>
                                        )}
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </td>
                            </tr>
                          )}
                        </Fragment>
                      );
                    }) : null}
                  </tbody>
                </table>
              </div>

              {/* Cards para mobile */}
              <div className="sm:hidden space-y-4 p-4">
                {entregas && entregas.length > 0 ? entregas.map((entrega: EntregaBff) => {
                  if (!entrega || !entrega.id) return null;

                  const status = entrega.status as keyof typeof statusConfig;
                  const statusInfo = statusConfig[status] || statusConfig.pendente;

                  return (
                    <div key={entrega.id} className="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex-1">
                          <p className="font-medium text-gray-900 text-sm"># {entrega.numeroEntrega}</p>
                          <p className="text-xs text-gray-600">{entrega.nomeDestinatario || '-'}</p>
                        </div>
                        <span className={`inline-flex items-center px-2.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap ${statusInfo.bgColor || statusInfo.color}`}>
                          {statusInfo.label}
                        </span>
                      </div>

                      <div className="space-y-2 text-sm border-t border-gray-100 pt-3">
                        <div className="flex justify-between">
                          <span className="text-gray-600">Endereço:</span>
                          <span className="text-gray-900 text-right flex-1 ml-2">{`${entrega.enderecoEntrega}, ${entrega.bairroEntrega}`}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Data Est.:</span>
                          <span className="text-gray-900">{entrega.dataEntregaEstimativa ? new Date(entrega.dataEntregaEstimativa).toLocaleDateString('pt-BR') : '-'}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Taxa:</span>
                          <span className="text-gray-900">R$ {entrega.taxaEntrega ? entrega.taxaEntrega.toFixed(2) : '0.00'}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Distância:</span>
                          <span className="text-gray-900">{entrega.distancia ? entrega.distancia.toFixed(1) : '0.0'} km</span>
                        </div>
                      </div>

                      <button
                        onClick={() => setEntregaExpandida(entregaExpandida === entrega.id ? null : entrega.id)}
                        className="w-full mt-3 px-3 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100"
                      >
                        {entregaExpandida === entrega.id ? 'Ocultar Detalhes' : 'Ver Detalhes'}
                      </button>

                      {entregaExpandida === entrega.id && (
                        <div className="bg-gray-50 rounded-lg border border-gray-200 p-3 space-y-3 text-sm">
                          <h5 className="font-medium text-gray-900 border-b border-gray-200 pb-2">Detalhes</h5>
                          <div>
                            <p className="text-gray-600 text-xs mb-1">Contato</p>
                            <p className="text-gray-900">{entrega.telefoneDestinatario}</p>
                            <p className="text-gray-900 break-all">{entrega.emailDestinatario}</p>
                          </div>
                          <div>
                            <p className="text-gray-600 text-xs mb-1">Rastreamento</p>
                            <p className="text-gray-900 font-mono text-xs break-all">{entrega.codigoRastreamento || '-'}</p>
                          </div>
                          {entrega.observacoesEntrega && (
                            <div>
                              <p className="text-gray-600 text-xs mb-1">Observações</p>
                              <p className="text-gray-900 text-xs">{entrega.observacoesEntrega}</p>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  );
                }) : null}
              </div>
            </div>

            {entregas.length === 0 && !loading && (
              <div className="text-center py-12">
                <Package className="mx-auto h-12 w-12 text-gray-400" />
                <h3 className="mt-2 text-sm font-medium text-gray-900">
                  Nenhuma entrega encontrada
                </h3>
                <p className="mt-1 text-sm text-gray-500">
                  {error ? 'Erro ao carregar entregas. Tente novamente.' : 'Não há entregas cadastradas no momento.'}
                </p>
                {error && (
                  <button
                    onClick={handleRefresh}
                    className="mt-3 inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                  >
                    <RotateCcw className="w-4 h-4 mr-2" />
                    Tentar Novamente
                  </button>
                )}
              </div>
            )}

            {loading && (
              <div className="text-center py-12">
                <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                <p className="text-gray-600">Carregando entregas...</p>
              </div>
            )}

            {/* Paginação */}
            {totalPages > 1 && (
              <div className="bg-white px-3 sm:px-4 py-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 sm:gap-0 border-t border-gray-200">
                <div className="flex-1 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0">
                  <div className="text-center sm:text-left">
                    <p className="text-xs sm:text-sm text-gray-700">
                      Mostrando página <span className="font-medium">{currentPage}</span> de{" "}
                      <span className="font-medium">{totalPages}</span> páginas, total de{" "}
                      <span className="font-medium">{totalEntregas}</span> entregas
                    </p>
                  </div>
                  <div className="flex justify-center sm:justify-end">
                    <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                      <button
                        onClick={handlePrevPage}
                        disabled={currentPage <= 1 || loading}
                        className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        <ChevronLeft className="h-5 w-5" />
                      </button>
                      <span className="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                        {currentPage}
                      </span>
                      <button
                        onClick={handleNextPage}
                        disabled={currentPage >= totalPages || loading}
                        className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        <ChevronRight className="h-5 w-5" />
                      </button>
                    </nav>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default function EntregasPage() {
  return <EntregasContent />;
}
