"use client"

import { useEffect, useRef, type RefObject } from "react"
import { Icon, addCollection } from "@iconify/react"
import { icons as mdiIcons } from "@iconify-json/mdi"
import { Camera, ChevronDown, ChevronUp, LogOut, Plus, X } from "lucide-react"
import { AccountAvatar } from "@/components/gmail/account-avatar"
import { Button } from "@/components/ui/button"
import { MOCK_USER_ACCOUNTS, STORAGE_USAGE } from "@/lib/accounts/mock-accounts"
import type { UserAccount } from "@/lib/accounts/types"
import {
  useAccountStore,
  useActiveAccount,
} from "@/lib/stores/account-store"
addCollection(mdiIcons)

interface AccountSwitcherDropdownProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  /** Clicks inside this node (e.g. avatar trigger) do not close the panel. */
  containerRef: RefObject<HTMLElement | null>
}

function AccountRow({
  account,
  onSelect,
}: {
  account: UserAccount
  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.displayName}
        </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 activeAccount = useActiveAccount()
  const activeAccountId = useAccountStore((s) => s.activeAccountId)
  const otherAccountsExpanded = useAccountStore((s) => s.otherAccountsExpanded)
  const setActiveAccount = useAccountStore((s) => s.setActiveAccount)
  const toggleOtherAccountsExpanded = useAccountStore(
    (s) => s.toggleOtherAccountsExpanded,
  )
  const signOutAll = useAccountStore((s) => s.signOutAll)

  const otherAccounts = MOCK_USER_ACCOUNTS.filter((a) => a.id !== activeAccountId)

  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) return null

  const handleSelectAccount = (id: string) => {
    setActiveAccount(id)
    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"
    >
      {/* Current account header */}
      <div className="relative px-4 pb-3 pt-4">
        <p className="truncate pr-8 text-center text-sm text-foreground">
          {activeAccount.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={activeAccount} 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 {activeAccount.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"
          >
            Gérer votre compte Google
          </Button>
        </div>
      </div>

      {/* Other accounts + actions */}
      <div className="px-3 pb-3">
        <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 plus de comptes"
                : "Afficher plus de comptes"}
            </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">
              {otherAccounts.map((account) => (
                <AccountRow
                  key={account.id}
                  account={account}
                  onSelect={() => handleSelectAccount(account.id)}
                />
              ))}
            </div>
          )}

          <div className="border-t border-border px-1 py-1">
            <button
              type="button"
              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
            </button>
            <button
              type="button"
              onClick={() => {
                signOutAll()
                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">
                <LogOut className="size-5 text-muted-foreground" aria-hidden />
              </span>
              Se déconnecter de tous les comptes
            </button>
          </div>
        </div>

        {/* Storage */}
        <div className="mt-3 flex items-center gap-2 rounded-full border border-border bg-mail-surface px-4 py-2.5">
          <Icon
            icon="mdi:alert-circle"
            className="size-5 shrink-0 text-[#e8710a]"
            aria-hidden
          />
          <span className="text-sm text-foreground">
            {STORAGE_USAGE.percentUsed} % utilisé(s) sur {STORAGE_USAGE.totalLabel}
          </span>
        </div>

        {/* Footer links */}
        <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>
  )
}
