"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
} from "@/components/ui/card"
import {
  deriveRuntimeConfig,
  ultiSpaceOrigin,
  type RuntimeConfig,
} from "@/lib/runtime-config"
import { persistNativeRuntimeConfig } from "@/lib/runtime-config/native"
import { cn } from "@/lib/utils"

const CARD_CLASS = cn(
  "w-full gap-4 border-0 bg-transparent px-4 py-6 shadow-none",
  "sm:gap-5 sm:bg-card sm:px-8 sm:py-8"
)

/**
 * Pre-login server picker for the native shells: choose the hosted UltiSpace or
 * point at a self-hosted instance. OIDC discovery derives the full runtime
 * config, which is persisted to the shared secure store (cross-app SSO).
 */
export function ServerPicker({
  onSelected,
}: {
  onSelected: (cfg: RuntimeConfig) => void
}) {
  const [mode, setMode] = useState<"choose" | "self">("choose")
  const [url, setUrl] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function select(rawOrigin: string, label?: string) {
    setLoading(true)
    setError(null)
    try {
      const cfg = await deriveRuntimeConfig(rawOrigin, { label })
      await persistNativeRuntimeConfig(cfg)
      onSelected(cfg)
    } catch (err) {
      setError(err instanceof Error ? err.message : "Connexion impossible.")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex flex-1 flex-col items-center justify-center px-4">
      <div className="mx-auto w-full max-w-sm">
        <Card className={CARD_CLASS}>
          <CardHeader className="gap-3 px-0 text-center">
            <div className="flex flex-col items-center gap-3 py-2">
              <img
                src="/ultisuite-mark.svg"
                alt=""
                width={64}
                height={64}
                className="h-14 w-14 select-none"
                aria-hidden
              />
              <span className="text-xl font-bold tracking-tight">
                Ulti<span className="text-[#4285F4]">Suite</span>
              </span>
            </div>
            <CardDescription>
              Choisis ton serveur pour te connecter.
            </CardDescription>
            {error ? (
              <p className="text-sm text-destructive" role="alert">
                {error}
              </p>
            ) : null}
          </CardHeader>

          <CardContent className="flex flex-col gap-3 px-0">
            {mode === "choose" ? (
              <>
                <Button
                  type="button"
                  size="lg"
                  className="w-full"
                  disabled={loading}
                  onClick={() => void select(ultiSpaceOrigin(), "UltiSpace")}
                >
                  {loading ? "Connexion…" : "UltiSpace (hébergé)"}
                </Button>
                <Button
                  type="button"
                  size="lg"
                  variant="outline"
                  className="w-full"
                  disabled={loading}
                  onClick={() => setMode("self")}
                >
                  Instance auto-hébergée
                </Button>
              </>
            ) : (
              <form
                className="flex flex-col gap-3"
                onSubmit={(e) => {
                  e.preventDefault()
                  if (url.trim()) void select(url.trim())
                }}
              >
                <Input
                  type="url"
                  inputMode="url"
                  autoCapitalize="none"
                  autoCorrect="off"
                  placeholder="https://mail.exemple.org"
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  disabled={loading}
                />
                <Button
                  size="lg"
                  type="submit"
                  className="w-full"
                  disabled={loading || !url.trim()}
                >
                  {loading ? "Connexion…" : "Continuer"}
                </Button>
                <Button
                  type="button"
                  variant="ghost"
                  className="w-full"
                  disabled={loading}
                  onClick={() => setMode("choose")}
                >
                  Retour
                </Button>
              </form>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
