import { createClient } from "@/lib/supabase/server";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { FileText, Search, User, Calendar } from "lucide-react";

export const dynamic = "force-dynamic";

export default async function MedicalRecordsPage({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
  const params = await searchParams;
  const search = params.q || "";
  const supabase = await createClient();

  let query = supabase
    .from("patients")
    .select("id, first_name, last_name, date_of_birth, gender, phone")
    .eq("is_active", true)
    .order("last_name")
    .limit(50);

  if (search) {
    query = query.or(`first_name.ilike.%${search}%,last_name.ilike.%${search}%`);
  }

  const { data: patients } = await query;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Expedientes</h1>
        <p className="text-muted-foreground">Selecciona un paciente para ver su expediente clinico.</p>
      </div>

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <form><Input name="q" placeholder="Buscar paciente..." defaultValue={search} className="h-11 pl-10" /></form>
      </div>

      {!patients || patients.length === 0 ? (
        <Card className="flex flex-col items-center justify-center py-16">
          <FileText className="h-12 w-12 text-muted-foreground/40 mb-4" />
          <h3 className="text-lg font-semibold">Sin pacientes registrados</h3>
          <p className="text-sm text-muted-foreground">Registra pacientes para acceder a sus expedientes.</p>
        </Card>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {patients.map((p) => (
            <Link key={p.id} href={`/medical-records/${p.id}`}>
              <Card className="group cursor-pointer transition-all hover:shadow-md hover:border-primary/20">
                <CardContent className="flex items-center gap-3 p-4">
                  <div className="flex h-11 w-11 items-center justify-center rounded-full bg-primary/10 text-primary font-semibold text-sm">
                    {p.first_name?.[0]}{p.last_name?.[0]}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold truncate group-hover:text-primary transition-colors">{p.first_name} {p.last_name}</p>
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      {p.date_of_birth && <span>{p.date_of_birth}</span>}
                      {p.gender && <Badge variant="secondary" className="text-[10px]">{p.gender === "M" ? "M" : p.gender === "F" ? "F" : "O"}</Badge>}
                    </div>
                  </div>
                  <FileText className="h-5 w-5 text-muted-foreground/40 group-hover:text-primary transition-colors" />
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
