"use client"

import { useState } from "react"
import { createClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Spinner } from "@/components/ui/spinner"
import { BarChart3, Building2, CalendarDays, Layers, LogIn } from "lucide-react"

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleGoogleSignIn = async () => {
    setError(null)
    setIsLoading(true)

    try {
      const supabase = createClient()
      const redirectTo = `${window.location.origin}/auth/callback?next=/dashboard`

      const { error: signInError } = await supabase.auth.signInWithOAuth({
        provider: "google",
        options: {
          redirectTo,
          queryParams: {
            prompt: "select_account",
          },
        },
      })

      if (signInError) {
        throw signInError
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Error al iniciar sesion")
      setIsLoading(false)
    }
  }

  return (
    <main className="min-h-screen bg-[var(--ds-background-layout-default)] text-[var(--ds-text-neutral-default)]">
      <div className="mx-auto grid min-h-screen w-full max-w-[1040px] items-center gap-[var(--ds-space-4x)] px-[var(--ds-grid-margin-s)] py-[var(--ds-space-5x)] sm:px-[var(--ds-grid-margin-m)] lg:grid-cols-[1.15fr_0.85fr] xl:px-[var(--ds-grid-margin-xl)]">
        <section className="order-1 rounded-[var(--ds-radius-l)] bg-[var(--ds-blueprimary-100)] p-[var(--ds-space-5x)] shadow-[var(--ds-shadow-4dp)] lg:order-1">
          <p className="ds-type-global-xs ds-type-semibold text-[var(--ds-brand-400)]">
            HU Books
          </p>
          <h1 className="mt-[var(--ds-space-2x)] ds-type-global-xl ds-type-semibold text-[var(--ds-blueprimary-800)]">
            Espacios y recursos bajo control
          </h1>
          <p className="mt-[var(--ds-space-2x)] ds-type-global-s text-[var(--ds-text-neutral-lighter)]">
            Una solución para organizar salas y activos limitados con visibilidad clara y decisiones
            basadas en uso real.
          </p>

          <ul className="mt-[var(--ds-space-4x)] space-y-[var(--ds-space-2x)]">
            <li className="flex items-start gap-[var(--ds-space-15x)]">
              <Layers className="mt-[var(--ds-space-05x)] h-[var(--ds-space-2x)] w-[var(--ds-space-2x)] shrink-0 text-[var(--ds-brand-400)]" />
              <p className="ds-type-global-s text-[var(--ds-blueprimary-800)]">
                Gestiona recursos escasos de la organización: ubicaciones, tipos y disponibilidad en
                un solo lugar.
              </p>
            </li>
            <li className="flex items-start gap-[var(--ds-space-15x)]">
              <BarChart3 className="mt-[var(--ds-space-05x)] h-[var(--ds-space-2x)] w-[var(--ds-space-2x)] shrink-0 text-[var(--ds-brand-400)]" />
              <p className="ds-type-global-s text-[var(--ds-blueprimary-800)]">
                Visualiza ocupación y métricas de uso para detectar picos, huecos y oportunidades de
                optimización.
              </p>
            </li>
            <li className="flex items-start gap-[var(--ds-space-15x)]">
              <CalendarDays className="mt-[var(--ds-space-05x)] h-[var(--ds-space-2x)] w-[var(--ds-space-2x)] shrink-0 text-[var(--ds-brand-400)]" />
              <p className="ds-type-global-s text-[var(--ds-blueprimary-800)]">
                Reservas alineadas a reglas y calendario: menos choques, más eficiencia en el día a
                día.
              </p>
            </li>
          </ul>
        </section>

        <Card className="order-2 w-full rounded-[var(--ds-radius-l)] border-[var(--ds-neutral-200)] bg-white py-[var(--ds-space-4x)] shadow-[var(--ds-shadow-4dp)] lg:order-2 lg:max-w-[440px] lg:justify-self-end">
          <CardHeader className="px-[var(--ds-space-4x)] text-left">
            <div className="mb-[var(--ds-space-2x)] flex h-[var(--ds-space-5x)] w-[var(--ds-space-5x)] items-center justify-center rounded-[var(--ds-radius-m)] bg-[var(--ds-blueprimary-100)]">
              <Building2 className="h-[var(--ds-space-3x)] w-[var(--ds-space-3x)] text-[var(--ds-brand-400)]" />
            </div>
            <CardTitle className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
              Ingreso
            </CardTitle>
            <CardDescription className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
              Usa tu cuenta de Google para entrar a HU Rooms.
            </CardDescription>
          </CardHeader>
          <CardContent className="px-[var(--ds-space-4x)]">
            <div className="space-y-[var(--ds-space-3x)]">
              {error && (
                <Alert
                  variant="destructive"
                  className="rounded-[var(--ds-radius-m)] border-[var(--ds-error-700)] bg-[var(--ds-error-100)]"
                >
                  <AlertDescription className="ds-type-global-xs text-[var(--ds-error-700)]">
                    {error}
                  </AlertDescription>
                </Alert>
              )}

              <Button
                type="button"
                onClick={handleGoogleSignIn}
                className="h-11 w-full rounded-[var(--ds-radius-m)] bg-[var(--ds-brand-400)] ds-type-global-s ds-type-semibold text-white hover:bg-[var(--ds-brand-500)]"
                disabled={isLoading}
              >
                {isLoading ? (
                  <>
                    <Spinner className="mr-[var(--ds-space-1x)]" />
                    Redirigiendo...
                  </>
                ) : (
                  <>
                    <LogIn className="mr-[var(--ds-space-1x)] h-4 w-4" />
                    Continuar con Google
                  </>
                )}
              </Button>

              <p className="text-center ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                Demo PoC: autenticacion por SSO de Google y provision automatica de perfil.
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </main>
  )
}
