import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { AgentDetailsModal } from '../components/AgentDetailsModal';
import { AgentDTO } from '@/types/rh';
import { rhService } from '@/services/rhService';
import { toast } from 'sonner';
import { PageHeader } from '@/components/common/PageHeader';

export function AgentDetailsPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [agent, setAgent] = useState<AgentDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(true);

  useEffect(() => {
    if (id) {
      loadAgent(id);
    }
  }, [id]);

  const loadAgent = async (agentId: string) => {
    try {
      setLoading(true);
      const data = await rhService.getAgentById(agentId);
      setAgent(data);
    } catch (error) {
      toast.error('Erro ao carregar dados do funcionário');
      navigate('/rh/agents');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setIsModalOpen(false);
    navigate('/rh/agents');
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!agent) {
    return (
      <div className="p-6">
        <PageHeader
          title="Funcionário não encontrado"
          description="O funcionário solicitado não foi encontrado."
        />
        <Button onClick={() => navigate('/rh/agents')} className="mt-4">
          <ArrowLeft className="mr-2 h-4 w-4" />
          Voltar para lista
        </Button>
      </div>
    );
  }

  return (
    <div className="p-6">
      <div className="mb-4">
        <Button
          variant="ghost"
          onClick={() => navigate('/rh/agents')}
          className="mb-4"
        >
          <ArrowLeft className="mr-2 h-4 w-4" />
          Voltar para lista
        </Button>
      </div>

      <AgentDetailsModal
        open={isModalOpen}
        onOpenChange={handleClose}
        agent={agent}
      />
    </div>
  );
}

