'use client';

import { useState, useEffect } from 'react';
import { useAuthStore } from '@/stores/authStore';

export default function ReferModal({ patient, onClose }) {
    const user = useAuthStore((state) => state.user);
    const [doctors, setDoctors] = useState([]);
    const [selectedDoctorId, setSelectedDoctorId] = useState('');
    const [loading, setLoading] = useState(true);
    const [submitting, setSubmitting] = useState(false);
    const [message, setMessage] = useState('');

    useEffect(() => {
        const fetchDoctors = async () => {
            try {
                const res = await fetch('/api/doctors');
                if (!res.ok) throw new Error('Failed to fetch doctors');
                const data = await res.json();
                setDoctors(data);
            } catch (error) {
                console.error('Error fetching doctors:', error.message);
            } finally {
                setLoading(false);
            }
        };
        fetchDoctors();
    }, []);

    const handleRefer = async () => {
        if (!selectedDoctorId) return;
        setSubmitting(true);
        try {
            
            const res = await fetch(`/api/refer/${patient.userId}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    referredDoctorId: selectedDoctorId,
                    referredById: user.id, 
                }),
            });

            if (!res.ok) throw new Error('Referral failed');
            setMessage('Patient successfully referred.');
        } catch (error) {
            console.error(error);
            setMessage('Error referring patient.');
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 px-4">
            <div className="bg-white rounded-xl shadow-lg w-full max-w-md p-6">
                <h2 className="text-xl font-semibold mb-4">Refer Patient</h2>
                <p className="mb-2 text-sm text-gray-700">Referring: <strong>{patient.firstName} {patient.lastName}</strong></p>
                {loading ? (
                    <p>Loading doctors...</p>
                ) : (
                    <>
                        <select
                            value={selectedDoctorId}
                            onChange={(e) => setSelectedDoctorId(e.target.value)}
                            className="w-full p-2 border rounded mb-4"
                        >
                            <option value="">Select a doctor</option>
                            {doctors.map((doc) => (
                                <option key={doc.userId} value={doc.userId}>
                                    Dr. {doc.firstName} {doc.lastName} ({doc.specialty || 'General'})
                                </option>
                            ))}
                        </select>
                        <button
                            onClick={handleRefer}
                            disabled={submitting}
                            className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700"
                        >
                            {submitting ? 'Referring...' : 'Confirm Referral'}
                        </button>
                        {message && <p className="mt-3 text-sm text-center text-gray-700">{message}</p>}
                        <button
                            onClick={onClose}
                            className="mt-3 w-full bg-red-600 text-white py-2 rounded hover:bg-red-700"
                        >
                            Close
                        </button>
                    </>
                )}
            </div>
        </div>
    );
}
