'use client';

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

export default function TestResults() {
  const user = useAuthStore((state) => state.user);
  const patientId = user?.id;

  const [testResults, setTestResults] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchTestResults = async () => {
      if (!patientId) return;

      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 test results');

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

        setTestResults(parsed);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchTestResults();
  }, [patientId]);

  return (
    <div className="bg-white rounded-lg shadow-md mt-6 max-w-5xl mx-auto p-6">
      <h3 className="text-2xl font-bold mb-4 text-gray-800">Your Lab Test Results</h3>

      {loading ? (
        <p className="text-sm text-gray-500">Loading results...</p>
      ) : error ? (
        <p className="text-sm text-red-500">{error}</p>
      ) : testResults.length === 0 ? (
        <div className="flex flex-col items-center justify-center text-center text-gray-500 mt-20">
          <TestTube2 className="w-12 h-12 mb-3 text-gray-400" />
          <p className="text-md font-semibold">No lab tests available yet</p>
          <p className="text-sm text-gray-400 max-w-sm">
            Once your doctor requests tests, results will appear here.
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {testResults.map((test) => (
            <div key={test.id} className="border rounded-lg p-4 bg-gray-50 shadow-sm">
              <div className="flex justify-between items-start mb-3">
                <div className="space-y-1">
                  <p className="text-gray-700 font-semibold">
                    <span className="text-gray-500">Date:</span>{' '}
                    {new Date(test.createdAt).toLocaleDateString()}
                  </p>

                  <p className="text-gray-700">
                    <span className="text-gray-500 font-medium">Status:</span>{' '}
                    <span
                      className={`inline-block px-2 py-1 rounded text-xs font-semibold uppercase ${test.status?.toLowerCase() === 'completed'
                        ? 'bg-green-100 text-green-700'
                        : test.status?.toLowerCase() === 'in_progress'
                          ? 'bg-blue-100 text-blue-700'
                          : 'bg-yellow-100 text-yellow-700'
                        }`}
                    >
                      {test.status?.replace('_', ' ') || 'Pending'}
                    </span>
                  </p>

                  {test.doctorProfile && (
                    <p className="text-gray-700 text-sm">
                      <span className="text-gray-500 font-medium">Doctor:</span>{' '}
                      {`${test.doctorProfile.firstName} ${test.doctorProfile.lastName}`}
                    </p>
                  )}

                  {test.labProfile && (
                    <p className="text-gray-700 text-sm">
                      <span className="text-gray-500 font-medium">Lab:</span>{' '}
                      {test.labProfile.labName}
                    </p>
                  )}

                  {test.resultFile ? (
                    <p className="text-sm">
                      <span className="text-gray-500 font-medium">Result File:</span>{' '}
                      <a
                        href={test.resultFile}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-600 hover:underline"
                      >
                        View Result
                      </a>
                    </p>
                  ) : (
                    <p className="text-sm text-gray-400 italic mt-1">No file uploaded</p>
                  )}
                </div>
              </div>

              <div>
                <p className="text-gray-600 font-medium mb-1">Tests Ordered:</p>
                <ul className="list-disc list-inside text-gray-800 text-sm space-y-2 ml-2">
                  {test.tests.map((t, i) => (
                    <li key={i}>
                      <span className="font-medium text-gray-700">Test Name:</span> {t.name || 'N/A'}
                      {t.reason && (
                        <>
                          {' '} - <span className="font-medium text-gray-700">Reason:</span>{' '}
                          <span className="text-gray-600">{t.reason}</span>
                        </>
                      )}
                    </li>
                  ))}
                </ul>
              </div>

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