"use client"

import { useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import { useContactsStore } from "@/lib/contacts/contacts-store"
import { fullContactDisplayName } from "@/lib/contacts/types"
import { avatarColor, senderInitial } from "@/lib/sender-display"

export function AddCoordinatesView() {
  const { getCoordinateSuggestions, updateContact } = useContactsStore()
  const suggestions = useMemo(() => getCoordinateSuggestions(), [getCoordinateSuggestions])
  const [dismissed, setDismissed] = useState<Set<string>>(new Set())

  const visible = suggestions.filter((s) => !dismissed.has(s.contact.id))

  function handleAdd(contactId: string, field: string, value: string) {
    updateContact(contactId, { [field]: value })
    setDismissed((s) => new Set(s).add(contactId))
  }

  function handleIgnore(contactId: string) {
    setDismissed((s) => new Set(s).add(contactId))
  }

  function handleAddAll() {
    for (const s of visible) {
      updateContact(s.contact.id, { [s.suggestedField]: s.suggestedValue })
    }
    setDismissed(new Set(suggestions.map((s) => s.contact.id)))
  }

  return (
    <div>
      <div className="mb-4 flex items-center justify-between">
        <h3 className="text-lg font-normal text-[#1f1f1f]">
          Ajouter des coordonnées ({visible.length})
        </h3>
        {visible.length > 0 && (
          <Button
            onClick={handleAddAll}
            className="rounded-full bg-[#1a73e8] px-5 text-sm font-medium text-white hover:bg-[#1557b0]"
          >
            Ajouter tous les détails
          </Button>
        )}
      </div>

      {visible.length === 0 && (
        <p className="py-8 text-center text-sm text-[#5f6368]">
          Aucune suggestion disponible
        </p>
      )}

      <div className="space-y-4">
        {visible.map((suggestion) => {
          const { contact, suggestedField, suggestedValue } = suggestion
          const displayName = fullContactDisplayName(contact)
          const name = displayName || contact.emails[0]?.value || "?"
          const color = avatarColor(name)
          const initial = senderInitial(name)

          return (
            <div key={contact.id} className="rounded-xl border border-gray-200 p-5">
              <p className="mb-2 text-xs font-medium text-[#5f6368]">Contact à modifier</p>
              <div className="flex items-start gap-3">
                {contact.avatarUrl ? (
                  <img src={contact.avatarUrl} alt={name} className="h-10 w-10 rounded-full object-cover" />
                ) : (
                  <div
                    className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-medium text-white"
                    style={{ backgroundColor: color }}
                  >
                    {initial}
                  </div>
                )}
                <div className="min-w-0">
                  <p className="truncate text-sm font-medium text-[#1f1f1f]">{name}</p>
                  {contact.emails[0] && (
                    <p className="truncate text-xs text-[#5f6368]">{contact.emails[0].value}</p>
                  )}
                  {contact.phones[0] && (
                    <p className="truncate text-xs text-[#5f6368]">{contact.phones[0].value} ({contact.phones[0].label})</p>
                  )}
                </div>
              </div>

              <div className="mt-3 border-t border-gray-100 pt-3">
                <p className="text-xs font-medium text-[#5f6368]">Détails à ajouter</p>
                <p className="mt-1 text-sm text-[#1f1f1f]">{suggestedValue}</p>
              </div>

              <div className="mt-4 flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => handleIgnore(contact.id)}
                  className="text-sm font-medium text-[#1a73e8] hover:text-[#1557b0]"
                >
                  Ignorer
                </button>
                <Button
                  onClick={() => handleAdd(contact.id, suggestedField, suggestedValue)}
                  className="rounded-full bg-[#1a73e8] px-5 text-sm font-medium text-white hover:bg-[#1557b0]"
                >
                  Ajouter
                </Button>
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}
