import { getDashboardStats, getRevenueChart, getUpcomingAppointments, getRecentPatients } from "@/lib/actions/dashboard";
import { RevenueChart } from "@/components/dashboard/revenue-chart";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Users, Calendar, Receipt, Package, TrendingUp, Clock, UserPlus, AlertTriangle, Phone } from "lucide-react";
import Link from "next/link";
import { format } from "date-fns";
import { es } from "date-fns/locale";

export const dynamic = "force-dynamic";

export default async function DashboardPage() {
  const [stats, chartData, upcomingAppts, recentPatients] = await Promise.all([
    getDashboardStats(),
    getRevenueChart(),
    getUpcomingAppointments(),
    getRecentPatients(),
  ]);

  const statCards = [
    { title: "Pacientes", value: stats.totalPatients.toString(), description: "Total registrados", icon: Users, color: "bg-blue-500/10 text-blue-600" },
    { title: "Citas hoy", value: stats.todayAppointments.toString(), description: "Programadas", icon: Calendar, color: "bg-emerald-500/10 text-emerald-600" },
    { title: "Ingresos del mes", value: `$${stats.monthRevenue.toLocaleString("es-MX", { minimumFractionDigits: 0 })}`, description: `${stats.totalInvoices} facturas`, icon: Receipt, color: "bg-violet-500/10 text-violet-600" },
    { title: "Inventario", value: stats.totalProducts.toString(), description: stats.lowStockCount > 0 ? `${stats.lowStockCount} con stock bajo` : "Stock OK", icon: Package, color: stats.lowStockCount > 0 ? "bg-amber-500/10 text-amber-600" : "bg-emerald-500/10 text-emerald-600" },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Dashboard</h1>
        <p className="text-muted-foreground">Panel de administracion de tu clinica.</p>
      </div>

      {/* Stats */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {statCards.map((stat) => (
          <Card key={stat.title} className="relative overflow-hidden">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">{stat.title}</CardTitle>
              <div className={`flex h-9 w-9 items-center justify-center rounded-lg ${stat.color}`}>
                <stat.icon className="h-5 w-5" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold">{stat.value}</div>
              <p className="mt-1 text-xs text-muted-foreground">{stat.description}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Chart + Upcoming */}
      <div className="grid gap-4 lg:grid-cols-3">
        <RevenueChart data={chartData} />

        {/* Upcoming Appointments */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-base">Proximas citas</CardTitle>
            <Link href="/appointments"><Button variant="ghost" size="sm" className="text-xs">Ver todo</Button></Link>
          </CardHeader>
          <CardContent className="space-y-3">
            {upcomingAppts.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">Sin citas pendientes hoy.</p>
            ) : (
              upcomingAppts.map((apt: any) => (
                <div key={apt.id} className="flex items-center gap-3">
                  <div className="text-center min-w-[40px]">
                    <div className="text-sm font-bold">{format(new Date(apt.starts_at), "HH:mm")}</div>
                  </div>
                  <div className="h-8 w-px bg-border" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium truncate">{apt.patient?.first_name} {apt.patient?.last_name}</p>
                    <p className="text-xs text-muted-foreground truncate">Dr. {apt.doctor?.full_name}</p>
                  </div>
                  <Badge variant="outline" className="text-[10px] shrink-0">
                    {apt.status === "confirmed" ? "Confirmada" : "Pendiente"}
                  </Badge>
                </div>
              ))
            )}
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions + Recent Patients */}
      <div className="grid gap-4 lg:grid-cols-2">
        {/* Quick Actions */}
        <Card>
          <CardHeader><CardTitle className="text-base">Acciones rapidas</CardTitle></CardHeader>
          <CardContent className="grid grid-cols-2 gap-3">
            {[
              { title: "Nuevo paciente", icon: UserPlus, href: "/patients/new", color: "bg-blue-500/10 text-blue-600" },
              { title: "Agendar cita", icon: Clock, href: "/appointments", color: "bg-emerald-500/10 text-emerald-600" },
              { title: "Nueva factura", icon: TrendingUp, href: "/billing/new", color: "bg-violet-500/10 text-violet-600" },
              { title: "Stock bajo", icon: AlertTriangle, href: "/inventory", color: "bg-amber-500/10 text-amber-600" },
            ].map((action) => (
              <Link key={action.title} href={action.href}>
                <div className="flex items-center gap-3 rounded-lg border p-3 transition-all hover:shadow-sm hover:border-primary/20 cursor-pointer">
                  <div className={`flex h-9 w-9 items-center justify-center rounded-lg ${action.color}`}>
                    <action.icon className="h-4 w-4" />
                  </div>
                  <span className="text-sm font-medium">{action.title}</span>
                </div>
              </Link>
            ))}
          </CardContent>
        </Card>

        {/* Recent Patients */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-base">Pacientes recientes</CardTitle>
            <Link href="/patients"><Button variant="ghost" size="sm" className="text-xs">Ver todo</Button></Link>
          </CardHeader>
          <CardContent className="space-y-3">
            {recentPatients.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">Sin pacientes registrados.</p>
            ) : (
              recentPatients.map((p: any) => (
                <Link key={p.id} href={`/patients/${p.id}`}>
                  <div className="flex items-center gap-3 rounded-lg p-2 -mx-2 transition-colors hover:bg-muted/50 cursor-pointer">
                    <div className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/10 text-primary font-semibold text-xs">
                      {p.first_name?.[0]}{p.last_name?.[0]}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium truncate">{p.first_name} {p.last_name}</p>
                      {p.phone && <p className="text-xs text-muted-foreground flex items-center gap-1"><Phone className="h-3 w-3" />{p.phone}</p>}
                    </div>
                  </div>
                </Link>
              ))
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
