"use client";

import { useState } from "react";
import type { PatientData } from "@/lib/types";
import { FlaskConical, Bot, CheckCircle, Eye } from "lucide-react";

export function ResultsTab({ data }: { data: PatientData }) {
  const [filter, setFilter] = useState<string>("all");

  const filters = ["all", "Critical", "Abnormal", "Normal", "Pending"];

  const filtered = filter === "all" ? data.labs : data.labs.filter((l) => l.status === filter);

  const statusColor = (status: string) => {
    switch (status) {
      case "Critical": return "bg-red-100 text-red-700 border-red-200";
      case "Abnormal": return "bg-orange-100 text-orange-700 border-orange-200";
      case "Normal": return "bg-green-100 text-green-700 border-green-200";
      default: return "bg-slate-100 text-slate-600 border-slate-200";
    }
  };

  const statusDot = (status: string) => {
    switch (status) {
      case "Critical": return "bg-red-500";
      case "Abnormal": return "bg-orange-500";
      case "Normal": return "bg-green-500";
      default: return "bg-slate-400";
    }
  };

  // Group by test name for trend sparklines
  const testGroups = new Map<string, typeof data.labs>();
  data.labs.forEach((lab) => {
    const group = testGroups.get(lab.testName) || [];
    group.push(lab);
    testGroups.set(lab.testName, group);
  });

  return (
    <div className="space-y-5 max-w-5xl">
      {/* Filters */}
      <div className="flex items-center gap-2 flex-wrap">
        {filters.map((f) => {
          const count = f === "all" ? data.labs.length : data.labs.filter((l) => l.status === f).length;
          return (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                filter === f
                  ? "bg-clinical-600 text-white"
                  : "bg-white border border-slate-200 text-slate-600 hover:bg-slate-50"
              }`}
            >
              {f === "all" ? "All" : f} ({count})
            </button>
          );
        })}
      </div>

      {/* Results List */}
      <div className="bg-white border border-slate-200 rounded-xl">
        <div className="px-5 py-3 border-b border-slate-100 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <FlaskConical size={14} className="text-clinical-600" />
            <h3 className="text-sm font-semibold text-slate-800">
              Results ({filtered.length})
            </h3>
          </div>
        </div>
        <div className="divide-y divide-slate-50">
          {filtered.map((lab) => {
            const sameTests = testGroups.get(lab.testName) || [];
            const prevValue = sameTests.length > 1 ? sameTests[1] : null;
            return (
              <div key={lab.id} className="px-5 py-4 hover:bg-slate-50 transition-colors">
                <div className="flex items-start gap-4">
                  <span className={`w-2.5 h-2.5 rounded-full mt-1.5 shrink-0 ${statusDot(lab.status)}`} />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-semibold text-slate-800">{lab.testName}</p>
                      <span className={`px-1.5 py-0.5 rounded text-[10px] font-medium border ${statusColor(lab.status)}`}>
                        {lab.status}
                      </span>
                      {!lab.isAcknowledged && (
                        <span className="px-1.5 py-0.5 bg-yellow-100 text-yellow-700 rounded text-[10px] font-medium">
                          Unacknowledged
                        </span>
                      )}
                    </div>
                    <div className="flex items-center gap-4 mt-1">
                      <span className={`text-lg font-bold ${
                        lab.status === "Critical" ? "text-red-600" :
                        lab.status === "Abnormal" ? "text-orange-600" :
                        "text-green-600"
                      }`}>
                        {lab.value} {lab.unit}
                      </span>
                      {lab.referenceRange && (
                        <span className="text-xs text-slate-400">
                          Ref: {lab.referenceRange}
                        </span>
                      )}
                      {prevValue && (
                        <span className="text-xs text-slate-500">
                          Previous: {prevValue.value} {prevValue.unit} ({new Date(prevValue.resultDate).toLocaleDateString()})
                        </span>
                      )}
                    </div>
                    <p className="text-[10px] text-slate-400 mt-1">
                      {new Date(lab.resultDate).toLocaleDateString()} at {new Date(lab.resultDate).toLocaleTimeString()}
                    </p>
                    {lab.aiInterpretation && (
                      <div className="mt-2 bg-clinical-50 rounded-lg p-2 flex items-start gap-2">
                        <Bot size={12} className="text-clinical-600 mt-0.5 shrink-0" />
                        <p className="text-[10px] text-clinical-700 leading-relaxed">{lab.aiInterpretation}</p>
                      </div>
                    )}
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <button className="p-1.5 hover:bg-green-50 rounded-lg transition-colors" title="Acknowledge">
                      <CheckCircle size={14} className="text-green-600" />
                    </button>
                    <button className="p-1.5 hover:bg-blue-50 rounded-lg transition-colors" title="View Details">
                      <Eye size={14} className="text-blue-600" />
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Trend Summary */}
      <div className="bg-white border border-slate-200 rounded-xl p-4">
        <h3 className="text-sm font-semibold text-slate-800 mb-3">📈 Trend Summary</h3>
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          {Array.from(testGroups.entries())
            .filter(([, tests]) => tests.length > 1)
            .map(([name, tests]) => {
              const latest = tests[0];
              const prev = tests[1];
              const change = parseFloat(latest.value) - parseFloat(prev.value);
              const changePercent = ((change / parseFloat(prev.value)) * 100).toFixed(1);
              return (
                <div key={name} className="bg-slate-50 rounded-lg p-3">
                  <p className="text-xs font-medium text-slate-600 truncate">{name}</p>
                  <p className={`text-lg font-bold mt-1 ${
                    latest.status === "Critical" ? "text-red-600" :
                    latest.status === "Abnormal" ? "text-orange-600" : "text-green-600"
                  }`}>
                    {latest.value}
                    <span className="text-[10px] text-slate-400 ml-1">{latest.unit}</span>
                  </p>
                  <p className={`text-[10px] mt-0.5 ${change > 0 ? "text-red-500" : "text-green-500"}`}>
                    {change > 0 ? "↑" : "↓"} {Math.abs(change).toFixed(1)} ({changePercent}%)
                  </p>
                </div>
              );
            })}
        </div>
      </div>
    </div>
  );
}
