'use client';

import { useEffect, useState } from 'react';
import { X } from 'lucide-react';

export default function ViewPrescriptionsModal({ patientId, patientName, onClose }) {
  const [prescriptions, setPrescriptions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchPrescriptions = async () => {
      try {
        const res = await fetch(`/api/prescriptions/patient/${patientId}`);
        const data = await res.json();
        console.log('Fetched prescriptions:', data);
        if (!res.ok) throw new Error(data.error || 'Failed to fetch prescriptions');
        setPrescriptions(data || []);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    fetchPrescriptions();
  }, [patientId]);

  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-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-hidden relative">
        <header className="sticky top-0 bg-white border-b px-6 py-4 flex justify-between items-center z-10">
          <h3 className="text-lg font-semibold">Prescriptions for {patientName}</h3>
          <button onClick={onClose} className="text-gray-500 hover:text-gray-700 text-2xl">
            <X />
          </button>
        </header>

        <div className="p-6 overflow-y-auto max-h-[calc(90vh-64px)]">
          {loading ? (
            <p className="text-sm text-gray-500">Loading...</p>
          ) : error ? (
            <p className="text-sm text-red-500">{error}</p>
          ) : prescriptions.length === 0 ? (
            <p className="text-sm text-gray-600">No prescriptions found.</p>
          ) : (
            <div className="space-y-4 text-sm text-gray-800">
              {prescriptions.map((prescription, idx) => (
                <div key={prescription.id || idx} className="border rounded-lg p-4 bg-gray-50 shadow-sm">
                  <div className="flex justify-between mb-2">
                    <p className="font-medium text-gray-700">
                      <span className="text-gray-500">Date:</span>{' '}
                      {new Date(prescription.createdAt).toLocaleDateString()}
                    </p>
                    <p className="text-gray-500">
                      <span className="font-medium text-gray-700">Doctor:</span> {prescription.doctorName}
                    </p>
                  </div>

                  <div className="text-sm text-gray-700">
                    <p className="font-semibold mb-1">Medications:</p>
                    <ul className="list-disc list-inside ml-4 space-y-1">
                      {prescription.medicines?.length > 0 ? (
                        prescription.medicines.map((med, i) => (
                          <li key={i}>
                            <span className="font-medium">{med.name}</span>
                            {med.dosage && <span className="text-gray-500"> — {med.dosage}</span>}
                            {med.duration && <span className="text-gray-400"> ({med.duration})</span>}
                          </li>
                        ))
                      ) : (
                        <li className="text-gray-400 italic">No medications listed</li>
                      )}
                    </ul>

                    <div className="mt-3">
                      <p>
                        <span className="font-semibold">Pharmacy:</span>{' '}
                        <span className="text-gray-700">{prescription.pharmacy || 'Not assigned'}</span>
                      </p>
                      <p>
                        <span className="font-semibold">Status:</span>{' '}
                        <span className="text-gray-700">{prescription.status}</span>
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

      </div>
    </div>
  );
}
