'use client';

import PatientDetails from "@/app/components/Patient/PatientDetails";
import { api } from "@/lib/api";
import { useLanguage } from '@/lib/language-context';
import { useParams } from 'next/navigation';
import { useEffect, useState } from 'react';

export default function PatientPage() {
    const { t } = useLanguage();
    const params = useParams();
    const id = params.id as string;
    const [patient, setPatient] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchPatient = async () => {
            try {
                setLoading(true);
                const res = await api.patients.getById(id);
                if (res.success && res.data) {
                    setPatient(res.data);
                } else {
                    setError(res.error || t('patientDetails.fetchFailed'));
                }
            } catch (err: any) {
                console.error('Failed to fetch patient:', err);
                setError(err.message || t('patientDetails.fetchFailed'));
            } finally {
                setLoading(false);
            }
        };
        if (id) {
            fetchPatient();
        }
    }, [id, t]);

    if (loading) {
        return <div className="p-8">{t('common.loading')}</div>;
    }

    if (error || !patient) {
        return <div className="p-8 text-red-600">{t('patientDetails.notFound').replace('{id}', String(id))}</div>;
    }

    return <PatientDetails patient={patient} />;
}
