"use client"

import Link from "next/link"
import { ExternalLink } from "lucide-react"
import { Button } from "@/components/ui/button"
import { AgendaVideoProviderIcon } from "@/components/agenda/agenda-video-provider-icon"
import {
  canAutoGenerateVideoLink,
  videoJoinLabel,
  videoToggleLabel,
} from "@/lib/agenda/agenda-video-conference"
import type { AgendaVideoProvider } from "@/lib/agenda/agenda-settings-types"
import { isUltiMeetUrl, meetJoinPath } from "@/lib/meet/meet-url"
import { cn } from "@/lib/utils"

export function AgendaVideoToggle({
  provider,
  enabled,
  onEnabledChange,
  meetUrl,
  disabled = false,
  pending = false,
  compact = false,
  tabIndex,
}: {
  provider: AgendaVideoProvider
  enabled: boolean
  onEnabledChange: (enabled: boolean) => void
  meetUrl?: string
  disabled?: boolean
  pending?: boolean
  compact?: boolean
  tabIndex?: number
}) {
  if (provider === "none") return null

  if (meetUrl) {
    const inAppJoin = provider === "ultimeet" && isUltiMeetUrl(meetUrl)
    const joinHref = inAppJoin ? meetJoinPath(meetUrl) : meetUrl

    return (
      <div className="flex flex-wrap items-center gap-2">
        <Button
          asChild
          variant="outline"
          className={cn("h-9 rounded-full gap-2", compact && "h-8 text-xs")}
        >
          {inAppJoin ? (
            <Link href={joinHref}>
              <AgendaVideoProviderIcon provider={provider} className="size-4" />
              {videoJoinLabel(provider)}
            </Link>
          ) : (
            <a href={joinHref} target="_blank" rel="noopener noreferrer">
              <AgendaVideoProviderIcon provider={provider} className="size-4" />
              {videoJoinLabel(provider)}
              <ExternalLink className="size-3.5 opacity-60" aria-hidden />
            </a>
          )}
        </Button>
        <Button
          type="button"
          variant="ghost"
          className={cn("h-9 rounded-full text-muted-foreground", compact && "h-8 text-xs")}
          disabled={pending}
          onClick={() => onEnabledChange(false)}
        >
          Retirer
        </Button>
      </div>
    )
  }

  const auto = canAutoGenerateVideoLink(provider)

  return (
    <div className="flex flex-col gap-1">
      <Button
        type="button"
        variant={enabled ? "default" : "outline"}
        className={cn(
          "h-9 w-fit rounded-full gap-2",
          compact && "h-8 text-xs",
          enabled && "shadow-sm",
        )}
        tabIndex={tabIndex}
        disabled={disabled || pending}
        onClick={() => onEnabledChange(!enabled)}
      >
        <AgendaVideoProviderIcon provider={provider} className="size-4" />
        {videoToggleLabel(provider, enabled)}
      </Button>
      {enabled && !auto ? (
        <p className="text-[11px] text-muted-foreground">
          Lien généré automatiquement bientôt — ajoutez-le dans le lieu en attendant.
        </p>
      ) : null}
    </div>
  )
}
