'use client'

import { useState, useEffect } from 'react'
import { AlertTriangle, ChevronDown, ChevronUp, ExternalLink } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { Contact, contactsAPI } from '@/lib/api/contacts'
import { format } from 'date-fns'

interface DuplicateAlertProps {
  email?: string
  phone?: string
  mobile?: string
  taxNumber?: string
  commercialRegister?: string
  excludeId?: string
  onMerge?: (contactId: string) => void
}

export default function DuplicateAlert({
  email,
  phone,
  mobile,
  taxNumber,
  commercialRegister,
  excludeId,
  onMerge
}: DuplicateAlertProps) {
  const router = useRouter()
  const [duplicates, setDuplicates] = useState<Contact[]>([])
  const [loading, setLoading] = useState(false)
  const [expanded, setExpanded] = useState(false)
  const [dismissed, setDismissed] = useState(false)

  useEffect(() => {
    const checkDuplicates = async () => {
      // Only check if we have at least one field to check
      if (!email && !phone && !mobile && !taxNumber && !commercialRegister) {
        setDuplicates([])
        return
      }

      setLoading(true)
      try {
        const results = await contactsAPI.checkDuplicates({
          email,
          phone,
          mobile,
          taxNumber,
          commercialRegister,
          excludeId
        })
        setDuplicates(results)
        setDismissed(false)
      } catch (error) {
        console.error('Error checking duplicates:', error)
        setDuplicates([])
      } finally {
        setLoading(false)
      }
    }

    // Debounce the duplicate check
    const debounce = setTimeout(checkDuplicates, 800)
    return () => clearTimeout(debounce)
  }, [email, phone, mobile, taxNumber, commercialRegister, excludeId])

  if (loading || duplicates.length === 0 || dismissed) {
    return null
  }

  const getMatchingFields = (contact: Contact) => {
    const matches: string[] = []
    if (email && contact.email === email) matches.push('Email')
    if (phone && contact.phone === phone) matches.push('Phone')
    if (mobile && contact.mobile === mobile) matches.push('Mobile')
    if (taxNumber && contact.taxNumber === taxNumber) matches.push('Tax Number')
    if (commercialRegister && contact.commercialRegister === commercialRegister) matches.push('Commercial Register')
    return matches
  }

  return (
    <div className="bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded-r-lg">
      <div className="flex items-start">
        <AlertTriangle className="h-5 w-5 text-yellow-400 mt-0.5 mr-3 flex-shrink-0" />
        <div className="flex-1">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-medium text-yellow-800">
                تم العثور على جهات اتصال مشابهة - Potential Duplicates Found
              </h3>
              <p className="mt-1 text-sm text-yellow-700">
                تم العثور على {duplicates.length} جهة اتصال مشابهة. يرجى المراجعة قبل المتابعة.
              </p>
            </div>
            <button
              onClick={() => setExpanded(!expanded)}
              className="ml-4 text-yellow-700 hover:text-yellow-900"
            >
              {expanded ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
            </button>
          </div>

          {expanded && (
            <div className="mt-4 space-y-3">
              {duplicates.map(contact => {
                const matchingFields = getMatchingFields(contact)
                return (
                  <div
                    key={contact.id}
                    className="bg-white border border-yellow-200 rounded-lg p-3"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <h4 className="text-sm font-semibold text-gray-900">
                            {contact.name}
                          </h4>
                          <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded">
                            {contact.type}
                          </span>
                        </div>
                        <div className="mt-1 text-xs text-gray-600 space-y-0.5">
                          {contact.email && (
                            <p>
                              Email: <span className="font-medium">{contact.email}</span>
                            </p>
                          )}
                          {contact.phone && (
                            <p>
                              Phone: <span className="font-medium">{contact.phone}</span>
                            </p>
                          )}
                          {contact.mobile && (
                            <p>
                              Mobile: <span className="font-medium">{contact.mobile}</span>
                            </p>
                          )}
                          {contact.taxNumber && (
                            <p>
                              Tax Number: <span className="font-medium">{contact.taxNumber}</span>
                            </p>
                          )}
                        </div>
                        <div className="mt-2 flex items-center gap-2 flex-wrap">
                          <span className="text-xs text-yellow-700 font-medium">
                            Matching: {matchingFields.join(', ')}
                          </span>
                          <span className="text-xs text-gray-500">
                            Created {format(new Date(contact.createdAt), 'MMM d, yyyy')}
                          </span>
                        </div>
                      </div>
                      <button
                        onClick={() => {
                          window.open(`/contacts/${contact.id}`, '_blank')
                        }}
                        className="ml-2 text-blue-600 hover:text-blue-800"
                        title="View contact"
                      >
                        <ExternalLink size={16} />
                      </button>
                    </div>
                  </div>
                )
              })}

              <div className="flex items-center gap-3 pt-2 border-t border-yellow-200">
                {onMerge && duplicates.length > 0 && (
                  <button
                    onClick={() => onMerge(duplicates[0].id)}
                    className="text-sm text-blue-600 hover:text-blue-800 font-medium"
                  >
                    دمج بدلاً من ذلك - Merge Instead
                  </button>
                )}
                <button
                  onClick={() => setDismissed(true)}
                  className="text-sm text-gray-600 hover:text-gray-800 font-medium"
                >
                  متابعة على أي حال - Continue Anyway
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
