"use client"

import { useCallback, useMemo, useState } from "react"
import { flushSync } from "react-dom"
import {
  useAddDiscoveredContact,
  useBlockedDiscoveredContacts,
  useRejectDiscoveredProfile,
} from "@/lib/api/hooks/use-contact-discovery"
import { fullContactToApiContact } from "@/lib/api/adapters"
import { profileDisplayName } from "@/lib/contacts/discovery-utils"
import type { ApiDiscoveredProfile, ApiDiscoveredProfileGroup } from "@/lib/contacts/discovery-types"
import type { FullContact } from "@/lib/contacts/types"
import { useContactsList } from "@/lib/contacts/use-contacts-list"
import { useBlockedSendersStore } from "@/lib/stores/blocked-senders-store"
import {
  CONTACTS_HEADING_TEXT,
  CONTACTS_MUTED_TEXT,
  CONTACTS_PAGE_SECTION_TITLE_CLASS,
} from "@/lib/contacts-chrome-classes"
import {
  DiscoveryCardsMasonry,
  DiscoveryCardsMasonryItem,
} from "@/components/gmail/contacts-page/discovery-cards-masonry"
import { SuggestedContactCard } from "@/components/gmail/contacts-page/suggested-contact-card"
import { cn } from "@/lib/utils"

interface BlockedContactsViewProps {
  searchQuery: string
}

function profileToGroup(profile: ApiDiscoveredProfile): ApiDiscoveredProfileGroup {
  return {
    group_key: profile.id,
    profile_ids: [profile.id],
    display_name: profileDisplayName(profile),
    primary_email: profile.primary_email,
    message_count: profile.message_count,
    profile,
    profiles: [profile],
  }
}

export function BlockedContactsView({ searchQuery }: BlockedContactsViewProps) {
  const { bookId } = useContactsList()
  const { data: profiles = [], isLoading } = useBlockedDiscoveredContacts()
  const addDiscoveredContact = useAddDiscoveredContact()
  const rejectProfile = useRejectDiscoveredProfile()
  const unblockSender = useBlockedSendersStore((s) => s.unblockSender)
  const [removedProfileIds, setRemovedProfileIds] = useState<Set<string>>(() => new Set())

  const markProfileRemoved = useCallback((profileId: string) => {
    setRemovedProfileIds((prev) => {
      if (prev.has(profileId)) return prev
      const next = new Set(prev)
      next.add(profileId)
      return next
    })
  }, [])

  const restoreProfile = useCallback((profileId: string) => {
    setRemovedProfileIds((prev) => {
      if (!prev.has(profileId)) return prev
      const next = new Set(prev)
      next.delete(profileId)
      return next
    })
  }, [])

  const filtered = useMemo(() => {
    const visible = profiles.filter((p) => !removedProfileIds.has(p.id))
    const q = searchQuery.trim().toLowerCase()
    if (!q) return visible
    return visible.filter((p) => {
      const name = profileDisplayName(p).toLowerCase()
      return name.includes(q) || p.primary_email.toLowerCase().includes(q)
    })
  }, [profiles, searchQuery, removedProfileIds])

  function handleAdd(profile: ApiDiscoveredProfile, buildContact: () => FullContact) {
    if (!bookId) return
    flushSync(() => markProfileRemoved(profile.id))
    unblockSender(profile.primary_email)
    requestAnimationFrame(() => {
      addDiscoveredContact.mutate(
        {
          bookId,
          profileId: profile.id,
          contact: fullContactToApiContact(buildContact()),
        },
        { onError: () => restoreProfile(profile.id) },
      )
    })
  }

  function handleRemove(profile: ApiDiscoveredProfile) {
    flushSync(() => markProfileRemoved(profile.id))
    unblockSender(profile.primary_email)
    requestAnimationFrame(() => {
      rejectProfile.mutate(profile.id, { onError: () => restoreProfile(profile.id) })
    })
  }

  const addingProfileId =
    addDiscoveredContact.isPending && typeof addDiscoveredContact.variables?.profileId === "string"
      ? addDiscoveredContact.variables.profileId
      : null

  return (
    <div className="px-6 py-6 text-foreground">
      <h2 className={cn("mb-2 text-base font-medium", CONTACTS_HEADING_TEXT)}>Bloqués</h2>
      <p className={cn("mb-6 text-sm", CONTACTS_MUTED_TEXT)}>
        Ces expéditeurs sont traités comme indésirables : pas de suggestion, contenus distants
        bloqués dans les e-mails. Vous pouvez les ajouter à votre carnet ou les supprimer
        définitivement.
      </p>

      <h3 className={cn("mb-4", CONTACTS_PAGE_SECTION_TITLE_CLASS)}>
        {filtered.length} expéditeur{filtered.length !== 1 ? "s" : ""}
      </h3>

      {isLoading && (
        <p className={cn("py-8 text-center text-sm", CONTACTS_MUTED_TEXT)}>Chargement…</p>
      )}

      {!isLoading && filtered.length === 0 && (
        <p className={cn("py-8 text-center text-sm", CONTACTS_MUTED_TEXT)}>
          Aucun expéditeur bloqué.
        </p>
      )}

      <DiscoveryCardsMasonry>
        {filtered.map((p) => (
          <DiscoveryCardsMasonryItem key={p.id}>
            <SuggestedContactCard
              group={profileToGroup(p)}
              mode="blocked"
              addBusy={addingProfileId === p.id}
              busy={rejectProfile.isPending && rejectProfile.variables === p.id}
              onAdd={(buildContact) => handleAdd(p, buildContact)}
              onRemove={() => handleRemove(p)}
            />
          </DiscoveryCardsMasonryItem>
        ))}
      </DiscoveryCardsMasonry>
    </div>
  )
}
