"use client"

import {
  ArrowLeft,
  Download,
  Pencil,
  Star,
  Trash2,
  Mail,
  Phone,
  Building2,
  MapPin,
  Cake,
  FileText,
  MessageSquare,
  Video,
} from "lucide-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"
import { useNavStore } from "@/lib/stores/nav-store"
import { downloadContactVCard } from "@/lib/contacts/export-contacts"

const FRENCH_MONTHS = [
  "janvier", "février", "mars", "avril", "mai", "juin",
  "juillet", "août", "septembre", "octobre", "novembre", "décembre",
]

function formatBirthday(b: { day?: number; month?: number; year?: number }): string {
  const parts: string[] = []
  if (b.day) parts.push(String(b.day))
  if (b.month) parts.push(FRENCH_MONTHS[b.month - 1] ?? "")
  if (b.year) parts.push(String(b.year))
  return parts.join(" ")
}

interface ContactDetailPageProps {
  contactId: string
  onBack: () => void
  onEdit: (id: string) => void
}

export function ContactDetailPage({ contactId, onBack, onEdit }: ContactDetailPageProps) {
  const { contacts, softDeleteContact } = useContactsStore()
  const labelRows = useNavStore((s) => s.labelRows)
  const contact = contacts.find((c) => c.id === contactId)

  if (!contact) {
    return (
      <div className="flex h-full items-center justify-center text-sm text-gray-500">
        Contact introuvable
      </div>
    )
  }

  const displayName = fullContactDisplayName(contact)
  const name = displayName || contact.emails[0]?.value || contact.phones[0]?.value || "?"
  const color = avatarColor(name)
  const initial = senderInitial(name)
  const primaryEmail = contact.emails[0]?.value

  function handleDelete() {
    softDeleteContact(contactId, "Supprimé manuellement")
    onBack()
  }

  return (
    <div className="mx-auto max-w-3xl px-6 py-8">
      {/* Top actions */}
      <div className="mb-6 flex items-center justify-between">
        <Button
          variant="ghost"
          size="icon"
          className="h-10 w-10 rounded-full text-[#5f6368]"
          onClick={onBack}
        >
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div className="flex items-center gap-1">
          <Button variant="ghost" size="icon" className="h-10 w-10 rounded-full text-[#5f6368]">
            <Star className="h-5 w-5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-10 w-10 rounded-full text-[#5f6368]"
            onClick={() => downloadContactVCard(contact)}
            aria-label="Télécharger la fiche contact"
          >
            <Download className="h-5 w-5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-10 w-10 rounded-full text-[#5f6368]"
            onClick={() => onEdit(contactId)}
          >
            <Pencil className="h-5 w-5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-10 w-10 rounded-full text-[#5f6368]"
            onClick={handleDelete}
          >
            <Trash2 className="h-5 w-5" />
          </Button>
        </div>
      </div>

      {/* Avatar + name */}
      <div className="flex items-center gap-6 pb-6">
        {contact.avatarUrl ? (
          <img src={contact.avatarUrl} alt={name} className="h-24 w-24 rounded-full object-cover" />
        ) : (
          <div
            className="flex h-24 w-24 items-center justify-center rounded-full text-3xl font-medium text-white"
            style={{ backgroundColor: color }}
          >
            {initial}
          </div>
        )}
        <div>
          <h1 className="text-3xl font-normal text-[#1f1f1f]">{name}</h1>
          {contact.company && (
            <p className="mt-1 text-base text-[#5f6368]">
              {contact.jobTitle ? `${contact.jobTitle} — ` : ""}
              {contact.company}
            </p>
          )}
          {contact.labels && contact.labels.length > 0 && (
            <div className="mt-2 flex flex-wrap gap-1">
              {contact.labels.map((labelId) => {
                const row = labelRows.find((r) => r.id === labelId)
                return row ? (
                  <span
                    key={labelId}
                    className="inline-flex items-center gap-1 rounded border border-gray-300 px-2 py-0.5 text-xs text-[#3c4043]"
                  >
                    <span className={`inline-block h-2 w-2 rounded-full ${row.color}`} />
                    {row.label}
                  </span>
                ) : null
              })}
            </div>
          )}
        </div>
      </div>

      {/* Quick actions */}
      {primaryEmail && (
        <div className="flex items-center gap-2 border-t border-gray-200 py-4">
          <button
            type="button"
            className="inline-flex h-9 items-center gap-2 rounded-full bg-[#d3e3fd] px-5 text-sm font-medium text-[#001d35] transition-colors hover:bg-[#c4d9fc]"
          >
            <Mail className="h-4 w-4" />
            Envoyer un e-mail
          </button>
          <button
            type="button"
            className="flex h-9 w-9 items-center justify-center rounded-full border border-[#dadce0] text-gray-500 hover:bg-gray-50"
          >
            <MessageSquare className="h-4 w-4" />
          </button>
          <button
            type="button"
            className="flex h-9 w-9 items-center justify-center rounded-full border border-[#dadce0] text-gray-500 hover:bg-gray-50"
          >
            <Video className="h-4 w-4" />
          </button>
        </div>
      )}

      {/* Details */}
      <div className="space-y-1 border-t border-gray-200 pt-4">
        {contact.emails.length > 0 && (
          <DetailRow icon={<Mail className="h-5 w-5 text-[#5f6368]" />}>
            {contact.emails.map((e, i) => (
              <div key={i}>
                <p className="text-sm text-[#1a73e8]">{e.value}</p>
                <p className="text-xs text-[#5f6368]">{e.label}</p>
              </div>
            ))}
          </DetailRow>
        )}

        {contact.phones.length > 0 && (
          <DetailRow icon={<Phone className="h-5 w-5 text-[#5f6368]" />}>
            {contact.phones.map((p, i) => (
              <div key={i}>
                <p className="text-sm text-[#1a73e8]">{p.value}</p>
                <p className="text-xs text-[#5f6368]">{p.label}</p>
              </div>
            ))}
          </DetailRow>
        )}

        {contact.company && (
          <DetailRow icon={<Building2 className="h-5 w-5 text-[#5f6368]" />}>
            <div>
              <p className="text-sm text-[#1f1f1f]">{contact.company}</p>
              {contact.department && <p className="text-xs text-[#5f6368]">{contact.department}</p>}
              {contact.jobTitle && <p className="text-xs text-[#5f6368]">{contact.jobTitle}</p>}
            </div>
          </DetailRow>
        )}

        {contact.addresses && contact.addresses.length > 0 && (
          <DetailRow icon={<MapPin className="h-5 w-5 text-[#5f6368]" />}>
            {contact.addresses.map((addr, i) => (
              <div key={i}>
                <p className="text-sm text-[#1f1f1f]">
                  {[addr.street, [addr.postalCode, addr.city].filter(Boolean).join(" "), addr.region, addr.country]
                    .filter(Boolean)
                    .join(", ")}
                </p>
                <p className="text-xs text-[#5f6368]">{addr.label}</p>
              </div>
            ))}
          </DetailRow>
        )}

        {contact.birthday && (contact.birthday.day || contact.birthday.month) && (
          <DetailRow icon={<Cake className="h-5 w-5 text-[#5f6368]" />}>
            <p className="text-sm text-[#1f1f1f]">{formatBirthday(contact.birthday)}</p>
          </DetailRow>
        )}

        {contact.notes && (
          <DetailRow icon={<FileText className="h-5 w-5 text-[#5f6368]" />}>
            <p className="whitespace-pre-wrap text-sm text-[#1f1f1f]">{contact.notes}</p>
          </DetailRow>
        )}
      </div>
    </div>
  )
}

function DetailRow({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) {
  return (
    <div className="flex gap-4 py-3">
      <div className="flex w-6 shrink-0 pt-0.5">{icon}</div>
      <div className="flex-1 space-y-2">{children}</div>
    </div>
  )
}
