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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Separator } from "@/components/ui/separator";
import { ArrowLeft, Plus, FileText, Stethoscope, Clock, CheckCircle2 } from "lucide-react";
import { format } from "date-fns";
import { es } from "date-fns/locale";

export const dynamic = "force-dynamic";

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

  const { data: patient, error: patientError } = await supabase
    .from("patients").select("*").eq("id", patientId).single();
  if (patientError || !patient) notFound();

  const { data: record } = await supabase
    .from("medical_records").select("*").eq("patient_id", patientId).single();

  const { data: consultations } = await supabase
    .from("consultation_notes")
    .select("*, doctor:users(id, full_name, specialty)")
    .eq("patient_id", patientId)
    .order("created_at", { ascending: false });

  const { data: prescriptions } = await supabase
    .from("prescriptions")
    .select("*")
    .eq("patient_id", patientId)
    .order("created_at", { ascending: false });

  return (
    <div className="mx-auto max-w-5xl space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href="/medical-records"><Button variant="ghost" size="icon"><ArrowLeft className="h-4 w-4" /></Button></Link>
          <div className="flex items-center gap-3">
            <div className="flex h-14 w-14 items-center justify-center rounded-full bg-primary/10 text-primary font-bold text-lg">
              {patient.first_name?.[0]}{patient.last_name?.[0]}
            </div>
            <div>
              <h1 className="text-2xl font-bold">{patient.first_name} {patient.last_name}</h1>
              <p className="text-sm text-muted-foreground">Expediente clinico electronico</p>
            </div>
          </div>
        </div>
        <Link href={`/medical-records/${patientId}/consultation/new`}>
          <Button className="gap-2"><Plus className="h-4 w-4" /> Nueva consulta</Button>
        </Link>
      </div>

      <Tabs defaultValue="consultations">
        <TabsList>
          <TabsTrigger value="consultations" className="gap-2"><Stethoscope className="h-4 w-4" /> Consultas</TabsTrigger>
          <TabsTrigger value="history" className="gap-2"><FileText className="h-4 w-4" /> Antecedentes</TabsTrigger>
        </TabsList>

        {/* Consultations Tab */}
        <TabsContent value="consultations" className="mt-4 space-y-4">
          {!consultations || consultations.length === 0 ? (
            <Card className="flex flex-col items-center justify-center py-16">
              <Stethoscope className="h-12 w-12 text-muted-foreground/40 mb-4" />
              <h3 className="text-lg font-semibold">Sin consultas registradas</h3>
              <p className="text-sm text-muted-foreground mb-4">Crea la primera nota de consulta.</p>
              <Link href={`/medical-records/${patientId}/consultation/new`}>
                <Button>Nueva consulta</Button>
              </Link>
            </Card>
          ) : (
            consultations.map((c: any) => (
              <Link key={c.id} href={`/medical-records/${patientId}/consultation/${c.id}`}>
                <Card className="group cursor-pointer transition-all hover:shadow-md hover:border-primary/20 mb-3">
                  <CardContent className="p-4">
                    <div className="flex items-start justify-between">
                      <div className="flex items-start gap-3">
                        <div className="mt-1 flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
                          <Stethoscope className="h-4 w-4 text-primary" />
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="font-semibold group-hover:text-primary transition-colors">
                              {format(new Date(c.created_at), "d 'de' MMMM, yyyy", { locale: es })}
                            </span>
                            {c.is_signed && <Badge variant="outline" className="text-emerald-600 border-emerald-200 gap-1"><CheckCircle2 className="h-3 w-3" /> Firmada</Badge>}
                          </div>
                          <p className="text-sm text-muted-foreground mt-0.5">Dr. {c.doctor?.full_name}</p>
                          {c.assessment && <p className="text-sm mt-2 line-clamp-2">{c.assessment}</p>}
                          {c.diagnoses && c.diagnoses.length > 0 && (
                            <div className="flex flex-wrap gap-1 mt-2">
                              {c.diagnoses.map((d: any, i: number) => (
                                <Badge key={i} variant="secondary" className="text-xs">{d.code} - {d.description}</Badge>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>
                      <div className="text-xs text-muted-foreground">
                        <Clock className="h-3 w-3 inline mr-1" />
                        {format(new Date(c.created_at), "HH:mm")}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </Link>
            ))
          )}
        </TabsContent>

        {/* History Tab */}
        <TabsContent value="history" className="mt-4">
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader><CardTitle className="text-base">Antecedentes familiares</CardTitle></CardHeader>
              <CardContent>
                {record?.family_history && record.family_history.length > 0 ? (
                  <ul className="space-y-1 text-sm">{record.family_history.map((h: any, i: number) => (
                    <li key={i} className="flex items-center gap-2"><span className="font-medium">{h.enfermedad}</span> <span className="text-muted-foreground">({h.parentesco})</span></li>
                  ))}</ul>
                ) : <p className="text-sm text-muted-foreground">Sin antecedentes registrados.</p>}
              </CardContent>
            </Card>
            <Card>
              <CardHeader><CardTitle className="text-base">Antecedentes personales</CardTitle></CardHeader>
              <CardContent>
                {record?.personal_history && record.personal_history.length > 0 ? (
                  <ul className="space-y-1 text-sm">{record.personal_history.map((h: any, i: number) => (
                    <li key={i}><span className="font-medium">{h.enfermedad}</span> <span className="text-muted-foreground">- {h.tratamiento}</span></li>
                  ))}</ul>
                ) : <p className="text-sm text-muted-foreground">Sin antecedentes registrados.</p>}
              </CardContent>
            </Card>
            <Card>
              <CardHeader><CardTitle className="text-base">Ciugias previas</CardTitle></CardHeader>
              <CardContent>
                {record?.surgical_history && record.surgical_history.length > 0 ? (
                  <ul className="space-y-1 text-sm">{record.surgical_history.map((h: any, i: number) => (
                    <li key={i}><span className="font-medium">{h.cirugia}</span> <span className="text-muted-foreground">({h.fecha})</span></li>
                  ))}</ul>
                ) : <p className="text-sm text-muted-foreground">Sin cirugias registradas.</p>}
              </CardContent>
            </Card>
            <Card>
              <CardHeader><CardTitle className="text-base">Medicamentos actuales</CardTitle></CardHeader>
              <CardContent>
                {record?.current_medications && record.current_medications.length > 0 ? (
                  <ul className="space-y-1 text-sm">{record.current_medications.map((m: any, i: number) => (
                    <li key={i}><span className="font-medium">{m.medicamento}</span> <span className="text-muted-foreground">{m.dosis} - {m.frecuencia}</span></li>
                  ))}</ul>
                ) : <p className="text-sm text-muted-foreground">Sin medicamentos registrados.</p>}
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
