"use client";

import { useState } from "react";
import type { PatientData } from "@/lib/types";
import { Bot, Send, Sparkles, BookOpen, Pill, Stethoscope, FileText } from "lucide-react";

interface ChatMessage {
  role: "user" | "assistant";
  content: string;
}

export function AISidebar({ data }: { data: PatientData }) {
  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<ChatMessage[]>([
    {
      role: "assistant",
      content: `Habari Daktari! I'm reviewing ${data.patient.firstName}'s chart. Key observations:\n\n• A1c has risen significantly to 10.2% — glycemic control has deteriorated\n• Metformin adherence at 78% — patient reports GI side effects\n• Blood pressure well-controlled at 128/78\n• Patient app shows fasting glucose consistently >10 mmol/L\n\nI recommend discussing GLP-1 RA initiation if available at KNH pharmacy. Alternatively, consider insulin initiation per Kenya Diabetes Guidelines. Would you like me to generate an order set or draft a patient education summary in Swahili?`,
    },
  ]);

  const quickActions = [
    { icon: Pill, label: "Drug interactions", query: "Check all current medications for interactions" },
    { icon: Stethoscope, label: "Differential", query: "What could explain the rising A1c despite metformin?" },
    { icon: BookOpen, label: "Guidelines", query: "ADA guidelines for T2DM with A1c >10%" },
    { icon: FileText, label: "Draft letter", query: "Draft a prior auth letter for semaglutide" },
  ];

  const handleSend = () => {
    if (!input.trim()) return;
    const userMsg = input.trim();
    setMessages((prev) => [...prev, { role: "user", content: userMsg }]);
    setInput("");

    // Simulate AI response
    setTimeout(() => {
      let response = "";
      if (userMsg.toLowerCase().includes("guidelines") || userMsg.toLowerCase().includes("ada")) {
        response = `Based on the 2024 ADA Standards of Care:\n\n**For A1c >10% or symptomatic hyperglycemia:**\n• Consider initiating combination injectable therapy (GLP-1 RA + basal insulin) or basal insulin alone\n• GLP-1 RAs are preferred over insulin for most patients due to weight loss benefits and lower hypoglycemia risk\n• For this patient with cardiovascular risk factors, semaglutide or liraglutide would provide cardiovascular benefit\n\n**Recommended approach:**\n1. Continue metformin if tolerated\n2. Add semaglutide 0.25mg weekly × 4 weeks, then 0.5mg weekly\n3. If A1c remains >8% after 3 months, uptitrate to 1mg weekly\n\nSource: ADA Standards of Care 2024, Section 9`;
      } else if (userMsg.toLowerCase().includes("interaction")) {
        response = `Drug interaction check for ${data.patient.firstName}'s current medications:\n\n✅ **Metformin + Lisinopril** — No significant interaction\n✅ **Metformin + Atorvastatin** — No significant interaction\n✅ **Lisinopril + Atorvastatin** — No significant interaction\n\n⚠️ **If adding Semaglutide:**\n• Semaglutide may delay gastric emptying, potentially affecting absorption of oral medications\n• Monitor for enhanced metformin GI side effects\n• No dose adjustment needed for current medications\n\nOverall: **Safe to proceed with GLP-1 RA addition**`;
      } else if (userMsg.toLowerCase().includes("draft") || userMsg.toLowerCase().includes("letter")) {
        response = `**Prior Authorization Request — Semaglutide (Ozempic)**\n\nPatient: ${data.patient.firstName} ${data.patient.lastName}\nDOB: ${new Date(data.patient.dateOfBirth).toLocaleDateString()}\nInsurance: ${data.patient.insuranceName}\n\nDear Medical Director,\n\nI am writing to request prior authorization for semaglutide (Ozempic) for my patient who has Type 2 Diabetes Mellitus (E11.65) with inadequate glycemic control despite maximum-dose metformin therapy.\n\n**Clinical Justification:**\n• Current A1c: 10.2% (target <7.0%)\n• Previous A1c: 7.8% → 10.2% (worsening trend)\n• Currently on metformin 1000mg BID with 78% adherence\n• Patient reports GI intolerance limiting dose escalation\n• BMI 29.2 — GLP-1 RA preferred for weight management benefit\n• Cardiovascular risk factors present (HTN, HLD)\n\nSemaglutide is the preferred agent per ADA 2024 guidelines for patients with established cardiovascular risk.\n\nSincerely,\nDr. James Chen\n\n*Ready to submit. Shall I send this to the PA agent?*`;
      } else {
        response = `Based on ${data.patient.firstName}'s current clinical picture, here are my recommendations:\n\n1. **Glycemic Management:** The A1c rise from 7.8% to 10.2% warrants therapy intensification. Consider GLP-1 RA as first-line add-on.\n\n2. **Adherence Support:** Metformin adherence at 78% is suboptimal. Consider switching to extended-release formulation to reduce GI side effects.\n\n3. **Monitoring:** Recommend CGM initiation for real-time glucose monitoring through the Clevora Patient app.\n\nWould you like me to generate orders for any of these recommendations?`;
      }

      setMessages((prev) => [...prev, { role: "assistant", content: response }]);
    }, 1000);
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="p-3 border-b border-slate-100">
        <div className="flex items-center gap-2">
          <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-clinical-500 to-accent-teal flex items-center justify-center">
            <Bot size={14} className="text-white" />
          </div>
          <div>
            <p className="text-xs font-semibold text-slate-800">Clevora AI Assistant</p>
            <p className="text-[10px] text-slate-400">Context: {data.patient.firstName}&apos;s chart</p>
          </div>
          <Sparkles size={12} className="text-yellow-500 ml-auto" />
        </div>
      </div>

      {/* Quick Actions */}
      <div className="p-2 border-b border-slate-100">
        <div className="grid grid-cols-2 gap-1">
          {quickActions.map((action) => (
            <button
              key={action.label}
              onClick={() => {
                setInput(action.query);
                setMessages((prev) => [...prev, { role: "user", content: action.query }]);
                setTimeout(() => {
                  setMessages((prev) => [
                    ...prev,
                    { role: "assistant", content: "Analyzing... Let me look into that for you." },
                  ]);
                }, 500);
              }}
              className="flex items-center gap-1.5 px-2 py-1.5 bg-slate-50 rounded-lg text-[10px] font-medium text-slate-600 hover:bg-clinical-50 hover:text-clinical-700 transition-colors"
            >
              <action.icon size={10} />
              {action.label}
            </button>
          ))}
        </div>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-auto p-3 space-y-3">
        {messages.map((msg, i) => (
          <div
            key={i}
            className={`${
              msg.role === "user" ? "ml-6" : "mr-2"
            }`}
          >
            {msg.role === "assistant" && (
              <div className="flex items-center gap-1 mb-1">
                <Bot size={10} className="text-clinical-600" />
                <span className="text-[10px] text-clinical-600 font-medium">Clevora AI</span>
              </div>
            )}
            <div
              className={`rounded-xl px-3 py-2 text-xs leading-relaxed ${
                msg.role === "user"
                  ? "bg-clinical-600 text-white"
                  : "bg-slate-50 text-slate-700 border border-slate-100"
              }`}
            >
              <pre className="whitespace-pre-wrap font-sans">{msg.content}</pre>
            </div>
          </div>
        ))}
      </div>

      {/* Input */}
      <div className="p-3 border-t border-slate-100">
        <div className="flex items-center gap-2">
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSend()}
            placeholder="Ask about this patient..."
            className="flex-1 px-3 py-2 bg-slate-50 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-clinical-500"
          />
          <button
            onClick={handleSend}
            className="p-2 bg-clinical-600 text-white rounded-lg hover:bg-clinical-700 transition-colors"
          >
            <Send size={12} />
          </button>
        </div>
        <p className="text-[8px] text-slate-400 mt-1 text-center">
          AI confidence: 94% • Sources: Chart data, ADA 2024 guidelines
        </p>
      </div>
    </div>
  );
}
