import React from 'react'
import { Tag, Collapse } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import useFetchAppointment from '../../api/hooks/useFetchAppointment'

type Props = {
  consultationId: number | null
}

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

/** A read-only text block; shows a muted placeholder when the doctor hasn't documented it. */
const Note: React.FC<{ label: string; value?: string | null }> = ({ label, value }) => {
  const has = value && value !== 'N/A' && value.trim() !== ''
  return (
    <div>
      <div className="text-[#0061FF] text-[13px] font-semibold mb-1">{label}</div>
      <div
        className={`rounded-[8px] border border-[#E5E7EB] bg-[#F9FAFB] p-3 text-sm whitespace-pre-wrap ${
          has ? 'text-[#111827]' : 'text-gray-400 italic'
        }`}
      >
        {has ? value : 'Not documented yet'}
      </div>
    </div>
  )
}

/** Map a previous-consultation lab/radiology `completed` flag (submit_final: 0/1/2) to a tag. */
const prevTestTag = (t: any) => {
  if (t.completed === 2) return { label: 'Finalized', color: 'green' }
  if (t.completed === 1) return { label: 'Completed', color: 'blue' }
  if (t.test_result) return { label: 'In Progress', color: 'orange' }
  return { label: 'Pending', color: 'default' }
}

const PrevMiniHeading: React.FC<{ title: string; count: number }> = ({ title, count }) => (
  <div className="text-[#0061FF] text-[12px] font-semibold mb-1">
    {title} ({count})
  </div>
)

/** Vitals, procedures, lab tests, radiology tests and pharmacy for a single previous consultation. */
const PrevExtras: React.FC<{ p: any }> = ({ p }) => {
  const procedures = p.procedures || []
  const labs = p.lab_tests || []
  const radiology = p.radiology_tests || []
  const meds = p.pharmacy_medications || []
  const v = p.vitals || {}

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

  if (!vitalItems.length && !procedures.length && !labs.length && !radiology.length && !meds.length) return null

  return (
    <>
      {vitalItems.length > 0 && (
        <div>
          <PrevMiniHeading title="Vitals" count={vitalItems.length} />
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2">
            {vitalItems.map((x) => (
              <div key={x.label} className={`rounded-md p-2 ${x.tone}`}>
                <div className="text-[10px] font-semibold uppercase tracking-wide text-gray-500">{x.label}</div>
                <div className="text-sm font-bold mt-0.5">{x.value}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {procedures.length > 0 && (
        <div>
          <PrevMiniHeading title="Scheduled Procedures" count={procedures.length} />
          <div className="space-y-1.5">
            {procedures.map((pr: any, i: number) => (
              <div key={pr.billItemId ?? i} className="rounded-md border border-gray-200 bg-white p-2 flex items-center justify-between gap-2 text-sm">
                <span className="min-w-0 truncate">
                  {pr.name || 'Procedure'}
                  {pr.quantity ? ` × ${pr.quantity}` : ''}
                </span>
                <span className={`text-xs shrink-0 ${pr.paid ? 'text-green-600' : 'text-gray-500'}`}>
                  {pr.paid ? 'Paid' : 'Unpaid'}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      {labs.length > 0 && (
        <div>
          <PrevMiniHeading title="Laboratory Tests" count={labs.length} />
          <div className="space-y-1.5">
            {labs.map((t: any) => {
              const st = prevTestTag(t)
              return (
                <div key={t.id} className="rounded-md border border-gray-200 bg-white p-2 text-sm">
                  <div className="flex items-center justify-between gap-2">
                    <span className="min-w-0 truncate font-medium">{t.test_name || 'Test'}</span>
                    <Tag color={st.color} className="shrink-0">{st.label}</Tag>
                  </div>
                  {t.test_result && <div className="text-xs text-gray-600 mt-1">Result: {t.test_result}</div>}
                  {t.comment && <div className="text-xs text-gray-400 mt-0.5">{t.comment}</div>}
                </div>
              )
            })}
          </div>
        </div>
      )}

      {radiology.length > 0 && (
        <div>
          <PrevMiniHeading title="Radiology Tests" count={radiology.length} />
          <div className="space-y-1.5">
            {radiology.map((t: any) => {
              const st = prevTestTag(t)
              return (
                <div key={t.id} className="rounded-md border border-gray-200 bg-white p-2 text-sm">
                  <div className="flex items-center justify-between gap-2">
                    <span className="min-w-0 truncate font-medium">{t.test_name || 'Test'}</span>
                    <Tag color={st.color} className="shrink-0">{st.label}</Tag>
                  </div>
                  {t.test_result && <div className="text-xs text-gray-600 mt-1">Result: {t.test_result}</div>}
                  {t.comment && <div className="text-xs text-gray-400 mt-0.5">{t.comment}</div>}
                </div>
              )
            })}
          </div>
        </div>
      )}

      {meds.length > 0 && (
        <div>
          <PrevMiniHeading title="Pharmacy" count={meds.length} />
          <div className="space-y-1.5">
            {meds.map((m: any) => (
              <div key={m.id} className="rounded-md border border-gray-200 bg-white p-2 text-sm">
                <div className="flex items-center justify-between gap-2">
                  <span className="min-w-0 truncate font-medium">
                    {m.medication_name || 'Medication'}
                    {m.quantity ? ` × ${m.quantity}` : ''}
                  </span>
                  <span className={`text-xs shrink-0 ${m.dispensed === 1 ? 'text-green-600' : 'text-gray-500'}`}>
                    {m.dispensed === 1 ? 'Dispensed' : 'Pending Dispense'}
                  </span>
                </div>
                {(m.dosage != null || m.daily_frequency != null || m.administration_mode) && (
                  <div className="text-xs text-gray-500 mt-1">
                    {[
                      m.dosage != null && `Dosage: ${m.dosage}`,
                      m.daily_frequency != null && `Freq: ${m.daily_frequency}x daily`,
                      m.administration_mode && `Route: ${m.administration_mode}`,
                    ]
                      .filter(Boolean)
                      .join('   ')}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  )
}

const DoctorDocumentationModal: React.FC<Props> = ({ consultationId }) => {
  const { data, isLoading, error } = useFetchAppointment(consultationId ?? 0)

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-16 text-gray-500">
        <LoadingOutlined spin style={{ fontSize: 28 }} />
        <span className="ml-3">Loading documentation…</span>
      </div>
    )
  }

  if (error || !data?.response) {
    return (
      <div className="py-10 text-center text-red-500">
        Could not load the doctor's documentation for this appointment.
      </div>
    )
  }

  const res = data.response
  const c = res.consultation || {}
  const patient = res.patient || {}
  const vitals = c.vitals || {}
  const diagnostics = res.diagnostics || []
  const radiology = res.radiology_diagnostics || []
  const medications = res.pharmacy_medications || []
  const previous = res.previous_consultations || []

  const patientName = [patient.first_name, patient.middle_name, patient.last_name]
    .filter(Boolean)
    .join(' ')

  const vitalItems: { label: string; value?: string | null; unit?: string }[] = [
    { label: 'Blood Pressure', value: vitals.blood_pressure, unit: '' },
    { label: 'Temperature', value: vitals.temperature, unit: '°C' },
    { label: 'Pulse', value: vitals.pulse_rate, unit: 'bpm' },
    { label: 'Weight', value: vitals.weight, unit: 'kg' },
    { label: 'Height', value: vitals.height, unit: 'cm' },
    { label: 'Oxygen', value: vitals.oxygen_level, unit: '%' },
    { label: 'RBS', value: vitals.blood_sugar_rbs, unit: '' },
    { label: 'FBS', value: vitals.blood_sugar_fbs, unit: '' },
  ]
  const hasVitals = vitalItems.some((v) => v.value && `${v.value}`.trim() !== '')

  return (
    <div className="max-h-[75vh] overflow-y-auto pr-1">
      {/* Patient / appointment header */}
      <div className="rounded-[10px] bg-[#EEF4FF] p-4 mb-4">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <div>
            <div className="text-lg font-bold text-[#030229]">{patientName || 'Patient'}</div>
            <div className="text-xs text-gray-500">
              File No: {patient.file_number || '—'} · {c.name || 'Consultation'}
            </div>
          </div>
          <div className="text-right text-xs text-gray-600">
            <div>
              <span className="font-semibold">Doctor:</span> {c.doctor_name || '—'}
            </div>
            <div>
              <span className="font-semibold">Date:</span> {formatDate(c.scheduled_date)}
            </div>
          </div>
        </div>
      </div>

      {/* Vitals */}
      {hasVitals && (
        <div className="mb-4">
          <div className="text-[#0061FF] text-[13px] font-semibold mb-2">Vitals</div>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
            {vitalItems
              .filter((v) => v.value && `${v.value}`.trim() !== '')
              .map((v) => (
                <div key={v.label} className="rounded-[8px] border border-[#E5E7EB] bg-white p-2 text-center">
                  <div className="text-[11px] text-gray-500">{v.label}</div>
                  <div className="text-sm font-semibold text-[#111827]">
                    {v.value}
                    {v.unit ? ` ${v.unit}` : ''}
                  </div>
                </div>
              ))}
          </div>
        </div>
      )}

      {/* Doctor's documentation */}
      <div className="grid grid-cols-1 gap-3 mb-4">
        <Note label="Patient Complaint" value={c.patient_complaint} />
        <Note label="Complaint History" value={c.patient_complaint_history} />
        <Note label="Doctor's 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>

      {/* Lab tests */}
      {diagnostics.length > 0 && (
        <div className="mb-4">
          <div className="text-[#0061FF] text-[13px] font-semibold mb-2">Lab Tests</div>
          <div className="space-y-2">
            {diagnostics.map((d: any) => (
              <div key={d.id} className="rounded-[8px] border border-[#E5E7EB] bg-white p-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">{d.medical_test}</span>
                  <Tag color={d.status_text === 'Finalized' || d.status_text === 'Completed' ? 'green' : 'orange'}>
                    {d.status_text}
                  </Tag>
                </div>
                {d.medical_test_result && (
                  <div className="text-sm text-gray-700 mt-1">Result: {d.medical_test_result}</div>
                )}
                {d.medical_test_comment && (
                  <div className="text-xs text-gray-500 mt-1">{d.medical_test_comment}</div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Radiology */}
      {radiology.length > 0 && (
        <div className="mb-4">
          <div className="text-[#0061FF] text-[13px] font-semibold mb-2">Radiology</div>
          <div className="space-y-2">
            {radiology.map((d: any) => (
              <div key={d.id} className="rounded-[8px] border border-[#E5E7EB] bg-white p-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">{d.medical_test || d.radiology_test}</span>
                  <Tag color={d.status_text === 'Finalized' || d.status_text === 'Completed' ? 'green' : 'orange'}>
                    {d.status_text}
                  </Tag>
                </div>
                {(d.radiology_test_result || d.medical_test_result) && (
                  <div className="text-sm text-gray-700 mt-1">
                    Result: {d.radiology_test_result || d.medical_test_result}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Prescriptions */}
      {medications.length > 0 && (
        <div className="mb-4">
          <div className="text-[#0061FF] text-[13px] font-semibold mb-2">Prescriptions</div>
          <div className="space-y-2">
            {medications.map((m: any) => (
              <div key={m.id} className="rounded-[8px] border border-[#E5E7EB] bg-white p-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">
                    {m.medication_name} {m.quantity ? `× ${m.quantity}` : ''}
                  </span>
                  <Tag color={m.status_text === 'Dispensed' ? 'green' : 'orange'}>{m.status_text}</Tag>
                </div>
                {m.comment && <div className="text-xs text-gray-500 mt-1">{m.comment}</div>}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Previous consultations */}
      {previous.length > 0 && (
        <div className="mb-2">
          <div className="text-[#0061FF] text-[13px] font-semibold mb-2">
            Previous Consultations ({previous.length})
          </div>
          <Collapse
            accordion
            items={previous.map((p: any, idx: number) => ({
              key: String(p.id ?? idx),
              label: (
                <span className="text-sm">
                  {formatDate(p.consultation_date || p.scheduled_date)} · {p.doctor_name || 'Doctor'}
                </span>
              ),
              children: (
                <div className="grid grid-cols-1 gap-3">
                  <Note label="Patient Complaint" value={p.patient_complaint} />
                  <Note label="Examination" value={p.doctor_examination} />
                  <Note label="Diagnosis" value={p.diagnosis || p.doctor_diagnosis} />
                  <Note label="Treatment Plan" value={p.treatment_plan || p.treatment} />
                  <Note label="Doctor's Comment" value={p.doctor_comment} />
                  <PrevExtras p={p} />
                </div>
              ),
            }))}
          />
        </div>
      )}
    </div>
  )
}

export default DoctorDocumentationModal
