'use client'

import { useState, useEffect } from 'react'
import { Clock, User, Edit, Archive, Trash2, GitMerge, Users as UsersIcon, Loader2 } from 'lucide-react'
import { contactsAPI } from '@/lib/api/contacts'
import { toast } from 'react-hot-toast'

interface HistoryEntry {
  id: string
  action: string
  entityType: string
  entityId: string
  userId: string
  user?: {
    name: string
    email: string
  }
  changes?: any
  metadata?: any
  reason?: string
  createdAt: string
}

interface ContactHistoryProps {
  contactId: string
}

export default function ContactHistory({ contactId }: ContactHistoryProps) {
  const [history, setHistory] = useState<HistoryEntry[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetchHistory()
  }, [contactId])

  const fetchHistory = async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await contactsAPI.getHistory(contactId)
      setHistory(data)
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to load history'
      setError(message)
      toast.error(message)
    } finally {
      setLoading(false)
    }
  }

  const getActionIcon = (action: string) => {
    switch (action.toLowerCase()) {
      case 'create':
      case 'created':
        return <User className="h-5 w-5 text-green-600" />
      case 'update':
      case 'updated':
        return <Edit className="h-5 w-5 text-blue-600" />
      case 'archive':
      case 'archived':
        return <Archive className="h-5 w-5 text-orange-600" />
      case 'delete':
      case 'deleted':
        return <Trash2 className="h-5 w-5 text-red-600" />
      case 'merge':
      case 'merged':
        return <GitMerge className="h-5 w-5 text-purple-600" />
      case 'relationship':
      case 'add_relationship':
        return <UsersIcon className="h-5 w-5 text-indigo-600" />
      default:
        return <Clock className="h-5 w-5 text-gray-600" />
    }
  }

  const getActionColor = (action: string) => {
    switch (action.toLowerCase()) {
      case 'create':
      case 'created':
        return 'bg-green-50 border-green-200'
      case 'update':
      case 'updated':
        return 'bg-blue-50 border-blue-200'
      case 'archive':
      case 'archived':
        return 'bg-orange-50 border-orange-200'
      case 'delete':
      case 'deleted':
        return 'bg-red-50 border-red-200'
      case 'merge':
      case 'merged':
        return 'bg-purple-50 border-purple-200'
      case 'relationship':
      case 'add_relationship':
        return 'bg-indigo-50 border-indigo-200'
      default:
        return 'bg-gray-50 border-gray-200'
    }
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    }).format(date)
  }

  const renderChanges = (entry: HistoryEntry) => {
    if (!entry.changes) return null

    const changes = entry.changes
    const changedFields = Object.keys(changes).filter(key => key !== 'updatedAt')

    if (changedFields.length === 0) return null

    return (
      <div className="mt-3 space-y-2">
        <p className="text-xs font-semibold text-gray-700">Changes:</p>
        <div className="space-y-1">
          {changedFields.map(field => (
            <div key={field} className="text-xs bg-white p-2 rounded border border-gray-200">
              <span className="font-medium text-gray-700">{field}:</span>
              <div className="flex items-center gap-2 mt-1">
                <span className="text-red-600 line-through">
                  {changes[field].old !== null && changes[field].old !== undefined 
                    ? String(changes[field].old) 
                    : '(empty)'}
                </span>
                <span className="text-gray-400">→</span>
                <span className="text-green-600">
                  {changes[field].new !== null && changes[field].new !== undefined 
                    ? String(changes[field].new) 
                    : '(empty)'}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
    )
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="text-center py-8 text-red-600">
        <p>{error}</p>
        <button
          onClick={fetchHistory}
          className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Retry
        </button>
      </div>
    )
  }

  if (history.length === 0) {
    return (
      <div className="text-center py-12 text-gray-500">
        <Clock className="h-12 w-12 mx-auto mb-2 text-gray-300" />
        <p>No history records found</p>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Timeline */}
      <div className="relative">
        {/* Vertical line */}
        <div className="absolute left-6 top-0 bottom-0 w-0.5 bg-gray-200" />

        {/* History entries */}
        <div className="space-y-6">
          {history.map((entry, index) => (
            <div key={entry.id} className="relative flex gap-4">
              {/* Icon */}
              <div className={`flex-shrink-0 w-12 h-12 rounded-full border-2 flex items-center justify-center z-10 ${getActionColor(entry.action)}`}>
                {getActionIcon(entry.action)}
              </div>

              {/* Content */}
              <div className="flex-1 pb-6">
                <div className={`border rounded-lg p-4 ${getActionColor(entry.action)}`}>
                  {/* Header */}
                  <div className="flex items-start justify-between mb-2">
                    <div>
                      <h4 className="font-semibold text-gray-900 capitalize">
                        {entry.action.replace('_', ' ')}
                      </h4>
                      {entry.user && (
                        <p className="text-sm text-gray-600">
                          by {entry.user.name}
                        </p>
                      )}
                    </div>
                    <span className="text-xs text-gray-500">
                      {formatDate(entry.createdAt)}
                    </span>
                  </div>

                  {/* Reason */}
                  {entry.reason && (
                    <p className="text-sm text-gray-700 mb-2">
                      <span className="font-medium">Reason:</span> {entry.reason}
                    </p>
                  )}

                  {/* Metadata */}
                  {entry.metadata && (
                    <div className="text-sm text-gray-700">
                      {JSON.stringify(entry.metadata, null, 2)}
                    </div>
                  )}

                  {/* Changes */}
                  {renderChanges(entry)}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
