'use client';

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

export default function ViewLabTestsModal({ patientId, patientName, onClose }) {
  const [labTests, setLabTests] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchLabTests = async () => {
      try {
        const res = await fetch(`/api/lab-tests/${patientId}`);
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to fetch lab tests');

        const parsed = (Array.isArray(data) ? data : []).map(test => ({
          ...test,
          tests: (test.tests || []).map(t => {
            try {
              return typeof t === 'string' ? JSON.parse(t) : t;
            } catch {
              return { name: 'Invalid', reason: '' };
            }
          }),
        }));

        setLabTests(parsed);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    fetchLabTests();
  }, [patientId]);

  const statusBadge = (status) => {
    const base = "px-2 py-0.5 text-xs font-medium rounded-full";
    switch (status) {
      case 'completed':
        return <span className={clsx(base, 'bg-green-100 text-green-800')}>Completed</span>;
      case 'pending':
        return <span className={clsx(base, 'bg-yellow-100 text-yellow-800')}>Pending</span>;
      case 'in_progress':
        return <span className={clsx(base, 'bg-blue-100 text-blue-800')}>In Progress</span>;
      case 'rejected':
        return <span className={clsx(base, 'bg-red-100 text-red-700')}>Rejected</span>;
      default:
        return <span className={clsx(base, 'bg-gray-100 text-gray-600')}>{status}</span>;
    }
  };

  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">
            Lab Tests for {patientName || labTests[0]?.patientProfile?.firstName || 'Patient'}
          </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>
          ) : labTests.length === 0 ? (
            <p className="text-sm text-gray-600">No lab tests found.</p>
          ) : (
            <div className="space-y-4">
              {labTests.map((test, idx) => (
                <div
                  key={test.id || idx}
                  className="border rounded-lg p-4 bg-gray-50 shadow-sm space-y-3"
                >
                  <div className="flex justify-between items-start">
                    <div className="space-y-1">
                      <p className="text-sm font-medium text-gray-700">
                        <span className="text-gray-500">Date:</span>{' '}
                        {new Date(test.createdAt).toLocaleDateString()}
                      </p>
                      {test.labProfile && (
                        <p className="text-sm text-gray-700">
                          <span className="text-gray-500 font-medium">Lab:</span>{' '}
                          {test.labProfile.labName}
                        </p>
                      )}
                      {test.patientProfile && (
                        <p className="text-sm text-gray-700">
                          <span className="text-gray-500 font-medium">Patient:</span>{' '}
                          {test.patientProfile.firstName} {test.patientProfile.lastName}
                        </p>
                      )}
                    </div>
                    {statusBadge(test.status)}
                  </div>

                  <div className="text-sm text-gray-700">
                    <p className="font-semibold mb-1">Requested Tests:</p>
                    <ul className="list-disc list-inside space-y-1 ml-2">
                      {test.tests.map((t, i) => (
                        <li key={i}>
                          <span className="font-medium">{t.name}</span>
                          {t.reason && (
                            <span className="text-gray-500"> — {t.reason}</span>
                          )}
                        </li>
                      ))}
                    </ul>
                  </div>

                  {test.notes && (
                    <div className="mt-2 text-sm text-gray-700 border-t pt-2">
                      <p className="font-medium text-gray-800">Lab Notes:</p>
                      <p className="italic text-gray-600 whitespace-pre-line">{test.notes}</p>
                    </div>
                  )}

                  {test.resultFile && (
                    <div className="mt-2">
                      <p className="text-sm font-medium text-gray-700">Result File:</p>
                      <a href={test.resultFile} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline">
                        View result file
                      </a>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
