
"use client";

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { fetchWrapper } from '@/api/fetchWrapper';
import { BASE_URL } from '@/api/config';

interface Doctor {
    id: string;
    first_name: string;
    last_name: string;
    username: string;
    full_name: string;
    email: string;
    is_active: boolean;
    created_at: string;
}

interface Insurance {
    id: number;
    name: string;
}

interface PrescriptionContextType {
    doctors: Doctor[];
    baseInsurances: Insurance[];
    supplementaryInsurances: Insurance[];
    loading: boolean;
    error: string | null;
}

const PrescriptionContext = createContext<PrescriptionContextType | undefined>(undefined);

export const PrescriptionProvider = ({ children }: { children: ReactNode }) => {
    const [doctors, setDoctors] = useState<Doctor[]>([]);
    const [baseInsurances, setBaseInsurances] = useState<Insurance[]>([]);
    const [supplementaryInsurances, setSupplementaryInsurances] = useState<Insurance[]>([]);

    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const [doctorsResponse, baseInsurancesResponse, supplementaryInsurancesResponse ] = await Promise.all([
                    fetchWrapper(`${BASE_URL}/api/users/?role=DOCTOR`),
                    fetchWrapper(`${BASE_URL}/api/insurances/base/`),
                    fetchWrapper(`${BASE_URL}/api/insurances/supplementary/`),
                ]);

                if (doctorsResponse.ok) {
                    const doctorsData = await doctorsResponse.json();
                    setDoctors(doctorsData.results);
                } else {
                    setError("Failed to load doctors.");
                }

                if (baseInsurancesResponse.ok) {
                    const insurancesData = await baseInsurancesResponse.json();
                    setBaseInsurances(insurancesData.results);
                } else {
                    setError((prevError) => prevError ? `${prevError} Failed to load base insurances.` : "Failed to load base insurances.");
                }

                if (supplementaryInsurancesResponse.ok) {
                    const insurancesData = await supplementaryInsurancesResponse.json();
                    setSupplementaryInsurances(insurancesData.results);
                } else {
                    setError((prevError) => prevError ? `${prevError} Failed to load supplementary insurances.` : "Failed to load supplementary insurances.");
                }
            } catch {
                setError("An error occurred while fetching data.");
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, []);

    return (
        <PrescriptionContext.Provider value={{
            doctors,
            baseInsurances: baseInsurances,
            supplementaryInsurances: supplementaryInsurances,
            loading,
            error
        }}>
            {children}
        </PrescriptionContext.Provider>
    );
};

export const usePrescriptionContext = () => {
    const context = useContext(PrescriptionContext);
    if (context === undefined) {
        throw new Error('usePrescriptionContext must be used within a PrescriptionProvider');
    }
    return context;
};
