"use client";

import type { PatientData } from "@/lib/types";
import {
  TrendingUp,
  TrendingDown,
  Minus,
  AlertTriangle,
  CheckCircle,
  ChevronRight,
  Smartphone,
  Bot,
} from "lucide-react";

export function SummaryTab({ data }: { data: PatientData }) {
  const controlColors: Record<string, string> = {
    Controlled: "bg-green-100 text-green-700 border-green-200",
    Stable: "bg-blue-100 text-blue-700 border-blue-200",
    Uncontrolled: "bg-red-100 text-red-700 border-red-200",
    Worsening: "bg-red-100 text-red-800 border-red-300",
  };

  const trendIcons: Record<string, React.ReactNode> = {
    up: <TrendingUp size={12} className="text-red-500" />,
    down: <TrendingDown size={12} className="text-green-500" />,
    stable: <Minus size={12} className="text-blue-500" />,
  };

  // Recent labs (last 30 days)
  const recentLabs = data.labs.filter((l) => {
    const d = new Date(l.resultDate);
    return Date.now() - d.getTime() < 30 * 86400000;
  });

  const outstandingItems = [
    ...(data.labs.filter((l) => l.status === "Critical" && !l.isAcknowledged).length > 0
      ? ["Review critical lab results"]
      : []),
    ...(data.problems.filter((p) => p.controlStatus === "Uncontrolled" || p.controlStatus === "Worsening").length > 0
      ? ["Address uncontrolled conditions"]
      : []),
    "Annual diabetic foot exam overdue",
    "Medication reconciliation needed",
    "Colorectal cancer screening due",
  ];

  return (
    <div className="space-y-5 max-w-5xl">
      {/* AI Visit Summary Banner */}
      <div className="bg-gradient-to-r from-clinical-50 to-accent-teal-light border border-clinical-200 rounded-xl p-4">
        <div className="flex items-start gap-3">
          <Bot size={18} className="text-clinical-600 mt-0.5 shrink-0" />
          <div>
            <h3 className="text-sm font-semibold text-clinical-800">
              AI Visit Preparation Summary
            </h3>
            <p className="text-xs text-clinical-700 mt-1 leading-relaxed">
              {data.patient.firstName} is here for a diabetes follow-up. Key concerns: A1c has risen
              significantly from 7.8% to 10.2%, indicating poor glycemic control. Patient reports
              increased fatigue and thirst. Metformin adherence at 78% — patient reports GI side effects.
              Consider GLP-1 RA initiation or insulin. Blood pressure well-controlled on current regimen.
              LDL at goal. Patient app data shows glucose readings consistently above 180 mg/dL fasting.
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        {/* Problem-Oriented Summary */}
        <div className="space-y-3">
          <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
            <AlertTriangle size={14} className="text-clinical-600" />
            Active Problems
          </h3>
          {data.problems.map((problem) => (
            <div
              key={problem.id}
              className="bg-white border border-slate-200 rounded-xl p-4 hover:border-clinical-300 transition-colors cursor-pointer"
            >
              <div className="flex items-start justify-between mb-2">
                <div>
                  <p className="text-sm font-semibold text-slate-800">
                    {problem.name}
                  </p>
                  <p className="text-[10px] text-slate-400 mt-0.5">
                    {problem.icdCode}
                  </p>
                </div>
                {problem.controlStatus && (
                  <span
                    className={`px-2 py-0.5 rounded-full text-[10px] font-medium border ${
                      controlColors[problem.controlStatus] || "bg-slate-100 text-slate-600 border-slate-200"
                    }`}
                  >
                    {problem.controlStatus}
                  </span>
                )}
              </div>
              {problem.lastResult && (
                <p className="text-xs text-slate-600 mt-1">
                  📊 {problem.lastResult}
                </p>
              )}
              {problem.patientReported && (
                <p className="text-xs text-purple-600 mt-1">
                  📱 Patient: &ldquo;{problem.patientReported}&rdquo;
                </p>
              )}
              {problem.aiRecommendation && (
                <div className="mt-2 flex items-start gap-1.5 bg-clinical-50 rounded-lg p-2">
                  <Bot size={12} className="text-clinical-600 mt-0.5 shrink-0" />
                  <p className="text-[11px] text-clinical-700">
                    {problem.aiRecommendation}
                  </p>
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Right Column */}
        <div className="space-y-5">
          {/* Outstanding Items */}
          <div>
            <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2 mb-3">
              <CheckCircle size={14} className="text-orange-500" />
              Outstanding Items
            </h3>
            <div className="bg-white border border-slate-200 rounded-xl divide-y divide-slate-50">
              {outstandingItems.map((item, idx) => (
                <div
                  key={idx}
                  className="flex items-center gap-3 px-4 py-2.5 hover:bg-slate-50 transition-colors cursor-pointer"
                >
                  <div className="w-5 h-5 rounded border-2 border-slate-300 shrink-0" />
                  <p className="text-xs text-slate-700 flex-1">{item}</p>
                  <ChevronRight size={12} className="text-slate-300" />
                </div>
              ))}
            </div>
          </div>

          {/* Recent Results */}
          <div>
            <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2 mb-3">
              📊 Recent Results
            </h3>
            <div className="bg-white border border-slate-200 rounded-xl divide-y divide-slate-50">
              {recentLabs.slice(0, 5).map((lab) => (
                <div
                  key={lab.id}
                  className="flex items-center gap-3 px-4 py-2.5"
                >
                  <span
                    className={`w-2 h-2 rounded-full shrink-0 ${
                      lab.status === "Critical"
                        ? "bg-red-500"
                        : lab.status === "Abnormal"
                        ? "bg-orange-500"
                        : "bg-green-500"
                    }`}
                  />
                  <p className="text-xs font-medium text-slate-700 flex-1">
                    {lab.testName}
                  </p>
                  <p
                    className={`text-xs font-semibold ${
                      lab.status === "Critical"
                        ? "text-red-600"
                        : lab.status === "Abnormal"
                        ? "text-orange-600"
                        : "text-green-600"
                    }`}
                  >
                    {lab.value} {lab.unit}
                  </p>
                </div>
              ))}
            </div>
          </div>

          {/* Patient App Snapshot */}
          <div>
            <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2 mb-3">
              <Smartphone size={14} className="text-purple-500" />
              Patient App Snapshot
            </h3>
            <div className="bg-white border border-slate-200 rounded-xl p-4 space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">Medication Adherence</span>
                <span className="text-xs font-semibold text-orange-600">78%</span>
              </div>
              <div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
                <div className="h-full bg-orange-500 rounded-full" style={{ width: "78%" }} />
              </div>

              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">Avg Fasting Glucose</span>
                <span className="text-xs font-semibold text-red-600">210 mg/dL</span>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">Weight Trend</span>
                <span className="text-xs font-semibold text-green-600">192 lbs ↓3</span>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">Last Symptom Log</span>
                <span className="text-xs text-slate-600">Fatigue (7/10), 2 days ago</span>
              </div>

              <div className="mt-2 bg-purple-50 rounded-lg p-2">
                <p className="text-[10px] font-medium text-purple-700">Patient flagged for today&apos;s visit:</p>
                <p className="text-[10px] text-purple-600 mt-0.5 italic">
                  &ldquo;I&apos;ve been feeling dizzy in the mornings — wondering if it&apos;s my blood pressure medication&rdquo;
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
