import { useRef, useState } from 'react';
import { Plus, Search, ChevronDown, CheckCircle2, AlertCircle, Check, TrendingUp, Calendar, Upload, X, Save, Trash2, FileText, Pencil } from 'lucide-react';
import { format, parseISO } from 'date-fns';
import { cn } from '../utils/helpers';
import { useNavigate } from 'react-router-dom';
import { useHealthStore } from '../store/useHealthStore';
import { uploadTestOCR, ingestTestJSON, deleteTestById, updateTestById, type APITest } from '../services/medical';
import { motion, AnimatePresence } from 'framer-motion';
import { DatePickerInput } from '../components/DatePickerInput';
import { useActivePatientId } from '../hooks/useActivePatientId';

interface LabResultDetail {
  id: string;
  processName: string;
  result: string;
  unit: string;
  referenceValue: string;
  status: 'normal' | 'high' | 'low';
}

interface LabResultGroup {
  id: string;
  date: string;
  hospital: string;
  summary: {
    normal: number;
    outOfReference?: number;
  };
  details?: {
    groupName: string;
    items: LabResultDetail[];
  }[];
}

interface TestDraftSubtest {
  name: string;
  value: number | null;
  unit: string;
  refMin: number | null;
  refMax: number | null;
}

interface TestDraft {
  testName: string;
  hospitalName: string;
  date: string;
  subtests: TestDraftSubtest[];
}

function createEmptySubtest(): TestDraftSubtest {
  return {
    name: '',
    value: null,
    unit: '',
    refMin: null,
    refMax: null,
  };
}

function createEmptyTestDraft(): TestDraft {
  return {
    testName: '',
    hospitalName: '',
    date: format(new Date(), 'yyyy-MM-dd'),
    subtests: [createEmptySubtest()],
  };
}

function parseOptionalNumber(value: string): number | null {
  const trimmed = value.trim();
  if (!trimmed) return null;

  const parsed = Number(trimmed);
  return Number.isFinite(parsed) ? parsed : null;
}

function isBlankDraftSubtest(subtest: TestDraftSubtest): boolean {
  return !subtest.name.trim()
    && subtest.value === null
    && !subtest.unit.trim()
    && subtest.refMin === null
    && subtest.refMax === null;
}

function normalizeDraftSubtest(subtest: TestDraftSubtest): TestDraftSubtest | null {
  if (isBlankDraftSubtest(subtest)) return null;
  if (!subtest.name.trim()) return null;

  return {
    ...subtest,
    name: subtest.name.trim(),
    unit: subtest.unit.trim(),
  };
}

function mergeOcrDraft(currentDraft: TestDraft, parsedData: any): TestDraft {
  const parsedSubtests = Array.isArray(parsedData?.subtests) ? parsedData.subtests : [];

  return {
    ...currentDraft,
    testName: (parsedData?.testName ?? parsedData?.name ?? currentDraft.testName ?? '').trim() || currentDraft.testName,
    hospitalName: (parsedData?.hospitalName ?? currentDraft.hospitalName ?? '').trim() || currentDraft.hospitalName,
    date: (parsedData?.date ?? currentDraft.date ?? '').toString().split('T')[0] || currentDraft.date,
    subtests: parsedSubtests.length > 0
      ? parsedSubtests.map((subtest: any) => ({
          name: String(subtest?.name ?? '').trim(),
          value: subtest?.value === '' || subtest?.value === undefined || subtest?.value === null
            ? null
            : Number(subtest.value),
          unit: String(subtest?.unit ?? '').trim(),
          refMin: subtest?.refMin === '' || subtest?.refMin === undefined || subtest?.refMin === null
            ? null
            : Number(subtest.refMin),
          refMax: subtest?.refMax === '' || subtest?.refMax === undefined || subtest?.refMax === null
            ? null
            : Number(subtest.refMax),
        }))
      : currentDraft.subtests,
  };
}

function mapTest(t: APITest): LabResultGroup {
  const subtests = t.subtests || [];
  let normalCount = 0;
  let outOfRefCount = 0;

  const items: LabResultDetail[] = subtests.map((st, idx) => {
    const val = st.value ?? 0;
    const min = st.refMin ?? 0;
    const max = st.refMax ?? Infinity;
    const isNormal = val >= min && val <= max;
    if (isNormal) normalCount++; else outOfRefCount++;

    return {
      id: `${t._id}-st${idx}`,
      processName: st.name,
      result: String(val),
      unit: st.unit || '',
      referenceValue: `${min}-${max === Infinity ? '∞' : max}`,
      status: isNormal ? 'normal' : (val > max ? 'high' : 'low'),
    };
  });

  return {
    id: t._id,
    date: (t.date || '').split('T')[0] || new Date().toISOString().split('T')[0],
    hospital: t.name || 'Lab Test',
    summary: {
      normal: normalCount,
      outOfReference: outOfRefCount > 0 ? outOfRefCount : undefined,
    },
    details: items.length > 0
      ? [{ groupName: t.name || t.testDescription || 'Results', items }]
      : undefined,
  };
}

/**
 * Component for uploading and reviewing test data
 */
function UploadTestModal({
  onClose,
  onUploadSuccess,
  activePatientId,
}: {
  onClose: () => void;
  onUploadSuccess: () => void;
  activePatientId: string | null;
}) {
  const [step, setStep] = useState<'processing' | 'review' | 'submitting'>('review');
  const [fileName, setFileName] = useState<string | null>(null);
  const [formData, setFormData] = useState<TestDraft>(() => createEmptyTestDraft());
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleOpenFilePicker = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files?.[0];
    if (!selected) return;

    setFileName(selected.name);
    e.target.value = '';
    setStep('processing');
    setError(null);

    try {
      const result = await uploadTestOCR(selected);
      setFormData((current) => mergeOcrDraft(current, result));
      setStep('review');
    } catch (err: any) {
      setError(err.message || 'OCR Failed');
      setStep('review');
    }
  };

  const handleUpdateSubtest = (index: number, field: keyof TestDraftSubtest, value: string | number | null) => {
    setFormData((current) => ({
      ...current,
      subtests: current.subtests.map((subtest, subtestIndex) => (
        subtestIndex === index ? { ...subtest, [field]: value } : subtest
      )),
    }));
  };

  const handleRemoveSubtest = (index: number) => {
    setFormData((current) => ({
      ...current,
      subtests: current.subtests.filter((_, subtestIndex) => subtestIndex !== index),
    }));
  };

  const handleAddSubtest = () => {
    setFormData((current) => ({
      ...current,
      subtests: [...current.subtests, createEmptySubtest()],
    }));
  };

  const handleSubmit = async () => {
    const normalizedTestName = formData.testName.trim();
    if (!normalizedTestName) {
      setError('Test name is required.');
      setStep('review');
      return;
    }

    const normalizedSubtests = formData.subtests
      .map(normalizeDraftSubtest)
      .filter((subtest): subtest is TestDraftSubtest => subtest !== null);

    setStep('submitting');
    setError(null);
    try {
      if (!activePatientId) {
        throw new Error('Missing patient ID. Please reload and try again.');
      }

      const payload = {
        testName: normalizedTestName,
        name: normalizedTestName,
        hospitalName: formData.hospitalName.trim(),
        date: formData.date,
        subtests: normalizedSubtests,
        patientId: activePatientId,
      };
      await ingestTestJSON(payload);
      onUploadSuccess();
      onClose();
    } catch (err: any) {
      setError(err.message || 'Submission Failed');
      setStep('review');
    }
  };

  const normalizedTestName = formData.testName.trim();
  const canSubmitUpload = step === 'review' && normalizedTestName.length > 0;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm"
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0, y: 20 }}
        animate={{ scale: 1, opacity: 1, y: 0 }}
        exit={{ scale: 0.95, opacity: 0, y: 20 }}
        className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden"
      >
        {/* Header */}
        <div className="px-6 py-4 border-b flex items-center justify-between bg-gray-50/50">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
              <Upload className="w-5 h-5" />
            </div>
            <div>
              <h2 className="font-bold text-gray-900">Create New Test</h2>
              <p className="text-xs text-gray-500">{fileName || 'Start empty or upload a PDF to prefill the draft'}</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <X className="w-5 h-5 text-gray-400" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {error && (
            <div className="mb-6 p-4 rounded-xl bg-red-50 border border-red-100 flex items-start gap-3 text-red-700">
              <AlertCircle className="w-5 h-5 shrink-0" />
              <div className="text-sm">{error}</div>
            </div>
          )}

          <div className="mb-6 rounded-2xl border border-dashed border-primary/20 bg-primary/5 p-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="font-semibold text-gray-900">Import from PDF</p>
            </div>
            <button
              onClick={handleOpenFilePicker}
              className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-xl bg-white border border-primary/20 text-primary font-bold shadow-sm hover:bg-primary/5 transition-colors"
            >
              <Upload className="w-4 h-4" />
              <span>Choose PDF</span>
            </button>
            <input
              ref={fileInputRef}
              type="file"
              accept=".pdf"
              onChange={handleFileChange}
              className="hidden"
            />
          </div>

          {step === 'processing' && (
            <div className="h-64 flex flex-col items-center justify-center space-y-4">
              <div className="relative">
                <div className="w-20 h-20 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
                <div className="absolute inset-0 flex items-center justify-center">
                  <FileText className="w-8 h-8 text-primary animate-pulse" />
                </div>
              </div>
              <div className="text-center">
                <p className="font-bold text-gray-900">Analyzing Document...</p>
                <p className="text-sm text-gray-500 mt-1">Extracting test results using OCR</p>
              </div>
            </div>
          )}

          {step === 'review' && (
            <div className="space-y-6">
              {/* General Info */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Test Name</label>
                  <input
                    type="text"
                    value={formData.testName}
                    onChange={(e) => setFormData({ ...formData, testName: e.target.value })}
                    placeholder="e.g. Complete Blood Count"
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 bg-gray-50 focus:ring-2 focus:ring-primary/20 transition-all font-medium text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Hospital Name</label>
                  <input
                    type="text"
                    value={formData.hospitalName}
                    onChange={(e) => setFormData({ ...formData, hospitalName: e.target.value })}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 bg-gray-50 focus:ring-2 focus:ring-primary/20 transition-all font-medium text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Test Date</label>
                  <DatePickerInput
                    value={formData.date}
                    onChange={(value) => setFormData({ ...formData, date: value })}
                    className="w-full rounded-xl bg-gray-50 px-4 py-2.5 font-medium text-sm"
                  />
                </div>
              </div>

              {/* Tables */}
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Extracted Results</label>
                  <button
                    onClick={handleAddSubtest}
                    className="text-xs font-bold text-primary flex items-center gap-1 hover:underline"
                  >
                    <Plus className="w-3.5 h-3.5" />
                    Add Item
                  </button>
                </div>
                <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
                  {formData.subtests.length === 0 ? (
                    <div className="p-6 text-center text-sm text-gray-500">
                      No subtests yet. Add one manually or upload a PDF to populate them.
                    </div>
                  ) : (
                    <table className="w-full text-left text-sm">
                      <thead>
                        <tr className="bg-gray-50 border-b border-gray-200 text-[10px] font-bold text-gray-500 uppercase tracking-wider">
                          <th className="px-4 py-3">Parameter</th>
                          <th className="px-4 py-3 w-24">Value</th>
                          <th className="px-4 py-3 w-20">Unit</th>
                          <th className="px-4 py-3 w-32">Ref Range</th>
                          <th className="px-4 py-3 w-10"></th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-100">
                        {formData.subtests.map((st, idx) => (
                          <tr key={idx} className="hover:bg-gray-50/50 transition-colors">
                            <td className="px-4 py-2">
                              <input
                                type="text"
                                value={st.name}
                                onChange={(e) => handleUpdateSubtest(idx, 'name', e.target.value)}
                                className="w-full bg-transparent focus:bg-white px-2 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-sm font-medium"
                              />
                            </td>
                            <td className="px-4 py-2">
                              <input
                                type="number"
                                value={st.value ?? ''}
                                onChange={(e) => handleUpdateSubtest(idx, 'value', parseOptionalNumber(e.target.value))}
                                className="w-full bg-transparent focus:bg-white px-2 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-sm font-bold text-primary"
                              />
                            </td>
                            <td className="px-4 py-2">
                              <input
                                type="text"
                                value={st.unit}
                                onChange={(e) => handleUpdateSubtest(idx, 'unit', e.target.value)}
                                className="w-full bg-transparent focus:bg-white px-2 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-xs text-gray-500"
                              />
                            </td>
                            <td className="px-4 py-2 flex items-center gap-1">
                              <input
                                type="number"
                                placeholder="Min"
                                value={st.refMin ?? ''}
                                onChange={(e) => handleUpdateSubtest(idx, 'refMin', parseOptionalNumber(e.target.value))}
                                className="w-14 bg-transparent focus:bg-white px-1 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-xs text-gray-400 text-center"
                              />
                              <span className="text-gray-300">-</span>
                              <input
                                type="number"
                                placeholder="Max"
                                value={st.refMax ?? ''}
                                onChange={(e) => handleUpdateSubtest(idx, 'refMax', parseOptionalNumber(e.target.value))}
                                className="w-14 bg-transparent focus:bg-white px-1 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-xs text-gray-400 text-center"
                              />
                            </td>
                            <td className="px-4 py-2 text-right">
                              <button
                                onClick={() => handleRemoveSubtest(idx)}
                                className="p-1.5 text-gray-300 hover:text-red-500 transition-colors"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              </div>
            </div>
          )}

          {step === 'submitting' && (
            <div className="h-64 flex flex-col items-center justify-center space-y-4">
              <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
              <p className="font-bold text-gray-900">Saving Records...</p>
            </div>
          )}
        </div>

        {/* Footer Actions */}
        <div className="px-6 py-4 border-t bg-gray-50/50 flex items-center justify-between">
          <button
            onClick={onClose}
            className="px-6 py-2 rounded-xl text-sm font-bold text-gray-500 hover:bg-gray-100 transition-all"
          >
            Cancel
          </button>
          {step === 'review' && (
            <div title={canSubmitUpload ? 'Confirm and upload this test' : 'Enter a test name to enable upload'}>
              <button
                onClick={handleSubmit}
                disabled={!canSubmitUpload}
                className={cn(
                  'px-8 py-2.5 rounded-xl text-sm font-bold transition-all flex items-center gap-2',
                  canSubmitUpload
                    ? 'bg-primary text-white shadow-lg shadow-primary/25 hover:-translate-y-0.5'
                    : 'bg-gray-200 text-gray-400 cursor-not-allowed'
                )}
              >
                <Save className="w-4 h-4" />
                Confirm & Upload
              </button>
            </div>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}

function EditTestModal({
  test,
  onClose,
  onSaveSuccess,
}: {
  test: APITest;
  onClose: () => void;
  onSaveSuccess: () => void;
}) {
  const [step, setStep] = useState<'review' | 'submitting'>('review');
  const [error, setError] = useState<string | null>(null);
  const [formData, setFormData] = useState<any>({
    name: test.name || '',
    date: test.date ? test.date.split('T')[0] : '',
    subtests: (test.subtests || []).map((st) => ({
      name: st.name || '',
      value: st.value,
      unit: st.unit || '',
      refMin: st.refMin,
      refMax: st.refMax,
    })),
  });

  const handleUpdateSubtest = (index: number, field: string, value: any) => {
    const next = { ...formData };
    next.subtests[index][field] = value;
    setFormData(next);
  };

  const handleRemoveSubtest = (index: number) => {
    const next = { ...formData };
    next.subtests.splice(index, 1);
    setFormData(next);
  };

  const handleAddSubtest = () => {
    const next = { ...formData };
    if (!next.subtests) next.subtests = [];
    next.subtests.push({
      name: 'New Test',
      value: 0,
      unit: '',
      refMin: 0,
      refMax: 100,
    });
    setFormData(next);
  };

  const handleSubmit = async () => {
    const normalizedName = (formData?.name || '').trim();
    if (!normalizedName) {
      setError('Test name is required.');
      return;
    }

    setStep('submitting');
    setError(null);
    try {
      await updateTestById(test._id, {
        name: normalizedName,
        date: formData.date,
        subtests: formData.subtests,
      });
      onSaveSuccess();
      onClose();
    } catch (err: any) {
      setError(err?.message || 'Update failed. Please try again.');
      setStep('review');
    }
  };

  const canSubmit = (formData?.name || '').trim().length > 0;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm"
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0, y: 20 }}
        animate={{ scale: 1, opacity: 1, y: 0 }}
        exit={{ scale: 0.95, opacity: 0, y: 20 }}
        className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden"
      >
        <div className="px-6 py-4 border-b flex items-center justify-between bg-gray-50/50">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
              <Pencil className="w-5 h-5" />
            </div>
            <div>
              <h2 className="font-bold text-gray-900">Edit Test</h2>
              <p className="text-xs text-gray-500">Update test details and values</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <X className="w-5 h-5 text-gray-400" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-6">
          {error && (
            <div className="mb-6 p-4 rounded-xl bg-red-50 border border-red-100 flex items-start gap-3 text-red-700">
              <AlertCircle className="w-5 h-5 shrink-0" />
              <div className="text-sm">{error}</div>
            </div>
          )}

          {step === 'review' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Test Name</label>
                  <input
                    type="text"
                    value={formData.name || ''}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 bg-gray-50 focus:ring-2 focus:ring-primary/20 transition-all font-medium text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Test Date</label>
                  <DatePickerInput
                    value={formData.date || ''}
                    onChange={(value) => setFormData({ ...formData, date: value })}
                    className="w-full rounded-xl bg-gray-50 px-4 py-2.5 font-medium text-sm"
                  />
                </div>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Results</label>
                  <button
                    onClick={handleAddSubtest}
                    className="text-xs font-bold text-primary flex items-center gap-1 hover:underline"
                  >
                    <Plus className="w-3.5 h-3.5" />
                    Add Item
                  </button>
                </div>
                <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
                  <table className="w-full text-left text-sm">
                    <thead>
                      <tr className="bg-gray-50 border-b border-gray-200 text-[10px] font-bold text-gray-500 uppercase tracking-wider">
                        <th className="px-4 py-3">Parameter</th>
                        <th className="px-4 py-3 w-24">Value</th>
                        <th className="px-4 py-3 w-20">Unit</th>
                        <th className="px-4 py-3 w-32">Ref Range</th>
                        <th className="px-4 py-3 w-10"></th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {formData.subtests.map((st: any, idx: number) => (
                        <tr key={idx} className="hover:bg-gray-50/50 transition-colors">
                          <td className="px-4 py-2">
                            <input
                              type="text"
                              value={st.name || ''}
                              onChange={(e) => handleUpdateSubtest(idx, 'name', e.target.value)}
                              className="w-full bg-transparent focus:bg-white px-2 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-sm font-medium"
                            />
                          </td>
                          <td className="px-4 py-2">
                            <input
                              type="number"
                              value={st.value ?? ''}
                              onChange={(e) => handleUpdateSubtest(idx, 'value', parseFloat(e.target.value))}
                              className="w-full bg-transparent focus:bg-white px-2 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-sm font-bold text-primary"
                            />
                          </td>
                          <td className="px-4 py-2">
                            <input
                              type="text"
                              value={st.unit || ''}
                              onChange={(e) => handleUpdateSubtest(idx, 'unit', e.target.value)}
                              className="w-full bg-transparent focus:bg-white px-2 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-xs text-gray-500"
                            />
                          </td>
                          <td className="px-4 py-2 flex items-center gap-1">
                            <input
                              type="number"
                              placeholder="Min"
                              value={st.refMin ?? ''}
                              onChange={(e) => handleUpdateSubtest(idx, 'refMin', parseFloat(e.target.value))}
                              className="w-14 bg-transparent focus:bg-white px-1 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-xs text-gray-400 text-center"
                            />
                            <span className="text-gray-300">-</span>
                            <input
                              type="number"
                              placeholder="Max"
                              value={st.refMax ?? ''}
                              onChange={(e) => handleUpdateSubtest(idx, 'refMax', parseFloat(e.target.value))}
                              className="w-14 bg-transparent focus:bg-white px-1 py-1 rounded border-transparent focus:border-gray-200 focus:ring-0 text-xs text-gray-400 text-center"
                            />
                          </td>
                          <td className="px-4 py-2 text-right">
                            <button
                              onClick={() => handleRemoveSubtest(idx)}
                              className="p-1.5 text-gray-300 hover:text-red-500 transition-colors"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {step === 'submitting' && (
            <div className="h-64 flex flex-col items-center justify-center space-y-4">
              <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
              <p className="font-bold text-gray-900">Updating Test...</p>
            </div>
          )}
        </div>

        <div className="px-6 py-4 border-t bg-gray-50/50 flex items-center justify-between">
          <button
            onClick={onClose}
            className="px-6 py-2 rounded-xl text-sm font-bold text-gray-500 hover:bg-gray-100 transition-all"
          >
            Cancel
          </button>
          {step === 'review' && (
            <button
              onClick={handleSubmit}
              disabled={!canSubmit}
              className={cn(
                'px-8 py-2.5 rounded-xl text-sm font-bold transition-all flex items-center gap-2',
                canSubmit
                  ? 'bg-primary text-white shadow-lg shadow-primary/25 hover:-translate-y-0.5'
                  : 'bg-gray-200 text-gray-400 cursor-not-allowed'
              )}
            >
              <Save className="w-4 h-4" />
              Save Changes
            </button>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}

export function TestsPage() {
  const [filter, setFilter] = useState<'all' | 'normal' | 'unusual' | 'outOfRange'>('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [expandedIds, setExpandedIds] = useState<string[]>([]);
  const rawTests = useHealthStore((s) => s._rawTests);
  const loadedUserId = useHealthStore((s) => s._loadedUserId);
  const loadUserData = useHealthStore((s) => s.loadUserData);
  const labResults = rawTests.map(mapTest);
  const loading = loadedUserId === null;
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [editingTestId, setEditingTestId] = useState<string | null>(null);
  const [deletingTestId, setDeletingTestId] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);
  const navigate = useNavigate();
  const activePatientId = useActivePatientId();
  const editingTest = rawTests.find((t) => t._id === editingTestId) || null;

  const effectiveStartDate = startDate && endDate && startDate > endDate ? endDate : startDate;
  const effectiveEndDate = startDate && endDate && startDate > endDate ? startDate : endDate;
  const parsedEffectiveStartDate = effectiveStartDate ? parseISO(effectiveStartDate) : undefined;
  const parsedEffectiveEndDate = effectiveEndDate ? parseISO(effectiveEndDate) : undefined;

  const loadTests = () => {
    if (activePatientId) loadUserData(activePatientId, true);
  };

  const filteredResults = labResults
    .filter((group) => {
      const normalizedSearchTerm = searchTerm.trim().toLowerCase();
      const groupProcessNames = group.details
        ?.flatMap((detailGroup) => detailGroup.items)
        .map((item) => item.processName.toLowerCase()) ?? [];

      const matchesSearch = !normalizedSearchTerm
        || group.hospital.toLowerCase().includes(normalizedSearchTerm)
        || groupProcessNames.some((name) => name.includes(normalizedSearchTerm));

      const isAfterStart = !effectiveStartDate || group.date >= effectiveStartDate;
      const isBeforeEnd = !effectiveEndDate || group.date <= effectiveEndDate;

      return matchesSearch && isAfterStart && isBeforeEnd;
    })
    .map((group) => {
      if (filter !== 'outOfRange') return group;

      const filteredDetails = group.details
        ?.map((detailGroup) => ({
          ...detailGroup,
          items: detailGroup.items.filter((item) => item.status !== 'normal'),
        }))
        .filter((detailGroup) => detailGroup.items.length > 0);

      const outOfReferenceCount = filteredDetails
        ? filteredDetails.reduce((sum, detailGroup) => sum + detailGroup.items.length, 0)
        : 0;

      if (!filteredDetails || outOfReferenceCount === 0) return null;

      return {
        ...group,
        details: filteredDetails,
        summary: {
          normal: 0,
          outOfReference: outOfReferenceCount,
        },
      };
    })
    .filter((group): group is LabResultGroup => {
      if (!group) return false;

      if (filter === 'normal') return !group.summary.outOfReference;
      if (filter === 'unusual') return (group.summary.outOfReference || 0) > 0;

      return true;
    });

  const filteredResultIds = filteredResults.map((group) => group.id);
  const hasFilteredResults = filteredResultIds.length > 0;
  const allFilteredExpanded = hasFilteredResults
    && filteredResultIds.every((id) => expandedIds.includes(id));
  const anyFilteredExpanded = filteredResultIds.some((id) => expandedIds.includes(id));

  const toggleExpand = (id: string) => {
    setExpandedIds((current) => (
      current.includes(id)
        ? current.filter((expandedId) => expandedId !== id)
        : [...current, id]
    ));
  };

  const handleExpandAll = () => {
    if (!hasFilteredResults) return;

    setExpandedIds((current) => Array.from(new Set([...current, ...filteredResultIds])));
  };

  const handleCollapseAll = () => {
    if (!hasFilteredResults) return;

    setExpandedIds((current) => current.filter((id) => !filteredResultIds.includes(id)));
  };

  const handleTrendClick = (metricName: string) => {
    navigate('/plots', { state: { selectedMetric: metricName } });
  };

  const handleTimelineClick = (date: string) => {
    navigate('/timeline', { state: { focusDate: date } });
  };

  const handleDeleteTest = async (testId: string, testName: string) => {
    if (deletingTestId) return;

    const confirmed = window.confirm(`Delete test "${testName}"? This action cannot be undone.`);
    if (!confirmed) return;

    setDeletingTestId(testId);
    setActionError(null);
    try {
      await deleteTestById(testId);
      setExpandedIds((current) => current.filter((id) => id !== testId));
      loadTests();
    } catch (err: any) {
      setActionError(err?.message || 'Failed to delete test. Please try again.');
    } finally {
      setDeletingTestId(null);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-32">
        <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
      </div>
    );
  }

  return (
    <div className="pb-20">
      <div className="mb-6 flex flex-col gap-4">
        <div className="flex flex-col xl:flex-row xl:items-end xl:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-gray-900">My Lab Tests</h1>
          <p className="text-gray-500 text-sm mt-1">View existing lab results or upload your own, conduct detailed analyses</p>
        </div>

          <div className="w-full xl:w-auto flex flex-col sm:flex-row sm:flex-wrap gap-3">
            <div className="space-y-1 sm:w-72">
              <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">Search</label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
                <input
                  type="text"
                  placeholder="Search test or subtest name..."
                  className="pl-10 pr-4 py-2 w-full bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>
            <div className="space-y-1 sm:w-40">
              <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">From Date</label>
              <DatePickerInput
                value={startDate}
                onChange={setStartDate}
                toDate={parsedEffectiveEndDate}
                className="w-full rounded-lg bg-white px-4 py-2 text-sm"
              />
            </div>
            <div className="space-y-1 sm:w-40">
              <label className="text-xs font-bold text-gray-500 uppercase tracking-wider ml-1">To Date</label>
              <DatePickerInput
                value={endDate}
                onChange={setEndDate}
                fromDate={parsedEffectiveStartDate}
                className="w-full rounded-lg bg-white px-4 py-2 text-sm"
              />
            </div>
          <button
            onClick={() => setIsUploadModalOpen(true)}
              className="h-[42px] self-end flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-bold shadow-lg shadow-primary/25 hover:-translate-y-0.5 active:translate-y-0 transition-all"
          >
            <Plus className="w-4 h-4" />
            <span>Upload Test</span>
          </button>
          </div>
        </div>
        {startDate && endDate && startDate > endDate && (
          <p className="text-xs text-amber-700">
            Date range was auto-corrected because the start date is after the end date.
          </p>
        )}
      </div>

      <div className="flex gap-2 mb-2 overflow-x-auto pb-2">
        <button
          onClick={() => setFilter('all')}
          className={cn("px-4 py-1.5 rounded-full text-xs font-medium transition-all", filter === 'all' ? "bg-primary text-white" : "bg-white border border-gray-200 text-gray-600 hover:bg-gray-50")}
        >
          All Results
        </button>
        <button
          onClick={() => setFilter('normal')}
          className={cn("px-4 py-1.5 rounded-full text-xs font-medium transition-all", filter === 'normal' ? "bg-green-600 text-white" : "bg-white border border-gray-200 text-gray-600 hover:bg-gray-50")}
        >
          Normal Results
        </button>
        <button
          onClick={() => setFilter('unusual')}
          className={cn("px-4 py-1.5 rounded-full text-xs font-medium transition-all", filter === 'unusual' ? "bg-red-600 text-white" : "bg-white border border-gray-200 text-gray-600 hover:bg-gray-50")}
        >
          Unusual Results
        </button>
        <button
          onClick={() => setFilter('outOfRange')}
          className={cn("px-4 py-1.5 rounded-full text-xs font-medium transition-all", filter === 'outOfRange' ? "bg-red-700 text-white" : "bg-white border border-gray-200 text-gray-600 hover:bg-gray-50")}
        >
          Only Out-of-Range
        </button>
      </div>

      <div className="flex gap-2 mb-4">
        <button
          onClick={handleExpandAll}
          disabled={!hasFilteredResults || allFilteredExpanded}
          className={cn(
            'px-3 py-1.5 rounded-lg text-xs font-medium transition-all border',
            !hasFilteredResults || allFilteredExpanded
              ? 'bg-gray-100 border-gray-200 text-gray-400 cursor-not-allowed'
              : 'bg-white border-gray-200 text-gray-700 hover:bg-gray-50'
          )}
        >
          Expand All Tests
        </button>
        <button
          onClick={handleCollapseAll}
          disabled={!anyFilteredExpanded}
          className={cn(
            'px-3 py-1.5 rounded-lg text-xs font-medium transition-all border',
            !anyFilteredExpanded
              ? 'bg-gray-100 border-gray-200 text-gray-400 cursor-not-allowed'
              : 'bg-white border-gray-200 text-gray-700 hover:bg-gray-50'
          )}
        >
          Collapse All Tests
        </button>
      </div>

      <div className="space-y-4">
        {actionError && (
          <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
            {actionError}
          </div>
        )}
        {filteredResults.map((group) => {
          const dateObj = parseISO(group.date);
          const isExpanded = expandedIds.includes(group.id);
          const isDeleting = deletingTestId === group.id;

          return (
            <div key={group.id} className={`card p-0 overflow-hidden transition-all duration-300 ${isExpanded ? 'ring-2 ring-primary/20 shadow-md' : 'hover:shadow-md'}`}>
              <div
                className="flex items-stretch cursor-pointer"
                onClick={() => toggleExpand(group.id)}
              >
                {/* Date Box */}
                <div className="bg-primary text-white w-20 flex flex-col items-center justify-center p-2 shrink-0">
                  <span className="text-2xl font-bold leading-none">{format(dateObj, 'd')}</span>
                  <span className="text-[10px] uppercase font-medium mt-1">{format(dateObj, 'MMM yyyy')}</span>
                </div>

                <div className="flex-1 p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                  <div>
                    <h3 className="font-bold text-gray-900 text-sm mb-2">{group.hospital}</h3>
                    <div className="flex flex-wrap gap-4 text-xs">
                      {group.summary.normal > 0 && (
                        <div className="flex items-center gap-1.5 text-green-700 bg-green-50 px-2 py-1 rounded-md">
                          <CheckCircle2 className="w-3.5 h-3.5" />
                          <span className="font-medium">{group.summary.normal} Normal</span>
                        </div>
                      )}
                      {group.summary.outOfReference && (
                        <div className="flex items-center gap-1.5 text-red-700 bg-red-50 px-2 py-1 rounded-md">
                          <AlertCircle className="w-3.5 h-3.5" />
                          <span className="font-medium">{group.summary.outOfReference} Out of Reference Range</span>
                        </div>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center gap-3 w-full sm:w-auto">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setActionError(null);
                        setEditingTestId(group.id);
                      }}
                      title="Edit test"
                      className="p-2 rounded-full text-gray-400 hover:text-primary hover:bg-primary/10 transition-colors"
                    >
                      <Pencil className="w-4 h-4" />
                    </button>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDeleteTest(group.id, group.hospital);
                      }}
                      disabled={isDeleting}
                      title="Delete test"
                      className={cn(
                        'p-2 rounded-full transition-colors',
                        isDeleting
                          ? 'text-red-300 bg-red-50 cursor-not-allowed'
                          : 'text-gray-400 hover:text-red-600 hover:bg-red-50'
                      )}
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                    <button className={`p-2 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100 transition-transform duration-300 ${isExpanded ? 'rotate-180' : ''}`}>
                      <ChevronDown className="w-5 h-5" />
                    </button>
                  </div>
                </div>
              </div>

              {/* Detailed View */}
              {isExpanded && group.details && (
                <div className="border-t border-gray-100 bg-gray-50/50 animate-in slide-in-from-top-2 duration-300">
                  {group.details.map((detailGroup, idx) => (
                    <div key={idx} className="p-4 sm:p-6">
                      <div className="flex justify-between items-center mb-4 bg-gray-200/50 p-2 rounded-lg">
                        <div className="flex items-center gap-2">
                          <CheckCircle2 className="w-4 h-4 text-gray-500" />
                          <h4 className="font-semibold text-gray-700 text-sm">{detailGroup.groupName}</h4>
                        </div>
                      </div>

                      <div className="bg-white rounded-lg border border-gray-100 overflow-hidden shadow-sm">
                        {/* Table Header - Hidden on mobile, shown on desktop */}
                        <div className="hidden sm:grid grid-cols-12 gap-4 px-4 py-3 bg-gray-50 border-b border-gray-100 text-[10px] font-bold text-gray-500 uppercase tracking-wider">
                          <div className="col-span-4">Process Name</div>
                          <div className="col-span-2">Result</div>
                          <div className="col-span-2">Reference Range</div>
                          <div className="col-span-2">Unit</div>
                          <div className="col-span-2 text-right">Actions</div>
                        </div>

                        <div className="divide-y divide-gray-50">
                          {detailGroup.items.map((item) => (
                            <div key={item.id} className="grid grid-cols-1 sm:grid-cols-12 gap-2 sm:gap-4 px-4 py-3 hover:bg-blue-50/30 transition-colors items-center group/row">
                              <div className="col-span-4 font-medium text-sm text-gray-800 flex items-center gap-2">
                                <span className="sm:hidden text-xs text-gray-400 font-normal w-24">Process:</span>
                                {item.processName}
                              </div>
                              <div className="col-span-2 text-sm text-gray-900 font-semibold">
                                <span className="sm:hidden text-xs text-gray-400 font-normal w-24 inline-block">Result:</span>
                                {item.result}
                              </div>
                              <div className="col-span-2 text-xs text-gray-500">
                                <span className="sm:hidden text-xs text-gray-400 font-normal w-24 inline-block">Ref:</span>
                                {item.referenceValue}
                              </div>
                              <div className="col-span-2 text-xs text-gray-500">
                                <span className="sm:hidden text-xs text-gray-400 font-normal w-24 inline-block">Unit:</span>
                                {item.unit}
                              </div>
                              <div className="col-span-2 flex items-center justify-end gap-2">
                                {/* Status Icon */}
                                <div className={`w-6 h-6 rounded flex items-center justify-center ${item.status === 'normal' ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'}`}>
                                  {item.status === 'normal' ? <Check className="w-3.5 h-3.5" /> : <AlertCircle className="w-3.5 h-3.5" />}
                                </div>

                                {/* Action Buttons (Graph/Timeline) */}
                                <div className="flex gap-1">
                                  <button
                                    onClick={() => handleTrendClick(item.processName)}
                                    className="p-1.5 bg-blue-100 text-blue-600 rounded hover:bg-blue-200"
                                    title="View Trend Plot"
                                  >
                                    <TrendingUp className="w-3.5 h-3.5" />
                                  </button>
                                  <button
                                    onClick={() => handleTimelineClick(group.date)}
                                    className="p-1.5 bg-purple-100 text-purple-600 rounded hover:bg-purple-200"
                                    title="View in Timeline"
                                  >
                                    <Calendar className="w-3.5 h-3.5" />
                                  </button>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  ))}

                  {!group.details && (
                    <div className="p-8 text-center text-gray-500 text-sm">
                      Detailed results not available for this record.
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
        {filteredResults.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            No results found matching your criteria.
          </div>
        )}
      </div>

      <AnimatePresence>
        {editingTest && (
          <EditTestModal
            test={editingTest}
            onClose={() => setEditingTestId(null)}
            onSaveSuccess={loadTests}
          />
        )}
        {isUploadModalOpen && (
          <UploadTestModal
            onClose={() => setIsUploadModalOpen(false)}
            onUploadSuccess={loadTests}
            activePatientId={activePatientId}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
