"use client";

import { useState } from "react";
import type { PatientData } from "@/lib/types";
import { Mic, MicOff, FileText, CheckCircle, AlertTriangle, Bot } from "lucide-react";

export function NotesTab({ data }: { data: PatientData }) {
  const [isListening, setIsListening] = useState(false);
  const [noteTemplate, setNoteTemplate] = useState("SOAP");

  const templates = ["SOAP", "H&P", "Consult", "Procedure", "Discharge", "Telehealth", "AWV"];

  const liveNote = `CHIEF COMPLAINT
Fatigue and increased thirst × 3 weeks

HISTORY OF PRESENT ILLNESS
${data.patient.firstName} ${data.patient.lastName} is a ${new Date().getFullYear() - new Date(data.patient.dateOfBirth).getFullYear()}-year-old ${data.patient.gender.toLowerCase()} with a history of ${data.problems.map(p => p.name).join(", ")} presenting today for follow-up of diabetes management. Reports increased fatigue and polydipsia over the past 3 weeks. Home glucose readings have been running 180-240 mg/dL fasting, higher than usual 130-160 range. Attributes worsening to increased work stress and reduced exercise. Denies polyuria, blurred vision, or lower extremity numbness.

REVIEW OF SYSTEMS
Constitutional: (+) Fatigue, (-) Fever, (-) Weight loss
HEENT: (-) Blurred vision, (-) Eye pain
Cardiovascular: (-) Chest pain, (-) Palpitations
Respiratory: (-) Dyspnea, (-) Cough
GI: (+) Nausea with metformin occasionally
Neuro: (-) Numbness, (-) Tingling
Endocrine: (+) Polydipsia, (-) Polyuria

PHYSICAL EXAM
Vitals: BP 128/78, HR 76, Temp 98.4°F, SpO2 98%, Weight 192 lbs
General: Alert, well-appearing, NAD
HEENT: PERRL, EOMI, oropharynx clear
CV: RRR, S1/S2 normal, no murmurs
Lungs: CTAB, no wheezing
Abdomen: Soft, NT/ND, NABS
Extremities: No edema, intact pedal pulses bilaterally
Neuro: Intact monofilament sensation bilaterally, DTRs 2+ symmetric

ASSESSMENT & PLAN
1. Type 2 Diabetes Mellitus (E11.65) — UNCONTROLLED
   - A1c risen from 7.8% to 10.2%
   - Consider initiating GLP-1 RA (semaglutide)
   - Continue metformin 1000mg BID — counsel on taking with food
   - Diabetic education referral
   - Recheck A1c in 3 months
   
2. Essential Hypertension (I10) — CONTROLLED
   - BP at goal on lisinopril 20mg daily
   - Continue current regimen
   
3. Hyperlipidemia (E78.5) — AT GOAL
   - LDL 98 on atorvastatin 40mg
   - Continue current therapy`;

  const qualityChecks = [
    { pass: true, text: "All required elements present for 99214" },
    { pass: true, text: "ICD-10 codes have supporting documentation" },
    { pass: true, text: "Orders consistent with documented assessment" },
    { pass: false, text: "Add stage/control status to HTN for accurate HCC coding" },
    { pass: false, text: "Medication reconciliation — patient app shows OTC supplements" },
  ];

  return (
    <div className="space-y-5 max-w-5xl">
      {/* Ambient Listening Control */}
      <div className="flex items-center justify-between bg-white border border-slate-200 rounded-xl p-4">
        <div className="flex items-center gap-3">
          <button
            onClick={() => setIsListening(!isListening)}
            className={`p-3 rounded-xl transition-all ${
              isListening
                ? "bg-red-100 text-red-600 shadow-lg shadow-red-200/50"
                : "bg-clinical-100 text-clinical-600 hover:bg-clinical-200"
            }`}
          >
            {isListening ? <MicOff size={20} /> : <Mic size={20} />}
          </button>
          <div>
            <p className="text-sm font-semibold text-slate-800">
              {isListening ? "Ambient AI Listening..." : "Ambient AI Documentation"}
            </p>
            <p className="text-xs text-slate-500">
              {isListening
                ? "Listening to visit — building note in real time"
                : 'Click to start or say "Clevora, start listening"'}
            </p>
          </div>
        </div>
        {isListening && (
          <div className="flex items-center gap-2">
            <span className="flex gap-0.5">
              {[1, 2, 3, 4, 5].map((i) => (
                <span
                  key={i}
                  className="w-1 bg-red-400 rounded-full animate-pulse"
                  style={{
                    height: `${8 + Math.random() * 16}px`,
                    animationDelay: `${i * 0.1}s`,
                  }}
                />
              ))}
            </span>
            <span className="text-xs text-red-600 font-medium ml-2">Recording</span>
          </div>
        )}
      </div>

      {/* Template Selection */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-xs font-medium text-slate-500">Template:</span>
        {templates.map((t) => (
          <button
            key={t}
            onClick={() => setNoteTemplate(t)}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
              noteTemplate === t
                ? "bg-clinical-600 text-white"
                : "bg-slate-100 text-slate-600 hover:bg-slate-200"
            }`}
          >
            {t}
          </button>
        ))}
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-5">
        {/* Note Content */}
        <div className="xl:col-span-2">
          <div className="bg-white border border-slate-200 rounded-xl">
            <div className="flex items-center justify-between px-4 py-3 border-b border-slate-100">
              <div className="flex items-center gap-2">
                <FileText size={14} className="text-clinical-600" />
                <span className="text-sm font-semibold text-slate-800">
                  {noteTemplate} Note — Live Preview
                </span>
              </div>
              <div className="flex items-center gap-1 text-[10px]">
                <span className="px-1.5 py-0.5 bg-green-100 text-green-700 rounded">CC ✓</span>
                <span className="px-1.5 py-0.5 bg-green-100 text-green-700 rounded">HPI ✓</span>
                <span className="px-1.5 py-0.5 bg-green-100 text-green-700 rounded">ROS ✓</span>
                <span className="px-1.5 py-0.5 bg-green-100 text-green-700 rounded">Exam ✓</span>
                <span className="px-1.5 py-0.5 bg-green-100 text-green-700 rounded">A&P ✓</span>
              </div>
            </div>
            <div className="p-4">
              <pre className="text-xs text-slate-700 whitespace-pre-wrap font-mono leading-relaxed">
                {liveNote}
              </pre>
            </div>
            <div className="px-4 py-3 border-t border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <button className="px-4 py-2 bg-clinical-600 text-white rounded-lg text-xs font-semibold hover:bg-clinical-700 transition-colors">
                  Sign Note
                </button>
                <button className="px-4 py-2 bg-slate-100 text-slate-600 rounded-lg text-xs font-medium hover:bg-slate-200 transition-colors">
                  Save Draft
                </button>
                <button className="px-4 py-2 bg-slate-100 text-slate-600 rounded-lg text-xs font-medium hover:bg-slate-200 transition-colors">
                  Add Addendum
                </button>
              </div>
              <span className="text-[10px] text-slate-400">Auto-saved 30 seconds ago</span>
            </div>
          </div>
        </div>

        {/* Quality & Billing Side */}
        <div className="space-y-4">
          {/* E&M Recommendation */}
          <div className="bg-white border border-slate-200 rounded-xl p-4">
            <h4 className="text-xs font-semibold text-slate-800 mb-3 flex items-center gap-1.5">
              💰 E&M Level Recommendation
            </h4>
            <div className="text-center mb-3">
              <span className="text-3xl font-bold text-clinical-700">99214</span>
              <p className="text-[10px] text-slate-500 mt-1">
                Level 4 — Moderate MDM
              </p>
            </div>
            <div className="space-y-2 text-[10px]">
              <div className="flex items-center gap-2">
                <CheckCircle size={10} className="text-green-500" />
                <span className="text-slate-600">Moderate number of diagnoses managed</span>
              </div>
              <div className="flex items-center gap-2">
                <CheckCircle size={10} className="text-green-500" />
                <span className="text-slate-600">Moderate data reviewed</span>
              </div>
              <div className="flex items-center gap-2">
                <CheckCircle size={10} className="text-green-500" />
                <span className="text-slate-600">Moderate risk (prescription drug management)</span>
              </div>
            </div>
            <div className="mt-3 bg-blue-50 rounded-lg p-2">
              <p className="text-[10px] text-blue-700">
                💡 Add documentation of drug interaction consideration to support 99215
              </p>
            </div>
          </div>

          {/* Quality Checks */}
          <div className="bg-white border border-slate-200 rounded-xl p-4">
            <h4 className="text-xs font-semibold text-slate-800 mb-3 flex items-center gap-1.5">
              <Bot size={12} className="text-clinical-600" />
              AI Quality Review
            </h4>
            <div className="space-y-2">
              {qualityChecks.map((check, i) => (
                <div key={i} className="flex items-start gap-2">
                  {check.pass ? (
                    <CheckCircle size={12} className="text-green-500 mt-0.5 shrink-0" />
                  ) : (
                    <AlertTriangle size={12} className="text-amber-500 mt-0.5 shrink-0" />
                  )}
                  <span className={`text-[10px] ${check.pass ? "text-slate-600" : "text-amber-700"}`}>
                    {check.text}
                  </span>
                </div>
              ))}
            </div>
          </div>

          {/* Previous Notes */}
          <div className="bg-white border border-slate-200 rounded-xl p-4">
            <h4 className="text-xs font-semibold text-slate-800 mb-3">
              Previous Notes
            </h4>
            {data.notes.length > 0 ? (
              data.notes.map((note) => (
                <div
                  key={note.id}
                  className="p-2 bg-slate-50 rounded-lg mb-2 cursor-pointer hover:bg-slate-100 transition-colors"
                >
                  <p className="text-xs font-medium text-slate-700">
                    {note.noteType} Note
                  </p>
                  <p className="text-[10px] text-slate-500">
                    {new Date(note.visitDate).toLocaleDateString()} — {note.status}
                  </p>
                </div>
              ))
            ) : (
              <p className="text-xs text-slate-400">No previous notes</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
