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

export const dynamic = "force-dynamic";

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

  let query = supabase
    .from("patients")
    .select("*")
    .eq("is_active", true)
    .order("created_at", { ascending: false })
    .limit(50);

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

  const { data: patients } = await query;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Pacientes</h1>
          <p className="text-muted-foreground">
            Gestiona el directorio de pacientes de tu clinica.
          </p>
        </div>
        <Link href="/patients/new">
          <Button className="gap-2">
            <UserPlus className="h-4 w-4" /> Nuevo paciente
          </Button>
        </Link>
      </div>

      {/* Search */}
      <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 por nombre, telefono..."
            defaultValue={search}
            className="h-11 pl-10"
          />
        </form>
      </div>

      {/* Patient Cards */}
      {!patients || patients.length === 0 ? (
        <Card className="flex flex-col items-center justify-center py-16">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/10 mb-4">
            <UserPlus className="h-8 w-8 text-primary" />
          </div>
          <h3 className="text-lg font-semibold">Sin pacientes</h3>
          <p className="mt-1 text-sm text-muted-foreground">
            Registra tu primer paciente para comenzar.
          </p>
          <Link href="/patients/new" className="mt-4">
            <Button>Registrar paciente</Button>
          </Link>
        </Card>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {patients.map((patient) => (
            <Link key={patient.id} href={`/patients/${patient.id}`}>
              <Card className="group cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/20">
                <CardContent className="p-4">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <div className="flex h-11 w-11 items-center justify-center rounded-full bg-primary/10 font-semibold text-primary text-sm">
                        {patient.first_name?.[0]}
                        {patient.last_name?.[0]}
                      </div>
                      <div>
                        <p className="font-semibold group-hover:text-primary transition-colors">
                          {patient.first_name} {patient.last_name}
                        </p>
                        {patient.gender && (
                          <Badge variant="secondary" className="mt-0.5 text-xs">
                            {patient.gender === "M"
                              ? "Masculino"
                              : patient.gender === "F"
                                ? "Femenino"
                                : "Otro"}
                          </Badge>
                        )}
                      </div>
                    </div>
                  </div>
                  <div className="mt-3 space-y-1.5 text-xs text-muted-foreground">
                    {patient.phone && (
                      <div className="flex items-center gap-2">
                        <Phone className="h-3.5 w-3.5" />
                        {patient.phone}
                      </div>
                    )}
                    {patient.email && (
                      <div className="flex items-center gap-2">
                        <Mail className="h-3.5 w-3.5" />
                        {patient.email}
                      </div>
                    )}
                    {patient.date_of_birth && (
                      <div className="flex items-center gap-2">
                        <Calendar className="h-3.5 w-3.5" />
                        {patient.date_of_birth}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
