'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { toast } from 'react-hot-toast'
import {
  ArrowLeft,
  Search,
  Check,
  X,
  AlertTriangle,
  ChevronRight,
  Loader2,
  User,
  Building2,
  Mail,
  Phone,
  Globe,
  MapPin,
  Calendar,
  Star,
  Tag as TagIcon
} from 'lucide-react'
import ProtectedRoute from '@/components/ProtectedRoute'
import { contactsAPI, Contact } from '@/lib/api/contacts'
import { format } from 'date-fns'
import Link from 'next/link'

type MergeStep = 'select' | 'compare' | 'preview' | 'confirm' | 'success'

interface FieldChoice {
  [key: string]: 'source' | 'target' | 'custom'
}

function MergeContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const preSelectedSourceId = searchParams?.get('sourceId')

  const [step, setStep] = useState<MergeStep>('select')
  const [searchTerm, setSearchTerm] = useState('')
  const [searchResults, setSearchResults] = useState<Contact[]>([])
  const [searching, setSearching] = useState(false)
  const [sourceContact, setSourceContact] = useState<Contact | null>(null)
  const [targetContact, setTargetContact] = useState<Contact | null>(null)
  const [fieldChoices, setFieldChoices] = useState<FieldChoice>({})
  const [mergedData, setMergedData] = useState<any>({})
  const [reason, setReason] = useState('')
  const [merging, setMerging] = useState(false)
  const [mergedContactId, setMergedContactId] = useState<string | null>(null)

  // Load pre-selected source contact
  useEffect(() => {
    if (preSelectedSourceId) {
      contactsAPI.getById(preSelectedSourceId).then(contact => {
        setSourceContact(contact)
      }).catch(error => {
        toast.error('Failed to load pre-selected contact')
      })
    }
  }, [preSelectedSourceId])

  // Search contacts with debouncing
  useEffect(() => {
    if (!searchTerm || searchTerm.length < 2) {
      setSearchResults([])
      return
    }

    const debounce = setTimeout(async () => {
      setSearching(true)
      try {
        const data = await contactsAPI.getAll({ search: searchTerm, pageSize: 10 })
        setSearchResults(data.contacts.filter(c => 
          c.id !== sourceContact?.id && c.id !== targetContact?.id
        ))
      } catch (error) {
        console.error('Search error:', error)
      } finally {
        setSearching(false)
      }
    }, 500)

    return () => clearTimeout(debounce)
  }, [searchTerm, sourceContact, targetContact])

  // Initialize field choices with smart defaults
  const initializeFieldChoices = useCallback(() => {
    if (!sourceContact || !targetContact) return

    const choices: FieldChoice = {}
    const fields = [
      'type', 'name', 'nameAr', 'email', 'phone', 'mobile', 'website',
      'companyName', 'companyNameAr', 'taxNumber', 'commercialRegister',
      'address', 'city', 'country', 'postalCode', 'rating', 'tags'
    ]

    fields.forEach(field => {
      const sourceValue = (sourceContact as any)[field]
      const targetValue = (targetContact as any)[field]
      
      // Prefer non-empty values
      if (sourceValue && !targetValue) {
        choices[field] = 'source'
      } else if (!sourceValue && targetValue) {
        choices[field] = 'target'
      } else if (sourceValue && targetValue) {
        // Prefer newer data
        choices[field] = new Date(sourceContact.createdAt) > new Date(targetContact.createdAt) 
          ? 'source' 
          : 'target'
      } else {
        choices[field] = 'source'
      }
    })

    setFieldChoices(choices)
  }, [sourceContact, targetContact])

  useEffect(() => {
    if (step === 'compare' && sourceContact && targetContact) {
      initializeFieldChoices()
    }
  }, [step, sourceContact, targetContact, initializeFieldChoices])

  // Generate merged data preview
  useEffect(() => {
    if (!sourceContact || !targetContact || Object.keys(fieldChoices).length === 0) return

    const merged: any = {}
    Object.keys(fieldChoices).forEach(field => {
      const choice = fieldChoices[field]
      if (choice === 'source') {
        merged[field] = (sourceContact as any)[field]
      } else if (choice === 'target') {
        merged[field] = (targetContact as any)[field]
      }
    })

    setMergedData(merged)
  }, [fieldChoices, sourceContact, targetContact])

  const handleSelectContact = (contact: Contact, type: 'source' | 'target') => {
    if (type === 'source') {
      setSourceContact(contact)
    } else {
      setTargetContact(contact)
    }
    setSearchTerm('')
    setSearchResults([])
  }

  const handleFieldChoice = (field: string, choice: 'source' | 'target') => {
    setFieldChoices(prev => ({ ...prev, [field]: choice }))
  }

  const handleMerge = async () => {
    if (!sourceContact || !targetContact || !reason.trim()) {
      toast.error('Please provide a reason for merging')
      return
    }

    setMerging(true)
    try {
      const result = await contactsAPI.merge(sourceContact.id, targetContact.id, reason)
      setMergedContactId(result.id)
      setStep('success')
      toast.success('Contacts merged successfully!')
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Failed to merge contacts')
    } finally {
      setMerging(false)
    }
  }

  const renderFieldValue = (value: any) => {
    if (Array.isArray(value)) {
      return value.length > 0 ? value.join(', ') : <span className="text-gray-400">Empty</span>
    }
    if (value === null || value === undefined || value === '') {
      return <span className="text-gray-400">Empty</span>
    }
    if (typeof value === 'boolean') {
      return value ? 'Yes' : 'No'
    }
    return value
  }

  const ContactCard = ({ contact, type, onRemove }: { contact: Contact, type: 'source' | 'target', onRemove: () => void }) => (
    <div className="border-2 border-blue-200 bg-blue-50 rounded-lg p-4">
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center gap-2">
          {contact.type === 'INDIVIDUAL' ? <User size={20} className="text-blue-600" /> : <Building2 size={20} className="text-blue-600" />}
          <div>
            <h4 className="font-semibold text-gray-900">{contact.name}</h4>
            <p className="text-sm text-gray-600">{contact.uniqueContactId}</p>
          </div>
        </div>
        <button
          onClick={onRemove}
          className="text-gray-400 hover:text-red-600"
        >
          <X size={18} />
        </button>
      </div>
      <div className="space-y-1 text-sm">
        {contact.email && (
          <div className="flex items-center gap-2 text-gray-700">
            <Mail size={14} />
            <span>{contact.email}</span>
          </div>
        )}
        {contact.phone && (
          <div className="flex items-center gap-2 text-gray-700">
            <Phone size={14} />
            <span>{contact.phone}</span>
          </div>
        )}
        {contact.city && (
          <div className="flex items-center gap-2 text-gray-700">
            <MapPin size={14} />
            <span>{contact.city}, {contact.country}</span>
          </div>
        )}
        <div className="flex items-center gap-2 text-gray-500 text-xs pt-2">
          <Calendar size={12} />
          <span>Created {format(new Date(contact.createdAt), 'MMM d, yyyy')}</span>
        </div>
      </div>
    </div>
  )

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex items-center gap-4">
            <Link
              href="/contacts"
              className="text-gray-600 hover:text-gray-900"
            >
              <ArrowLeft size={24} />
            </Link>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">
                دمج جهات الاتصال - Merge Contacts
              </h1>
              <p className="text-sm text-gray-600 mt-1">
                {step === 'select' && 'Select two contacts to merge'}
                {step === 'compare' && 'Choose which data to keep'}
                {step === 'preview' && 'Preview merged contact'}
                {step === 'confirm' && 'Confirm merge'}
                {step === 'success' && 'Merge completed'}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Progress Steps */}
      <div className="bg-white border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            {[
              { key: 'select', label: 'Select Contacts' },
              { key: 'compare', label: 'Compare Fields' },
              { key: 'preview', label: 'Preview' },
              { key: 'confirm', label: 'Confirm' }
            ].map((s, idx) => (
              <div key={s.key} className="flex items-center">
                <div className={`flex items-center gap-2 ${
                  step === s.key ? 'text-blue-600' : 
                  ['select', 'compare', 'preview', 'confirm'].indexOf(step) > idx ? 'text-green-600' : 'text-gray-400'
                }`}>
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                    step === s.key ? 'bg-blue-600 text-white' :
                    ['select', 'compare', 'preview', 'confirm'].indexOf(step) > idx ? 'bg-green-600 text-white' : 'bg-gray-200'
                  }`}>
                    {['select', 'compare', 'preview', 'confirm'].indexOf(step) > idx ? <Check size={16} /> : idx + 1}
                  </div>
                  <span className="font-medium hidden sm:inline">{s.label}</span>
                </div>
                {idx < 3 && <ChevronRight className="mx-4 text-gray-400" size={20} />}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Step 1: Select Contacts */}
        {step === 'select' && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Source Contact */}
              <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-4">
                  Source Contact (will be archived)
                </h3>
                {sourceContact ? (
                  <ContactCard
                    contact={sourceContact}
                    type="source"
                    onRemove={() => setSourceContact(null)}
                  />
                ) : (
                  <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
                    <p className="text-gray-600">Search and select a contact</p>
                  </div>
                )}
              </div>

              {/* Target Contact */}
              <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-4">
                  Target Contact (will be kept)
                </h3>
                {targetContact ? (
                  <ContactCard
                    contact={targetContact}
                    type="target"
                    onRemove={() => setTargetContact(null)}
                  />
                ) : (
                  <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
                    <p className="text-gray-600">Search and select a contact</p>
                  </div>
                )}
              </div>
            </div>

            {/* Search */}
            <div className="bg-white border rounded-lg p-6">
              <div className="relative">
                <Search className="absolute left-3 top-3 text-gray-400" size={20} />
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder="Search contacts by name, email, or phone..."
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900"
                />
              </div>

              {searching && (
                <div className="mt-4 text-center text-gray-600">
                  <Loader2 className="inline animate-spin mr-2" size={20} />
                  Searching...
                </div>
              )}

              {searchResults.length > 0 && (
                <div className="mt-4 space-y-2 max-h-96 overflow-y-auto">
                  {searchResults.map(contact => (
                    <button
                      key={contact.id}
                      onClick={() => {
                        if (!sourceContact) {
                          handleSelectContact(contact, 'source')
                        } else if (!targetContact) {
                          handleSelectContact(contact, 'target')
                        } else {
                          toast.error('Both contacts are already selected')
                        }
                      }}
                      className="w-full text-left p-3 border border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-colors"
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          {contact.type === 'INDIVIDUAL' ? <User size={18} /> : <Building2 size={18} />}
                          <div>
                            <p className="font-medium text-gray-900">{contact.name}</p>
                            <p className="text-sm text-gray-600">{contact.email || contact.phone || contact.uniqueContactId}</p>
                          </div>
                        </div>
                        <span className="text-xs bg-gray-100 px-2 py-1 rounded">{contact.type}</span>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Navigation */}
            <div className="flex justify-between">
              <Link
                href="/contacts"
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                Cancel
              </Link>
              <button
                onClick={() => setStep('compare')}
                disabled={!sourceContact || !targetContact}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
              >
                Next: Compare Fields
              </button>
            </div>
          </div>
        )}

        {/* Step 2: Compare Fields */}
        {step === 'compare' && sourceContact && targetContact && (
          <div className="space-y-6">
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 flex items-start gap-3">
              <AlertTriangle className="text-yellow-600 flex-shrink-0 mt-0.5" size={20} />
              <div className="text-sm text-yellow-800">
                <p className="font-semibold mb-1">Choose which data to keep</p>
                <p>Select the value you want to keep for each field. Smart defaults are pre-selected based on data quality.</p>
              </div>
            </div>

            <div className="bg-white border rounded-lg overflow-hidden">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Field
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Source Contact
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Target Contact
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {Object.keys(fieldChoices).map(field => {
                    const sourceValue = (sourceContact as any)[field]
                    const targetValue = (targetContact as any)[field]
                    const isDifferent = JSON.stringify(sourceValue) !== JSON.stringify(targetValue)

                    return (
                      <tr key={field} className={isDifferent ? 'bg-yellow-50' : ''}>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                          {field.charAt(0).toUpperCase() + field.slice(1).replace(/([A-Z])/g, ' $1')}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-900">
                          <label className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="radio"
                              name={field}
                              checked={fieldChoices[field] === 'source'}
                              onChange={() => handleFieldChoice(field, 'source')}
                              className="w-4 h-4 text-blue-600"
                            />
                            <span className={fieldChoices[field] === 'source' ? 'font-semibold' : ''}>
                              {renderFieldValue(sourceValue)}
                            </span>
                          </label>
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-900">
                          <label className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="radio"
                              name={field}
                              checked={fieldChoices[field] === 'target'}
                              onChange={() => handleFieldChoice(field, 'target')}
                              className="w-4 h-4 text-blue-600"
                            />
                            <span className={fieldChoices[field] === 'target' ? 'font-semibold' : ''}>
                              {renderFieldValue(targetValue)}
                            </span>
                          </label>
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>

            {/* Navigation */}
            <div className="flex justify-between">
              <button
                onClick={() => setStep('select')}
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                Back
              </button>
              <button
                onClick={() => setStep('preview')}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                Next: Preview
              </button>
            </div>
          </div>
        )}

        {/* Step 3: Preview */}
        {step === 'preview' && (
          <div className="space-y-6">
            <div className="bg-white border rounded-lg p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Merged Contact Preview</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {Object.keys(mergedData).map(field => (
                  <div key={field} className="border-b border-gray-200 pb-2">
                    <p className="text-sm text-gray-600">
                      {field.charAt(0).toUpperCase() + field.slice(1).replace(/([A-Z])/g, ' $1')}
                    </p>
                    <p className="text-base text-gray-900 font-medium">
                      {renderFieldValue(mergedData[field])}
                    </p>
                  </div>
                ))}
              </div>
            </div>

            {/* Navigation */}
            <div className="flex justify-between">
              <button
                onClick={() => setStep('compare')}
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                Back
              </button>
              <button
                onClick={() => setStep('confirm')}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                Next: Confirm
              </button>
            </div>
          </div>
        )}

        {/* Step 4: Confirm */}
        {step === 'confirm' && (
          <div className="space-y-6">
            <div className="bg-red-50 border-2 border-red-200 rounded-lg p-6">
              <div className="flex items-start gap-3">
                <AlertTriangle className="text-red-600 flex-shrink-0 mt-1" size={24} />
                <div>
                  <h3 className="text-lg font-semibold text-red-900 mb-2">
                    This action cannot be undone!
                  </h3>
                  <p className="text-sm text-red-800 mb-4">
                    The source contact will be archived and all its data will be merged into the target contact.
                    Relationships, activities, and history will be transferred.
                  </p>
                  <div className="space-y-2 text-sm">
                    <p>
                      <span className="font-semibold">Source (will be archived):</span> {sourceContact?.name}
                    </p>
                    <p>
                      <span className="font-semibold">Target (will be kept):</span> {targetContact?.name}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white border rounded-lg p-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Reason for Merge <span className="text-red-500">*</span>
              </label>
              <textarea
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                placeholder="Explain why these contacts are being merged..."
                rows={4}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900"
                required
              />
            </div>

            {/* Navigation */}
            <div className="flex justify-between">
              <button
                onClick={() => setStep('preview')}
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                disabled={merging}
              >
                Back
              </button>
              <button
                onClick={handleMerge}
                disabled={!reason.trim() || merging}
                className="flex items-center gap-2 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
              >
                {merging ? (
                  <>
                    <Loader2 className="animate-spin" size={18} />
                    Merging...
                  </>
                ) : (
                  'Merge Contacts'
                )}
              </button>
            </div>
          </div>
        )}

        {/* Step 5: Success */}
        {step === 'success' && mergedContactId && (
          <div className="max-w-2xl mx-auto text-center py-12">
            <div className="bg-green-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-6">
              <Check className="text-green-600" size={40} />
            </div>
            <h2 className="text-2xl font-bold text-gray-900 mb-4">
              تم دمج جهات الاتصال بنجاح - Contacts Merged Successfully!
            </h2>
            <p className="text-gray-600 mb-8">
              The contacts have been merged and the source contact has been archived.
            </p>
            <div className="flex items-center justify-center gap-4">
              <Link
                href="/contacts"
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                Back to Contacts
              </Link>
              <Link
                href={`/contacts/${mergedContactId}`}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                View Merged Contact
              </Link>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export default function MergePage() {
  return (
    <ProtectedRoute>
      <MergeContent />
    </ProtectedRoute>
  )
}
