import { createClient } from "@/lib/supabase/server";
import { notFound } from "next/navigation";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ArrowLeft, CheckCircle2, Activity, Stethoscope, ClipboardList } from "lucide-react";
import { format } from "date-fns";
import { es } from "date-fns/locale";

export const dynamic = "force-dynamic";

export default async function ConsultationDetailPage({ params }: { params: Promise<{ patientId: string; id: string }> }) {
  const { patientId, id } = await params;
  const supabase = await createClient();

  const { data: note, error } = await supabase
    .from("consultation_notes")
    .select("*, doctor:users(id, full_name, specialty, license_number), patient:patients(id, first_name, last_name)")
    .eq("id", id).single();

  if (error || !note) notFound();

  const vs = note.vital_signs || {};

  return (
    <div className="mx-auto max-w-3xl space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href={`/medical-records/${patientId}`}><Button variant="ghost" size="icon"><ArrowLeft className="h-4 w-4" /></Button></Link>
          <div>
            <h1 className="text-2xl font-bold">Nota de consulta</h1>
            <p className="text-sm text-muted-foreground">
              {format(new Date(note.created_at), "d 'de' MMMM yyyy, HH:mm", { locale: es })} — Dr. {note.doctor?.full_name}
            </p>
          </div>
        </div>
        {note.is_signed && <Badge variant="outline" className="text-emerald-600 border-emerald-200 gap-1"><CheckCircle2 className="h-3 w-3" /> Firmada</Badge>}
      </div>

      {/* Vital Signs */}
      {Object.keys(vs).length > 0 && (
        <Card>
          <CardHeader className="pb-3"><CardTitle className="text-base flex items-center gap-2"><Activity className="h-4 w-4 text-primary" /> Signos vitales</CardTitle></CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              {vs.peso && <div className="text-center p-3 rounded-lg bg-muted/50"><div className="text-lg font-bold">{vs.peso}</div><div className="text-xs text-muted-foreground">Peso (kg)</div></div>}
              {vs.talla && <div className="text-center p-3 rounded-lg bg-muted/50"><div className="text-lg font-bold">{vs.talla}</div><div className="text-xs text-muted-foreground">Talla (cm)</div></div>}
              {(vs.ta_sistolica || vs.ta_diastolica) && <div className="text-center p-3 rounded-lg bg-muted/50"><div className="text-lg font-bold">{vs.ta_sistolica}/{vs.ta_diastolica}</div><div className="text-xs text-muted-foreground">T/A (mmHg)</div></div>}
              {vs.fc && <div className="text-center p-3 rounded-lg bg-muted/50"><div className="text-lg font-bold">{vs.fc}</div><div className="text-xs text-muted-foreground">FC (lpm)</div></div>}
              {vs.fr && <div className="text-center p-3 rounded-lg bg-muted/50"><div className="text-lg font-bold">{vs.fr}</div><div className="text-xs text-muted-foreground">FR (rpm)</div></div>}
              {vs.temp && <div className="text-center p-3 rounded-lg bg-muted/50"><div className="text-lg font-bold">{vs.temp}</div><div className="text-xs text-muted-foreground">Temp (C)</div></div>}
              {vs.spo2 && <div className="text-center p-3 rounded-lg bg-muted/50"><div className="text-lg font-bold">{vs.spo2}%</div><div className="text-xs text-muted-foreground">SpO2</div></div>}
            </div>
          </CardContent>
        </Card>
      )}

      {/* SOAP */}
      <Card>
        <CardHeader className="pb-3"><CardTitle className="text-base flex items-center gap-2"><Stethoscope className="h-4 w-4 text-primary" /> Nota SOAP</CardTitle></CardHeader>
        <CardContent className="space-y-4">
          {note.subjective && <div><h4 className="text-sm font-semibold text-primary mb-1">S — Subjetivo</h4><p className="text-sm whitespace-pre-wrap">{note.subjective}</p></div>}
          {note.objective && <><Separator /><div><h4 className="text-sm font-semibold text-primary mb-1">O — Objetivo</h4><p className="text-sm whitespace-pre-wrap">{note.objective}</p></div></>}
          {note.assessment && <><Separator /><div><h4 className="text-sm font-semibold text-primary mb-1">A — Evaluacion</h4><p className="text-sm whitespace-pre-wrap">{note.assessment}</p></div></>}
          {note.plan && <><Separator /><div><h4 className="text-sm font-semibold text-primary mb-1">P — Plan</h4><p className="text-sm whitespace-pre-wrap">{note.plan}</p></div></>}
        </CardContent>
      </Card>

      {/* Diagnoses */}
      {note.diagnoses && note.diagnoses.length > 0 && (
        <Card>
          <CardHeader className="pb-3"><CardTitle className="text-base flex items-center gap-2"><ClipboardList className="h-4 w-4 text-primary" /> Diagnosticos (CIE-10)</CardTitle></CardHeader>
          <CardContent>
            <div className="space-y-2">
              {note.diagnoses.map((d: any, i: number) => (
                <div key={i} className="flex items-center gap-2">
                  <Badge variant={d.type === "principal" ? "default" : "secondary"}>{d.code}</Badge>
                  <span className="text-sm">{d.description}</span>
                  {d.type === "principal" && <Badge variant="outline" className="text-xs">Principal</Badge>}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
