"use client"

import { useEffect, useState } from "react"
import { db } from "@/lib/firebase"
import { collection, getDocs, updateDoc, doc } from "firebase/firestore"
import { 
  CheckCircleIcon, 
  ClockIcon, 
  XCircleIcon, 
  PhoneIcon, 
  EnvelopeIcon, 
  UserIcon,
  TagIcon,
  PencilSquareIcon,
  ChatBubbleLeftRightIcon
} from '@heroicons/react/24/outline'

interface Contact {
  id: string
  nom: string
  email: string
  type: string
  message: string
  status: string
  notes: string
  [key: string]: any
}

const statusConfig: Record<string, { color: string; icon: any; label: string }> = {
  "traité": { color: "bg-green-100 text-green-800 border-green-200", icon: CheckCircleIcon, label: "Traité" },
  "en attente": { color: "bg-yellow-100 text-yellow-800 border-yellow-200", icon: ClockIcon, label: "En attente" },
  "résolu": { color: "bg-blue-100 text-blue-800 border-blue-200", icon: CheckCircleIcon, label: "Résolu" },
  "contacter": { color: "bg-purple-100 text-purple-800 border-purple-200", icon: PhoneIcon, label: "À contacter" },
  "annulé": { color: "bg-red-100 text-red-800 border-red-200", icon: XCircleIcon, label: "Annulé" },
}

export default function ContactsAdmin() {
  const [contacts, setContacts] = useState<Contact[]>([])
  const [loading, setLoading] = useState(true)

  const loadContacts = async () => {
    setLoading(true)
    try {
      const snap = await getDocs(collection(db, "contacts"))
      const data: Contact[] = []
      snap.forEach(d => {
        data.push({ id: d.id, ...d.data() } as Contact)
      })
      setContacts(data)
    } catch (error) {
      console.error("Error loading contacts:", error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadContacts()
  }, [])

  const updateNotes = async (id: string, notes: string) => {
    try {
      await updateDoc(doc(db, "contacts", id), { notes })
    } catch (error) {
      console.error("Error updating notes:", error)
    }
  }

  const updateStatus = async (id: string, status: string) => {
    try {
      await updateDoc(doc(db, "contacts", id), { status })
      await loadContacts() // Refresh to show updated status
    } catch (error) {
      console.error("Error updating status:", error)
    }
  }

  const StatusBadge = ({ status }: { status: string }) => {
    const config = statusConfig[status] || statusConfig["en attente"]
    const Icon = config.icon
    return (
      <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium border ${config.color}`}>
        <Icon className="w-4 h-4" />
        {config.label}
      </span>
    )
  }

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
          Messages reçus
        </h1>
        <p className="text-gray-600 mt-2">
          Gérez et suivez tous les messages de contact
        </p>
      </div>

      {contacts.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-2xl border-2 border-dashed border-gray-300">
          <ChatBubbleLeftRightIcon className="mx-auto h-12 w-12 text-gray-400" />
          <h3 className="mt-2 text-sm font-semibold text-gray-900">Aucun message</h3>
          <p className="mt-1 text-sm text-gray-500">Commencez par recevoir des messages de contact.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3">
          {contacts.map((contact) => (
            <div
              key={contact.id}
              className="group bg-white rounded-2xl shadow-sm hover:shadow-xl transition-all duration-300 border border-gray-200 overflow-hidden hover:border-blue-200"
            >
              {/* Header with status */}
              <div className="px-6 py-4 bg-gradient-to-r from-gray-50 to-white border-b border-gray-200">
                <div className="flex items-center justify-between">
                  <StatusBadge status={contact.status || "en attente"} />
                  <span className="text-xs text-gray-500 font-medium">
                    #{contact.id.slice(0, 8)}
                  </span>
                </div>
              </div>

              {/* Contact details */}
              <div className="px-6 py-4 space-y-3">
                <div className="flex items-center gap-2 text-gray-700">
                  <UserIcon className="w-4 h-4 text-gray-400" />
                  <span className="font-medium">{contact.nom}</span>
                </div>
                
                <div className="flex items-center gap-2 text-gray-600">
                  <EnvelopeIcon className="w-4 h-4 text-gray-400" />
                  <a href={`mailto:${contact.email}`} className="text-sm hover:text-blue-600 transition-colors">
                    {contact.email}
                  </a>
                </div>

                <div className="flex items-center gap-2 text-gray-600">
                  <TagIcon className="w-4 h-4 text-gray-400" />
                  <span className="text-sm px-2 py-0.5 bg-gray-100 rounded-full">
                    {contact.type || "Général"}
                  </span>
                </div>

                <div className="mt-3 p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm text-gray-700 leading-relaxed">
                    {contact.message}
                  </p>
                </div>

                {/* Notes section */}
                <div className="relative">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Notes internes
                  </label>
                  <textarea
                    defaultValue={contact.notes || ""}
                    onBlur={(e) => updateNotes(contact.id, e.target.value)}
                    placeholder="Ajouter des notes privées..."
                    rows={2}
                    className="w-full p-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none transition-all bg-white hover:border-gray-400"
                  />
                  <PencilSquareIcon className="absolute right-3 bottom-3 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>

                {/* Status actions */}
                <div className="pt-3 border-t border-gray-200">
                  <p className="text-xs font-medium text-gray-500 mb-2">Changer le statut :</p>
                  <div className="flex flex-wrap gap-2">
                    {Object.entries(statusConfig).map(([key, config]) => {
                      const Icon = config.icon
                      return (
                        <button
                          key={key}
                          onClick={() => updateStatus(contact.id, key)}
                          className={`inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 
                            ${contact.status === key 
                              ? `${config.color} ring-2 ring-offset-2 ring-${config.color.split(' ')[0].replace('bg-', '')}`
                              : 'bg-gray-100 text-gray-600 hover:bg-gray-200 border border-gray-200'
                            }`}
                        >
                          <Icon className="w-3.5 h-3.5" />
                          {config.label}
                        </button>
                      )
                    })}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}