"use client";

import type React from "react";
import Link from "next/link";
import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useParams } from "next/navigation";
import { toast } from "@/hooks/use-toast";

// [TIPAGEM] Interfaces importadas dos serviços
import { pacientesApi, Patient } from "@/services/pacientesApi";
import { relatoriosApi, Report } from "@/services/relatoriosApi";

export default function LaudosPage() {
    const params = useParams();
    const patientId = params.id as string;

    // [ESTADO] Gerenciamento de estado robusto
    const [patient, setPatient] = useState<Patient | null>(null);
    const [laudos, setLaudos] = useState<Report[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage] = useState(5);

    // [API] Lógica de busca de dados corrigida
    useEffect(() => {
        if (patientId) {
            const fetchPatientAndLaudos = async () => {
                setIsLoading(true);
                setError(null);
                try {
                    const [patientData, allLaudosData] = await Promise.all([
                        pacientesApi.getById(patientId),
                        relatoriosApi.list() // Corrigido: Chama a função sem argumentos
                    ]);

                    // Filtra os laudos para o paciente específico no lado do cliente
                    const patientLaudos = allLaudosData.filter(laudo => laudo.patient_id === patientId);

                    setPatient(patientData);
                    setLaudos(patientLaudos);
                } catch (err: any) {
                    const errorMessage = "Falha ao buscar os dados do paciente e seus laudos.";
                    setError(errorMessage);
                    toast({
                        title: "Erro",
                        description: err.message || errorMessage,
                        variant: "destructive",
                    });
                } finally {
                    setIsLoading(false);
                }
            };

            fetchPatientAndLaudos();
        }
    }, [patientId]);

    const indexOfLastItem = currentPage * itemsPerPage;
    const indexOfFirstItem = indexOfLastItem - itemsPerPage;
    const currentItems = laudos.slice(indexOfFirstItem, indexOfLastItem);
    const totalPages = Math.ceil(laudos.length / itemsPerPage);

    const paginate = (pageNumber: number) => setCurrentPage(pageNumber);

    // [UI] Feedback Visual para Carregamento e Erro
    if (isLoading) {
        return <div className="container mx-auto p-4 text-center">Carregando...</div>;
    }

    if (error) {
        return <div className="container mx-auto p-4 text-center text-red-600">{error}</div>;
    }

    return (
        <div className="container mx-auto p-4">
            {patient && (
                <Card className="mb-4">
                    <CardHeader>
                        <CardTitle>Informações do Paciente</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <p><strong>Nome:</strong> {patient.full_name}</p>
                        <p><strong>Email:</strong> {patient.email}</p>
                        <p><strong>Telefone:</strong> {patient.phone_mobile}</p>
                    </CardContent>
                </Card>
            )}
            <Card>
                <CardHeader className="flex flex-row items-center justify-between">
                    <CardTitle>Laudos do Paciente</CardTitle>
                    <Link href={`/doctor/medicos/${patientId}/laudos/novo`}>
                        <Button>Criar Novo Laudo</Button>
                    </Link>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Nº do Pedido</TableHead>
                                <TableHead>Exame</TableHead>
                                <TableHead>Diagnóstico</TableHead>
                                <TableHead>Status</TableHead>
                                <TableHead>Data de Criação</TableHead>
                                <TableHead>Ações</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {currentItems.length > 0 ? (
                                currentItems.map((laudo) => (
                                    <TableRow key={laudo.id}>
                                        <TableCell>{laudo.order_number}</TableCell>
                                        <TableCell>{laudo.exam}</TableCell>
                                        <TableCell>{laudo.diagnosis}</TableCell>
                                        <TableCell>{laudo.status}</TableCell>
                                        <TableCell>{new Date(laudo.created_at).toLocaleDateString()}</TableCell>
                                        <TableCell>
                                            <Link href={`/doctor/medicos/${patientId}/laudos/${laudo.id}/editar`}>
                                                <Button variant="outline" size="sm">Editar</Button>
                                            </Link>
                                        </TableCell>
                                    </TableRow>
                                ))
                            ) : (
                                <TableRow>
                                    <TableCell colSpan={6} className="text-center">Nenhum laudo encontrado.</TableCell>
                                </TableRow>
                            )}
                        </TableBody>
                    </Table>
                    {totalPages > 1 && (
                        <div className="flex justify-center space-x-2 mt-4 p-4">
                            {Array.from({ length: totalPages }, (_, i) => (
                                <Button key={i} onClick={() => paginate(i + 1)} variant={currentPage === i + 1 ? 'default' : 'outline'}>
                                    {i + 1}
                                </Button>
                            ))}
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}