'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
} from '@/components/ui/dialog';
import { X } from 'lucide-react';
import { authFetch } from '@/lib/api';
import { useAuthStore } from '@/stores/authStore';
import { toast } from '@/hooks/useToast';
import CreatableSelect from 'react-select/creatable';

const LAB_TEST_OPTIONS = {
  '🩸 Basic Hematology': [
    'Complete Blood Count (CBC)',
    'Blood Smear / Differential',
    'ESR (Erythrocyte Sedimentation Rate)',
    'Reticulocyte Count',
    'Coagulation Tests – PT, aPTT, INR, fibrinogen',
  ],
  '🧬 Clinical Chemistry & Metabolites': [
    'Electrolytes – sodium, potassium, chloride, bicarbonate',
    'Kidney Function – BUN, creatinine, eGFR',
    'Liver Panel – ALT, AST, ALP, GGT, bilirubin, albumin, total protein',
    'Lipid Profile – cholesterol, HDL, LDL, triglycerides',
    'Glucose Tests – fasting, post-prandial, HbA1c, OGTT',
    'Pancreatic Markers – amylase, lipase',
    'Thyroid Function – TSH, Free T3/T4, TPO antibodies',
  ],
  '💉 Infectious Disease & Serology': [
    'HIV – antigen/antibody, viral load',
    'Hepatitis Panel – A, B, C',
    'COVID-19 – PCR, antigen, antibody',
    'STIs – syphilis, chlamydia, gonorrhoea',
    'Malaria – smear, rapid antigen',
    'Dengue, CMV, EBV, Rubella, Measles, Mumps',
  ],
  '🦠 Microbiology & Cultures': [
    'Blood Culture',
    'Urine Culture & Sensitivity',
    'Throat/Nasopharyngeal Culture',
    'Wound/Tissue Culture',
    'Stool Culture & Parasite Exam',
  ],
  '🧬 Immunology & Autoimmune': [
    'ANA (Antinuclear Antibody)',
    'Rheumatoid Factor (RF)',
    'Anti-CCP',
    'Complement (C3, C4)',
    'Anti-dsDNA, Anti-Smith',
  ],
  '🔬 Tumor Markers & Oncology': [
    'PSA (Prostate)',
    'CA-125 (Ovarian)',
    'CA 19-9 (Pancreatic)',
    'CEA (Colon)',
    'AFP (Liver, Testicular)',
  ],
  '🧫 Genetic, Molecular & Cytogenetics': [
    'PCR / qPCR',
    'BRCA1/2',
    'Karyotyping, FISH',
    'Pharmacogenomics',
  ],
  '🧈 Endocrine & Hormonal Tests': [
    'Cortisol / ACTH',
    'Sex Hormones – estrogen, progesterone, testosterone',
    'FSH, LH, Prolactin',
    'PTH, Calcium, Vitamin D',
  ],
  '🫀 Cardiac & Coagulation Markers': [
    'Troponin I/T',
    'CK-MB',
    'BNP / NT-proBNP',
    'D-dimer',
    'Homocysteine',
  ],
  '🧂 Urinalysis & Body Fluids': [
    'Routine Urinalysis',
    'Microscopy – cells, casts, crystals',
    'Fluid Analysis – CSF, pleural, synovial',
  ],
  '🌡 Toxicology & Drug Monitoring': [
    'Therapeutic Drug Levels',
    'Drugs of Abuse Screens',
    'Blood Alcohol',
  ],
  '➕ Specialized Panels': [
    'Allergy Panels – food, seasonal',
    'Microbiome Sequencing',
    'Autoimmune Panels – IBD, vasculitis',
    'Prenatal Screening – AFP, hCG',
    'Nutritional Markers – iron, B12, folate',
  ],
};

export default function LabTestModal({ patientId, patientName, children }) {
  const user = useAuthStore((state) => state.user);
  const [tests, setTests] = useState([{ name: '', reason: '' }]);
  const [isOpen, setIsOpen] = useState(false);
  const [labs, setLabs] = useState([]);
  const [selectedLab, setSelectedLab] = useState('');

  useEffect(() => {
    if (isOpen) {
      authFetch('/api/labs')
        .then((res) => setLabs(res))
        .catch((err) => console.error('Failed to fetch labs', err));
    }
  }, [isOpen]);

  const addTest = () => setTests((prev) => [...prev, { name: '', reason: '' }]);

  const updateTest = (i, key, value) => {
    const updated = [...tests];
    updated[i][key] = value;
    setTests(updated);
  };

  const removeTest = (i) => setTests(tests.filter((_, index) => index !== i));

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await authFetch('/api/lab-tests', {
        method: 'POST',
        body: JSON.stringify({
          patientId,
          doctorId: user.id,
          labId: selectedLab,
          tests,
        }),
      });
      toast('Lab test suggested successfully');
      setTests([{ name: '', reason: '' }]);
      setSelectedLab('');
      setIsOpen(false);
    } catch (err) {
      alert('Error submitting lab test: ' + err.message);
    }
  };

  const allTestOptions = Object.entries(LAB_TEST_OPTIONS).flatMap(([category, tests]) =>
    tests.map((name) => ({ category, name }))
  );

  const selectOptions = allTestOptions.map((t) => ({
    label: `${t.name} (${t.category})`,
    value: t.name,
  }));

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className="sm:max-w-[700px] bg-gray-50">
        <DialogHeader>
          <DialogTitle>Suggest Lab Tests</DialogTitle>
          <DialogDescription>
            Select lab and suggest one or more lab tests for patient: {patientName}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label className="block text-sm font-medium mb-2">Select Lab</label>
            <select
              required
              value={selectedLab}
              onChange={(e) => setSelectedLab(e.target.value)}
              className="w-full p-2 border rounded"
            >
              <option value="" disabled>Select a lab...</option>
              {labs.map((lab) => (
                <option key={lab.id} value={lab.userId}>
                  {lab.labName} – {lab.address}
                  {lab.servicesOffered ? ` | Services: ${lab.servicesOffered}` : ''}
                  {lab.specializations ? ` | Specializations: ${lab.specializations}` : ''}
                </option>
              ))}
            </select>
          </div>

          {tests.map((test, index) => (
            <div key={index} className="grid grid-cols-12 gap-3 items-center mb-3">
              <div className="col-span-5">
                <CreatableSelect
                  isClearable
                  options={selectOptions}
                  placeholder="Select or type test..."
                  onChange={(selected) =>
                    updateTest(index, 'name', selected ? selected.value : '')
                  }
                  value={
                    test.name
                      ? { label: test.name, value: test.name }
                      : null
                  }
                />
              </div>

              <input
                className="col-span-6 p-2 border rounded"
                type="text"
                placeholder="Reason / Notes"
                value={test.reason}
                onChange={(e) => updateTest(index, 'reason', e.target.value)}
              />

              <button
                type="button"
                className="text-red-500 hover:text-red-700 col-span-1"
                onClick={() => removeTest(index)}
              >
                <X size={16} />
              </button>
            </div>
          ))}

          <Button type="button" variant="secondary" size="sm" onClick={addTest} className="mt-2">
            Add Lab Test
          </Button>

          <DialogFooter className="mt-4">
            <DialogClose asChild>
              <Button type="button" variant="outline">
                Cancel
              </Button>
            </DialogClose>
            <Button type="submit" className="cursor-pointer">
              Submit Request
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
