import React, { useState } from 'react'
import dayjs from 'dayjs'
import {
  Calendar,
  User,
  ChevronDown,
  FlaskConical,
  Pill,
  Radiation,
  Activity,
  ClipboardList,
} from 'lucide-react'

type Props = {
  consultations: any[] | undefined
}

const fmtDate = (d?: string | null) => (d ? dayjs(d).format('MMM D, YYYY') : '—')
const fmtTime = (d?: string | null) => (d ? dayjs(d).format('hh:mm A') : '')

/** Map a lab/radiology `completed` flag (submit_final: 0/1/2) to a label + dot colour. */
const testStatus = (t: any): { label: string; color: string } => {
  if (t.completed === 2) return { label: 'Finalized', color: '#16a34a' }
  if (t.completed === 1) return { label: 'Completed', color: '#2563eb' }
  if (t.test_result) return { label: 'In Progress', color: '#f59e0b' }
  return { label: 'Pending', color: '#9ca3af' }
}

const VitalCard: React.FC<{ label: string; value: string; tone: string }> = ({ label, value, tone }) => (
  <div className={`rounded-lg p-3 ${tone}`}>
    <div className="text-[11px] font-semibold tracking-wide text-gray-500 uppercase">{label}</div>
    <div className="text-base font-bold mt-1">{value}</div>
  </div>
)

const SectionHeading: React.FC<{ icon: React.ReactNode; title: string; count?: number }> = ({
  icon,
  title,
  count,
}) => (
  <div className="flex items-center gap-2 mb-2">
    <span className="text-[#0061FF]">{icon}</span>
    <span className="text-sm font-semibold text-[#111827]">{title}</span>
    {typeof count === 'number' && <span className="text-sm text-gray-400">({count})</span>}
  </div>
)

const Note: React.FC<{ label: string; value?: string | null }> = ({ label, value }) => {
  if (!value || value === 'N/A' || `${value}`.trim() === '') return null
  return (
    <div>
      <div className="text-[12px] font-semibold text-[#0061FF] mb-1">{label}</div>
      <div className="rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm whitespace-pre-wrap text-[#111827]">
        {value}
      </div>
    </div>
  )
}

const EncounterCard: React.FC<{ c: any; open: boolean; onToggle: () => void }> = ({ c, open, onToggle }) => {
  const [openResult, setOpenResult] = useState<Record<string, boolean>>({})

  const labs = c.lab_tests || []
  const radiology = c.radiology_tests || []
  const meds = c.pharmacy_medications || []
  const procedures = c.procedures || []
  const vitals = c.vitals || {}

  const preview =
    c.patient_complaint || c.doctor_comment || c.diagnosis || c.doctor_examination || ''

  const vitalItems = [
    { label: 'Blood Pressure', value: vitals.blood_pressure, tone: 'bg-blue-50 text-blue-700' },
    { label: 'Pulse Rate', value: vitals.pulse_rate ? `${vitals.pulse_rate} bpm` : '', tone: 'bg-green-50 text-green-700' },
    { label: 'Temperature', value: vitals.temperature ? `${vitals.temperature}°C` : '', tone: 'bg-red-50 text-red-700' },
    { label: 'Oxygen Level', value: vitals.oxygen_level ? `${vitals.oxygen_level}%` : '', tone: 'bg-purple-50 text-purple-700' },
    { label: 'Weight', value: vitals.weight ? `${vitals.weight} kg` : '', tone: 'bg-teal-50 text-teal-700' },
    { label: 'Height', value: vitals.height ? `${vitals.height} cm` : '', tone: 'bg-indigo-50 text-indigo-700' },
    { label: 'Random Blood Sugar', value: vitals.blood_sugar_rbs ? `${vitals.blood_sugar_rbs} mg/dL` : '', tone: 'bg-orange-50 text-orange-700' },
    { label: 'Fasting Blood Sugar', value: vitals.blood_sugar_fbs ? `${vitals.blood_sugar_fbs} mg/dL` : '', tone: 'bg-pink-50 text-pink-700' },
  ].filter((v) => v.value && `${v.value}`.trim() !== '')

  const hasNotes =
    c.patient_complaint || c.patient_complaint_history || c.doctor_examination ||
    c.diagnosis || c.doctor_diagnosis || c.treatment_plan || c.treatment ||
    c.doctor_comment || c.nurse_comment

  return (
    <div className="relative pl-6">
      {/* timeline dot */}
      <span className="absolute left-0 top-4 w-2.5 h-2.5 rounded-full bg-[#0061FF] ring-4 ring-blue-100" />

      <div className="rounded-xl border border-gray-200 mb-4 overflow-hidden">
        {/* Collapsed header */}
        <button
          type="button"
          onClick={onToggle}
          className="w-full text-left px-4 py-3 hover:bg-gray-50 transition-colors flex items-start justify-between gap-3"
        >
          <div className="min-w-0">
            <div className="flex flex-wrap items-center gap-2">
              <Calendar size={15} className="text-gray-400" />
              <span className="text-sm font-semibold text-[#111827]">{fmtDate(c.consultation_date)}</span>
              <span className="text-xs text-gray-400">{fmtTime(c.consultation_date)}</span>
              {c.name && (
                <span className="text-[11px] font-medium text-[#0061FF] bg-blue-50 rounded-full px-2 py-0.5">
                  {c.name}
                </span>
              )}
            </div>
            <div className="flex items-center gap-1.5 mt-1 text-sm text-gray-600">
              <User size={14} className="text-gray-400" />
              {c.doctor_name || 'N/A'}
            </div>
            {preview && !open && (
              <div className="text-sm text-gray-500 italic mt-1 truncate max-w-[46ch]">{preview}</div>
            )}
          </div>

          <div className="flex items-center gap-2 shrink-0">
            {procedures.length > 0 && <ClipboardList size={16} className="text-blue-500" />}
            {meds.length > 0 && <Pill size={16} className="text-purple-500" />}
            {labs.length > 0 && <FlaskConical size={16} className="text-green-600" />}
            {radiology.length > 0 && <Radiation size={16} className="text-orange-500" />}
            <ChevronDown
              size={18}
              className={`text-gray-400 transition-transform ${open ? 'rotate-180' : ''}`}
            />
          </div>
        </button>

        {/* Expanded body */}
        {open && (
          <div className="border-t border-gray-100 px-4 py-4 space-y-5">
            {/* Vitals */}
            {vitalItems.length > 0 && (
              <div>
                <SectionHeading icon={<Activity size={16} />} title="Vital Documentation" />
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2">
                  {vitalItems.map((v) => (
                    <VitalCard key={v.label} label={v.label} value={`${v.value}`} tone={v.tone} />
                  ))}
                </div>
              </div>
            )}

            {/* Scheduled Procedures */}
            {procedures.length > 0 && (
              <div>
                <SectionHeading icon={<ClipboardList size={16} />} title="Scheduled Procedures" count={procedures.length} />
                <div className="space-y-2">
                  {procedures.map((p: any, idx: number) => (
                    <div
                      key={p.billItemId ?? idx}
                      className="rounded-lg bg-[#F0F6FF] border border-blue-100 p-3 flex flex-wrap items-center justify-between gap-2"
                    >
                      <div className="min-w-0">
                        <div className="text-sm font-semibold text-[#111827]">{p.name || 'Procedure'}</div>
                        {(p.quantity != null) && (
                          <div className="text-xs text-gray-500 mt-0.5">Qty: {p.quantity}</div>
                        )}
                      </div>
                      <span
                        className={`text-xs font-medium ${
                          p.paid ? 'text-green-600' : 'text-gray-500'
                        }`}
                      >
                        {p.paid ? 'Paid' : 'Unpaid'}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Prescriptions (Pharmacy) */}
            {meds.length > 0 && (
              <div>
                <SectionHeading icon={<Pill size={16} />} title="Prescriptions" count={meds.length} />
                <div className="space-y-2">
                  {meds.map((m: any) => (
                    <div
                      key={m.id}
                      className="rounded-lg bg-[#FAF7FE] border border-purple-100 p-3 flex flex-wrap items-start justify-between gap-2"
                    >
                      <div className="min-w-0">
                        <div className="text-sm font-semibold text-[#111827]">
                          {m.medication_name || 'Unknown'}
                        </div>
                        <div className="text-xs text-gray-500 mt-0.5">
                          {[
                            m.dosage != null && `Dosage: ${m.dosage}`,
                            m.daily_frequency != null && `Freq: ${m.daily_frequency}x daily`,
                            m.administration_mode && `Route: ${m.administration_mode}`,
                            (m.start_date || m.end_date) && `Duration: ${m.start_date || '—'} – ${m.end_date || '—'}`,
                          ]
                            .filter(Boolean)
                            .join('   ')}
                        </div>
                      </div>
                      <span
                        className={`text-xs font-medium ${
                          m.dispensed === 1 ? 'text-green-600' : 'text-gray-500'
                        }`}
                      >
                        {m.dispensed === 1 ? 'Dispensed' : 'Pending Dispense'}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Laboratory investigations */}
            {labs.length > 0 && (
              <div>
                <SectionHeading icon={<FlaskConical size={16} />} title="Laboratory Investigations" count={labs.length} />
                <div className="space-y-2">
                  {labs.map((t: any) => {
                    const st = testStatus(t)
                    const resultOpen = !!openResult[`lab-${t.id}`]
                    return (
                      <div key={t.id} className="rounded-lg bg-[#F6FBF7] border border-green-100 p-3">
                        <div className="flex flex-wrap items-center justify-between gap-2">
                          <div className="min-w-0">
                            <div className="text-sm font-semibold text-[#111827]">{t.test_name || 'Unnamed Test'}</div>
                            <div className="text-xs text-gray-400">{fmtDate(t.ordered_date)}</div>
                          </div>
                          <div className="flex items-center gap-3">
                            <span className="flex items-center gap-1.5 text-xs">
                              <span className="w-2 h-2 rounded-full" style={{ backgroundColor: st.color }} />
                              {st.label}
                            </span>
                            {t.test_result && (
                              <button
                                type="button"
                                onClick={() => setOpenResult((p) => ({ ...p, [`lab-${t.id}`]: !p[`lab-${t.id}`] }))}
                                className="text-xs text-[#0061FF] font-medium hover:underline"
                              >
                                {resultOpen ? 'Hide Result' : 'View Result ›'}
                              </button>
                            )}
                          </div>
                        </div>
                        {resultOpen && t.test_result && (
                          <div className="mt-2 rounded-md bg-white border border-green-100 p-2 text-sm whitespace-pre-wrap">
                            {t.test_result}
                            {t.comment && <div className="text-xs text-gray-500 mt-1">Comment: {t.comment}</div>}
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              </div>
            )}

            {/* Radiology investigations */}
            {radiology.length > 0 && (
              <div>
                <SectionHeading icon={<Radiation size={16} />} title="Radiology Investigations" count={radiology.length} />
                <div className="space-y-2">
                  {radiology.map((t: any) => {
                    const st = testStatus(t)
                    const resultOpen = !!openResult[`rad-${t.id}`]
                    return (
                      <div key={t.id} className="rounded-lg bg-[#FFF8F1] border border-orange-100 p-3">
                        <div className="flex flex-wrap items-center justify-between gap-2">
                          <div className="min-w-0">
                            <div className="text-sm font-semibold text-[#111827]">{t.test_name || 'Unnamed Test'}</div>
                            <div className="text-xs text-gray-400">{fmtDate(t.ordered_date)}</div>
                          </div>
                          <div className="flex items-center gap-3">
                            <span className="flex items-center gap-1.5 text-xs">
                              <span className="w-2 h-2 rounded-full" style={{ backgroundColor: st.color }} />
                              {st.label}
                            </span>
                            {t.test_result && (
                              <button
                                type="button"
                                onClick={() => setOpenResult((p) => ({ ...p, [`rad-${t.id}`]: !p[`rad-${t.id}`] }))}
                                className="text-xs text-[#0061FF] font-medium hover:underline"
                              >
                                {resultOpen ? 'Hide Result' : 'View Result ›'}
                              </button>
                            )}
                          </div>
                        </div>
                        {resultOpen && t.test_result && (
                          <div className="mt-2 rounded-md bg-white border border-orange-100 p-2 text-sm whitespace-pre-wrap">
                            {t.test_result}
                            {t.comment && <div className="text-xs text-gray-500 mt-1">Comment: {t.comment}</div>}
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              </div>
            )}

            {/* Clinical notes */}
            {hasNotes && (
              <div>
                <SectionHeading icon={<User size={16} />} title="Clinical Notes" />
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <Note label="Patient Complaint" value={c.patient_complaint} />
                  <Note label="Complaint History" value={c.patient_complaint_history} />
                  <Note label="Examination" value={c.doctor_examination} />
                  <Note label="Diagnosis" value={c.diagnosis || c.doctor_diagnosis} />
                  <Note label="Treatment Plan" value={c.treatment_plan || c.treatment} />
                  <Note label="Doctor's Comment" value={c.doctor_comment} />
                  <Note label="Nurse's Comment" value={c.nurse_comment} />
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}

const ConsultationHistoryTimeline: React.FC<Props> = ({ consultations }) => {
  const items = consultations || []
  // Accordion: only one encounter open at a time.
  const [openKey, setOpenKey] = useState<string | number | null>(null)

  if (items.length === 0) return null

  return (
    <div>
      <div className="mb-4">
        <h3 className="text-lg font-bold text-[#111827]">Consultation History</h3>
        <p className="text-xs text-gray-400">Newest first · {items.length} encounter{items.length === 1 ? '' : 's'}</p>
      </div>
      <div className="relative">
        {/* vertical timeline line */}
        <span className="absolute left-[4px] top-2 bottom-2 w-px bg-gray-200" aria-hidden />
        {items.map((c: any, idx: number) => {
          const key = c.id ?? idx
          return (
            <EncounterCard
              key={key}
              c={c}
              open={openKey === key}
              onToggle={() => setOpenKey((prev) => (prev === key ? null : key))}
            />
          )
        })}
      </div>
    </div>
  )
}

export default ConsultationHistoryTimeline
