import { createClient } from "@/lib/supabase/server"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { DashboardCheckInButton } from "@/components/dashboard/dashboard-check-in-button"
import Link from "next/link"
import { Calendar, Clock, ArrowRight } from "lucide-react"
import { DynamicIcon } from "@/components/ui/dynamic-icon"
import { format } from "date-fns"
import { es } from "date-fns/locale"
import { getResourceLocationPathLabel } from "@/lib/resources/location"
import type { Database } from "@/lib/supabase/database.types"
import { isCheckInWindowOpen, resolveCheckInWindowMinutes } from "@/lib/reservations/policies"

type ReservationRow = Database["public"]["Tables"]["reservations"]["Row"]
type ResourceRow = Database["public"]["Tables"]["resources"]["Row"]

type DashboardReservation = ReservationRow & {
  resources: (Pick<ResourceRow, "name" | "floor" | "metadata"> & {
    resource_types: { id: string; name: string; slug: string; icon: string | null } | null
  }) | null
}

export default async function DashboardPage() {
  const supabase = await createClient()
  
  const { data: { user } } = await supabase.auth.getUser()
  
  // Get user's upcoming reservations
  const { data: upcomingReservations } = await supabase
    .from("reservations")
    .select(`
      *,
      resources (
        name,
        floor,
        resource_types (id, name, slug, icon)
      )
    `)
    .eq("user_id", user?.id)
    .in("status", ["confirmed", "checked_in"])
    .gte("start_at", new Date().toISOString())
    .order("start_at", { ascending: true })
    .limit(5)

  // Get resource type counts
  const { data: resourceTypes } = await supabase
    .from("resource_types")
    .select("*")
    .eq("is_active", true)

  const { data: policiesData } = await supabase
    .from("resource_policies")
    .select("*")

  const fullName = (user?.user_metadata?.full_name as string | undefined) ?? null
  const typedUpcomingReservations = (upcomingReservations ?? []) as DashboardReservation[]
  const typedPolicies = (policiesData ?? []) as Database["public"]["Tables"]["resource_policies"]["Row"][]

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "confirmed":
        return (
          <Badge className="rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-blueprimary-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-blueprimary-800)]">
            Confirmada
          </Badge>
        )
      case "checked_in":
        return (
          <Badge className="rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-success-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-success-700)] hover:bg-[var(--ds-success-100)]">
            Check-in
          </Badge>
        )
      default:
        return (
          <Badge
            variant="outline"
            className="rounded-[var(--ds-radius-s)] border-[var(--ds-neutral-200)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]"
          >
            {status}
          </Badge>
        )
    }
  }

  return (
    <div className="space-y-[var(--ds-space-4x)]">
      <section className="rounded-[var(--ds-radius-l)] bg-[var(--ds-blueprimary-100)] p-[var(--ds-space-4x)] shadow-[var(--ds-shadow-4dp)]">
        <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-blueprimary-800)]">
          Hola, {fullName || user?.email?.split("@")[0]}
        </h1>
        <p className="mt-[var(--ds-space-1x)] ds-type-global-s text-[var(--ds-text-neutral-lighter)]">
          Bienvenido al sistema de reservas de espacios
        </p>
      </section>

      <section className="space-y-[var(--ds-space-2x)]">
        <h2 className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
          Reserva rapido
        </h2>
        <div className="grid gap-[var(--ds-space-2x)] md:grid-cols-2 lg:grid-cols-3">
        {resourceTypes?.map((type) => (
          <Card
            key={type.id}
            className="rounded-[var(--ds-radius-l)] border-[var(--ds-neutral-200)] bg-white py-[var(--ds-space-2x)] shadow-[var(--ds-shadow-4dp)] transition-shadow hover:shadow-[var(--ds-shadow-8dp)]"
          >
            <CardHeader className="flex flex-row items-center justify-between px-[var(--ds-space-3x)] pb-[var(--ds-space-05x)]">
              <CardTitle className="ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
                {type.name}
              </CardTitle>
              <div className="rounded-[var(--ds-radius-m)] bg-[var(--ds-blueprimary-100)] p-[var(--ds-space-1x)] text-[var(--ds-brand-400)]">
                <DynamicIcon name={type.icon} className="h-5 w-5" />
              </div>
            </CardHeader>
            <CardContent className="px-[var(--ds-space-3x)]">
              <p className="mb-[var(--ds-space-1x)] min-h-[var(--ds-space-3x)] ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                {type.description ?? ""}
              </p>
              <Button
                asChild
                size="sm"
                className="h-10 w-full rounded-[var(--ds-radius-m)] bg-[var(--ds-brand-400)] ds-type-global-xs ds-type-semibold text-white hover:bg-[var(--ds-brand-500)]"
              >
                <Link href={`/reservations?type=${encodeURIComponent(type.slug)}`}>
                  Reservar
                  <ArrowRight className="ml-[var(--ds-space-2x)] h-4 w-4" />
                </Link>
              </Button>
            </CardContent>
          </Card>
        ))}
        </div>
      </section>

      <Card className="rounded-[var(--ds-radius-l)] border-[var(--ds-neutral-200)] bg-white py-[var(--ds-space-3x)] shadow-[var(--ds-shadow-4dp)]">
        <CardHeader className="flex flex-row items-center justify-between px-[var(--ds-space-3x)]">
          <div>
            <CardTitle className="ds-type-global-m ds-type-semibold text-[var(--ds-text-neutral-default)]">
              Proximas Reservas
            </CardTitle>
            <CardDescription className="mt-[var(--ds-space-05x)] ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
              Tus reservas confirmadas
            </CardDescription>
          </div>
          <Button
            variant="outline"
            asChild
            className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs text-[var(--ds-text-neutral-default)]"
          >
            <Link href="/reservations/my-reservations">Ver todas</Link>
          </Button>
        </CardHeader>
        <CardContent className="px-[var(--ds-space-3x)]">
          {typedUpcomingReservations.length === 0 ? (
            <div className="py-[var(--ds-space-5x)] text-center text-[var(--ds-text-neutral-lighter)]">
              <Calendar className="mx-auto mb-[var(--ds-space-2x)] h-[var(--ds-space-5x)] w-[var(--ds-space-5x)] opacity-50" />
              <p className="ds-type-global-s">No tienes reservas proximas</p>
              <p className="mt-[var(--ds-space-05x)] ds-type-global-xs">
                Reserva un espacio para comenzar
              </p>
            </div>
          ) : (
            <div className="space-y-[var(--ds-space-2x)]">
              {typedUpcomingReservations.map((reservation) => {
                const resourceTypeId = reservation.resources?.resource_types?.id ?? null
                const checkInWindowMinutes = resolveCheckInWindowMinutes({
                  resourceId: reservation.resource_id,
                  resourceTypeId,
                  policies: typedPolicies,
                })
                const canCheckIn = reservation.status === "confirmed" &&
                  isCheckInWindowOpen({
                    startAt: reservation.start_at,
                    endAt: reservation.end_at,
                    now: new Date(),
                    windowMinutes: checkInWindowMinutes,
                  })

                return (
                  <div
                    key={reservation.id}
                    className="flex items-center justify-between rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-200)] bg-white p-[var(--ds-space-2x)]"
                  >
                    <div className="flex items-center gap-4">
                      <div className="rounded-[var(--ds-radius-m)] bg-[var(--ds-blueprimary-100)] p-[var(--ds-space-1x)] text-[var(--ds-blueprimary-800)]">
                        <DynamicIcon name={reservation.resources?.resource_types?.icon} className="h-5 w-5" />
                      </div>
                      <div>
                        <p className="ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
                          {reservation.resources?.name}
                        </p>
                        <div className="mt-[var(--ds-space-05x)] flex items-center gap-[var(--ds-space-1x)] ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                          <Clock className="h-3 w-3 shrink-0" />
                          <span>
                            {format(new Date(reservation.start_at), "EEEE d 'de' MMMM, HH:mm", {
                              locale: es,
                            })}
                            {" - "}
                            {format(new Date(reservation.end_at), "HH:mm", { locale: es })}
                          </span>
                        </div>
                        <p className="mt-[var(--ds-space-025x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                          {getResourceLocationPathLabel(reservation.resources) ??
                            reservation.resources?.floor ??
                            "Sin ubicacion jerarquica"}
                          {reservation.resources?.floor &&
                            getResourceLocationPathLabel(reservation.resources) &&
                            ` • ${reservation.resources.floor}`}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-[var(--ds-space-1x)]">
                      {getStatusBadge(reservation.status || "")}
                      {canCheckIn && (
                        <DashboardCheckInButton
                          reservationId={reservation.id}
                          className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs text-[var(--ds-text-neutral-default)]"
                        />
                      )}
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
