"use client"

import type React from "react"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Building2, ChevronsUpDown, LogOut, Plus, Trophy, X, Check } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Wordmark } from "@/components/wordmark"
import { TournamentCard, type Tournament } from "@/components/tournament-card"
import type { TournamentStatus } from "@/components/tournament-status-badge"

type MyOrg = { organization_id: string; name: string; role: string }

type Me = {
  id: string
  email: string
  display_name: string
  preferred_locale: string
  organizations: MyOrg[]
}

type ApiTournament = {
  id: string
  name: string
  status: TournamentStatus
  start_date: string | null
  end_date: string | null
}

function toTournament(t: ApiTournament): Tournament {
  return {
    id: t.id,
    name: t.name,
    status: t.status,
    startDate: t.start_date ?? undefined,
    endDate: t.end_date ?? undefined,
  }
}

// --- Component -------------------------------------------------------------

export function Dashboard() {
  const router = useRouter()
  const [me, setMe] = useState<Me | null>(null)
  const [loadingMe, setLoadingMe] = useState(true)
  const [activeOrgId, setActiveOrgId] = useState<string | null>(null)
  const [tournaments, setTournaments] = useState<Tournament[]>([])
  const [loadingTournaments, setLoadingTournaments] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Hent innlogget bruker + organisasjonsmedlemskap. Ingen gyldig sesjon ->
  // tilbake til innloggingssiden (denne siden krever auth).
  useEffect(() => {
    let cancelled = false
    async function loadMe() {
      try {
        const res = await fetch("/auth/me", { credentials: "include" })
        if (!res.ok) {
          router.replace("/")
          return
        }
        const data: Me = await res.json()
        if (cancelled) return
        setMe(data)
        setActiveOrgId(data.organizations[0]?.organization_id ?? null)
      } catch {
        if (!cancelled) router.replace("/")
      } finally {
        if (!cancelled) setLoadingMe(false)
      }
    }
    void loadMe()
    return () => {
      cancelled = true
    }
  }, [router])

  // Turneringer hentes per valgt organisasjon, ikke i /auth/me-kallet.
  useEffect(() => {
    if (!activeOrgId) {
      setTournaments([])
      return
    }
    let cancelled = false
    async function loadTournaments() {
      setLoadingTournaments(true)
      setError(null)
      try {
        const res = await fetch(`/orgs/${activeOrgId}/tournaments`, { credentials: "include" })
        if (!res.ok) throw new Error(`tournaments: ${res.status}`)
        const data: ApiTournament[] = await res.json()
        if (!cancelled) setTournaments(data.map(toTournament))
      } catch {
        if (!cancelled) setError("Klarte ikke å hente turneringer. Prøv igjen om litt.")
      } finally {
        if (!cancelled) setLoadingTournaments(false)
      }
    }
    void loadTournaments()
    return () => {
      cancelled = true
    }
  }, [activeOrgId])

  async function handleCreateOrg(name: string) {
    setError(null)
    try {
      const res = await fetch("/orgs", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ name }),
      })
      if (!res.ok) throw new Error(`orgs: ${res.status}`)
      const org: { id: string; name: string; role: string } = await res.json()
      setMe((prev) =>
        prev
          ? {
              ...prev,
              organizations: [
                ...prev.organizations,
                { organization_id: org.id, name: org.name, role: org.role },
              ],
            }
          : prev,
      )
      setActiveOrgId(org.id)
    } catch {
      setError("Klarte ikke å opprette organisasjonen. Prøv igjen.")
    }
  }

  async function handleCreateTournament(name: string) {
    if (!activeOrgId) return
    setError(null)
    try {
      const res = await fetch(`/orgs/${activeOrgId}/tournaments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ name }),
      })
      if (!res.ok) throw new Error(`create tournament: ${res.status}`)
      const created: ApiTournament = await res.json()
      setTournaments((prev) => [toTournament(created), ...prev])
    } catch {
      setError("Klarte ikke å opprette turneringen. Prøv igjen.")
    }
  }

  async function handleLogout() {
    try {
      await fetch("/auth/logout", { method: "POST", credentials: "include" })
    } finally {
      router.replace("/")
    }
  }

  if (loadingMe) {
    return (
      <div className="flex min-h-[100dvh] flex-col items-center justify-center gap-4 bg-background">
        <div
          aria-hidden="true"
          className="size-10 animate-spin rounded-full border-4 border-primary/20 border-t-primary"
        />
      </div>
    )
  }

  if (!me) return null // router.replace("/") er allerede utløst

  const activeOrg = me.organizations.find((o) => o.organization_id === activeOrgId) ?? null
  const hasOrg = me.organizations.length > 0 && activeOrg !== null

  return (
    <div className="flex min-h-[100dvh] flex-col bg-background">
      <header className="sticky top-0 z-10 border-b border-border bg-background/80 backdrop-blur">
        <div className="mx-auto flex w-full max-w-3xl items-center justify-between gap-4 px-5 py-4">
          <Wordmark compact />
          <button
            type="button"
            onClick={handleLogout}
            className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-sm font-semibold text-muted-foreground transition-colors hover:text-foreground"
          >
            <LogOut aria-hidden="true" className="size-4" />
            Logg ut
          </button>
        </div>
      </header>

      <main className="mx-auto w-full max-w-3xl flex-1 px-5 py-8 sm:py-10">
        {error && (
          <p role="alert" className="mb-4 text-sm font-medium text-destructive">
            {error}
          </p>
        )}

        {hasOrg && activeOrg ? (
          <OrganizationView
            org={activeOrg}
            orgs={me.organizations}
            tournaments={tournaments}
            loadingTournaments={loadingTournaments}
            onSelectOrg={setActiveOrgId}
            onCreateTournament={handleCreateTournament}
          />
        ) : (
          <CreateOrganizationState onCreate={handleCreateOrg} />
        )}
      </main>
    </div>
  )
}

// --- State A: no organization ---------------------------------------------

function CreateOrganizationState({ onCreate }: { onCreate: (name: string) => void }) {
  const [name, setName] = useState("")
  const valid = name.trim().length >= 2

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!valid) return
    onCreate(name.trim())
    setName("")
  }

  return (
    <div className="mx-auto flex max-w-md flex-col items-center gap-6 pt-6 text-center sm:pt-12">
      <div className="flex size-16 items-center justify-center rounded-2xl bg-primary/15">
        <Building2 aria-hidden="true" className="size-8 text-primary" />
      </div>

      <div className="flex flex-col gap-2">
        <h1 className="text-2xl font-extrabold tracking-tight text-foreground text-balance">
          Du har ingen organisasjon ennå
        </h1>
        <p className="text-sm leading-relaxed text-muted-foreground text-pretty">
          En organisasjon er golfklubben eller bedriften som arrangerer turneringen. Opprett en for
          å komme i gang.
        </p>
      </div>

      <form
        onSubmit={handleSubmit}
        className="flex w-full flex-col gap-4 rounded-3xl border border-border bg-card p-6 text-left shadow-lg shadow-black/5"
      >
        <div className="flex flex-col gap-2">
          <Label htmlFor="org-name" className="text-sm font-semibold">
            Navn på organisasjon
          </Label>
          <Input
            id="org-name"
            autoFocus
            placeholder="F.eks. Oslo Golfklubb"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="h-14 rounded-2xl text-base"
          />
        </div>
        <Button
          type="submit"
          disabled={!valid}
          className="h-14 rounded-2xl text-base font-bold shadow-sm"
        >
          Opprett organisasjon
        </Button>
      </form>
    </div>
  )
}

// --- State B: has organization(s) -----------------------------------------

function OrganizationView({
  org,
  orgs,
  tournaments,
  loadingTournaments,
  onSelectOrg,
  onCreateTournament,
}: {
  org: MyOrg
  orgs: MyOrg[]
  tournaments: Tournament[]
  loadingTournaments: boolean
  onSelectOrg: (id: string) => void
  onCreateTournament: (name: string) => void
}) {
  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        {orgs.length > 1 ? (
          <OrganizationSwitcher org={org} orgs={orgs} onSelectOrg={onSelectOrg} />
        ) : (
          <div className="flex items-center gap-3">
            <div className="flex size-11 items-center justify-center rounded-xl bg-primary/15">
              <Building2 aria-hidden="true" className="size-5 text-primary" />
            </div>
            <div className="flex flex-col">
              <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Organisasjon
              </span>
              <span className="text-lg font-extrabold tracking-tight text-foreground">
                {org.name}
              </span>
            </div>
          </div>
        )}

        <NewTournamentControl onCreate={onCreateTournament} />
      </div>

      <section className="flex flex-col gap-3" aria-label="Turneringer">
        {loadingTournaments ? (
          <div className="flex justify-center py-12">
            <div
              aria-hidden="true"
              className="size-8 animate-spin rounded-full border-4 border-primary/20 border-t-primary"
            />
          </div>
        ) : tournaments.length > 0 ? (
          tournaments.map((t) => <TournamentCard key={t.id} tournament={t} />)
        ) : (
          <EmptyTournamentState orgName={org.name} />
        )}
      </section>
    </div>
  )
}

function OrganizationSwitcher({
  org,
  orgs,
  onSelectOrg,
}: {
  org: MyOrg
  orgs: MyOrg[]
  onSelectOrg: (id: string) => void
}) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger className="flex items-center gap-3 rounded-2xl border border-border bg-card px-3 py-2.5 text-left shadow-sm shadow-black/5 transition-colors hover:bg-accent/50">
        <div className="flex size-11 items-center justify-center rounded-xl bg-primary/15">
          <Building2 aria-hidden="true" className="size-5 text-primary" />
        </div>
        <div className="flex flex-col">
          <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
            Organisasjon
          </span>
          <span className="text-lg font-extrabold tracking-tight text-foreground">
            {org.name}
          </span>
        </div>
        <ChevronsUpDown aria-hidden="true" className="ml-1 size-4 text-muted-foreground" />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-64 rounded-2xl p-1.5">
        {orgs.map((o) => (
          <DropdownMenuItem
            key={o.organization_id}
            onClick={() => onSelectOrg(o.organization_id)}
            className="flex cursor-pointer items-center justify-between gap-2 rounded-xl px-3 py-2.5 text-sm font-semibold"
          >
            {o.name}
            {o.organization_id === org.organization_id && (
              <Check aria-hidden="true" className="size-4 text-primary" />
            )}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

function NewTournamentControl({ onCreate }: { onCreate: (name: string) => void }) {
  const [open, setOpen] = useState(false)
  const [name, setName] = useState("")
  const valid = name.trim().length >= 2

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!valid) return
    onCreate(name.trim())
    setName("")
    setOpen(false)
  }

  if (!open) {
    return (
      <Button
        type="button"
        onClick={() => setOpen(true)}
        className="h-12 shrink-0 rounded-2xl text-base font-bold shadow-sm"
      >
        <Plus aria-hidden="true" className="size-5" />
        Ny turnering
      </Button>
    )
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="flex w-full items-center gap-2 rounded-2xl border border-border bg-card p-2 shadow-sm shadow-black/5 sm:w-auto"
    >
      <Input
        autoFocus
        placeholder="Navn på turnering"
        value={name}
        onChange={(e) => setName(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === "Escape") setOpen(false)
        }}
        className="h-10 min-w-0 flex-1 rounded-xl text-base sm:w-56"
      />
      <Button
        type="submit"
        disabled={!valid}
        size="icon"
        className="size-10 shrink-0 rounded-xl"
        aria-label="Opprett turnering"
      >
        <Check aria-hidden="true" className="size-5" />
      </Button>
      <Button
        type="button"
        variant="ghost"
        size="icon"
        onClick={() => setOpen(false)}
        className="size-10 shrink-0 rounded-xl text-muted-foreground"
        aria-label="Avbryt"
      >
        <X aria-hidden="true" className="size-5" />
      </Button>
    </form>
  )
}

function EmptyTournamentState({ orgName }: { orgName: string }) {
  return (
    <div className="flex flex-col items-center gap-3 rounded-3xl border border-dashed border-border bg-card/50 px-6 py-12 text-center">
      <div className="flex size-14 items-center justify-center rounded-2xl bg-muted">
        <Trophy aria-hidden="true" className="size-7 text-muted-foreground" />
      </div>
      <div className="flex flex-col gap-1">
        <h2 className="text-base font-bold text-foreground text-balance">
          Ingen turneringer ennå i {orgName}
        </h2>
        <p className="text-sm leading-relaxed text-muted-foreground text-pretty">
          Trykk på «Ny turnering» for å opprette den første.
        </p>
      </div>
    </div>
  )
}
