"use client"

import { useEffect, useRef, type RefObject } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { Camera, ChevronDown, ChevronUp, LogOut, Plus, X } from "lucide-react"
import { AccountAvatar } from "@/components/gmail/account-avatar"
import { Button } from "@/components/ui/button"
import type { ApiMailAccount } from "@/lib/api/types"
import { useMailAccounts } from "@/lib/api/hooks/use-mail-queries"
import { useChromeIdentity } from "@/lib/hooks/use-chrome-identity"
import { buildOidcLoginUrl } from "@/lib/auth/login-url"
import {
  useAccountStore,
  useSignOutAll,
} from "@/lib/stores/account-store"

interface AccountSwitcherDropdownProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  containerRef: RefObject<HTMLElement | null>
}

function AccountRow({
  account,
  onSelect,
}: {
  account: ApiMailAccount
  onSelect: () => void
}) {
  return (
    <button
      type="button"
      onClick={onSelect}
      className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors hover:bg-accent"
    >
      <AccountAvatar account={account} size="sm" />
      <div className="min-w-0 flex-1">
        <p className="truncate text-sm font-medium text-foreground">
          {account.name}
        </p>
        <p className="truncate text-xs text-muted-foreground">{account.email}</p>
      </div>
    </button>
  )
}

export function AccountSwitcherDropdown({
  open,
  onOpenChange,
  containerRef,
}: AccountSwitcherDropdownProps) {
  const panelRef = useRef<HTMLDivElement>(null)
  const pathname = usePathname()
  const identity = useChromeIdentity()
  const otherAccountsExpanded = useAccountStore((s) => s.otherAccountsExpanded)
  const setActiveAccountId = useAccountStore((s) => s.setActiveAccountId)
  const toggleOtherAccountsExpanded = useAccountStore(
    (s) => s.toggleOtherAccountsExpanded,
  )
  const signOutAll = useSignOutAll()

  const { data: accounts } = useMailAccounts()
  const mailAccounts = accounts ?? []
  const hasMultipleMailAccounts = mailAccounts.length > 1

  const firstName = identity?.firstName ?? ""
  const addAccountHref = buildOidcLoginUrl({
    returnTo: pathname || "/mail/inbox",
    intent: "add_account",
  })

  useEffect(() => {
    if (!open) return
    function handleClickOutside(event: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        onOpenChange(false)
      }
    }
    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") onOpenChange(false)
    }
    document.addEventListener("mousedown", handleClickOutside)
    document.addEventListener("keydown", handleEscape)
    return () => {
      document.removeEventListener("mousedown", handleClickOutside)
      document.removeEventListener("keydown", handleEscape)
    }
  }, [open, onOpenChange, containerRef])

  if (!open || !identity) return null

  const handleSelectAccount = (id: string) => {
    setActiveAccountId(id)
    onOpenChange(false)
  }

  const handleSignOut = () => {
    void signOutAll()
    onOpenChange(false)
  }

  return (
    <div
      ref={panelRef}
      role="dialog"
      aria-label="Comptes connectés"
      className="absolute right-0 top-12 z-50 w-[min(100vw-1rem,356px)] overflow-hidden rounded-[28px] bg-mail-surface-elevated text-foreground shadow-[0_4px_16px_rgba(0,0,0,0.35)] border border-border"
    >
      <div className="relative px-4 pb-3 pt-4">
        <p className="truncate pr-8 text-center text-sm text-foreground">
          {identity.email}
        </p>
        <Button
          type="button"
          variant="ghost"
          size="icon"
          className="absolute right-2 top-2 size-8 text-muted-foreground hover:bg-accent"
          aria-label="Fermer"
          onClick={() => onOpenChange(false)}
        >
          <X className="size-4" />
        </Button>

        <div className="mt-4 flex flex-col items-center">
          <div className="relative">
            <AccountAvatar
              account={{ name: identity.name, email: identity.email }}
              size="lg"
            />
            <span className="absolute bottom-0 right-0 flex size-7 items-center justify-center rounded-full border-2 border-border bg-mail-surface text-muted-foreground shadow-sm">
              <Camera className="size-3.5" aria-hidden />
            </span>
          </div>
          <h2 className="mt-3 text-xl font-normal text-foreground">
            Bonjour {firstName} !
          </h2>
          <Button
            type="button"
            variant="outline"
            className="mt-4 h-9 rounded-full border-border bg-transparent px-5 text-sm font-medium text-primary hover:bg-accent hover:text-primary"
            asChild
          >
            <Link href="/compte" onClick={() => onOpenChange(false)}>
              Gérer votre compte
            </Link>
          </Button>
        </div>
      </div>

      <div className="px-3 pb-3">
        {hasMultipleMailAccounts ? (
          <div className="overflow-hidden rounded-2xl border border-border bg-mail-surface">
            <button
              type="button"
              onClick={toggleOtherAccountsExpanded}
              className="flex w-full items-center justify-between px-4 py-3 text-left text-sm text-foreground hover:bg-accent"
            >
              <span>
                {otherAccountsExpanded
                  ? "Masquer les comptes mail"
                  : "Changer de compte mail"}
              </span>
              {otherAccountsExpanded ? (
                <ChevronUp className="size-5 text-muted-foreground" aria-hidden />
              ) : (
                <ChevronDown className="size-5 text-muted-foreground" aria-hidden />
              )}
            </button>

            {otherAccountsExpanded && (
              <div className="border-t border-border px-1 pb-1 pt-0.5">
                {mailAccounts.map((account) => (
                  <AccountRow
                    key={account.id}
                    account={account}
                    onSelect={() => handleSelectAccount(account.id)}
                  />
                ))}
              </div>
            )}
          </div>
        ) : null}

        <div
          className={
            hasMultipleMailAccounts
              ? "mt-3 overflow-hidden rounded-2xl border border-border bg-mail-surface"
              : "overflow-hidden rounded-2xl border border-border bg-mail-surface"
          }
        >
          <div className="px-1 py-1">
            <a
              href={addAccountHref}
              onClick={() => onOpenChange(false)}
              className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm text-foreground transition-colors hover:bg-accent"
            >
              <span className="flex size-8 items-center justify-center">
                <Plus className="size-5 text-primary" aria-hidden />
              </span>
              Ajouter un compte
            </a>
            <button
              type="button"
              onClick={handleSignOut}
              className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm text-foreground transition-colors hover:bg-accent"
            >
              <span className="flex size-8 items-center justify-center">
                <LogOut className="size-5 text-muted-foreground" aria-hidden />
              </span>
              Se déconnecter
            </button>
          </div>
        </div>

        <div className="mt-4 flex flex-wrap items-center justify-center gap-1 pb-2 text-center text-xs text-muted-foreground">
          <button type="button" className="hover:underline">
            Règles de confidentialité
          </button>
          <span aria-hidden>·</span>
          <button type="button" className="hover:underline">
            Conditions d&apos;utilisation
          </button>
        </div>
      </div>
    </div>
  )
}
