import { useEffect, useState, useCallback } from 'react'
import pendingIdentificationsApi, { PendingIdentification } from '../api/pendingIdentifications'
import { apiClient } from '../api/client'

export default function ApproveIdentified() {
  const [pendingIdentifications, setPendingIdentifications] = useState<PendingIdentification[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [decisions, setDecisions] = useState<Record<number, 'approve' | 'deny' | null>>({})
  const [submitting, setSubmitting] = useState(false)
  const [includeDenied, setIncludeDenied] = useState(false)

  const loadPendingIdentifications = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const response = await pendingIdentificationsApi.list(includeDenied)
      setPendingIdentifications(response.items)
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to load pending identifications')
      console.error('Error loading pending identifications:', err)
    } finally {
      setLoading(false)
    }
  }, [includeDenied])

  useEffect(() => {
    loadPendingIdentifications()
  }, [loadPendingIdentifications])

  const formatDate = (dateString: string | null | undefined): string => {
    if (!dateString) return '-'
    try {
      const date = new Date(dateString)
      return date.toLocaleDateString()
    } catch {
      return dateString
    }
  }

  const formatName = (pending: PendingIdentification): string => {
    const parts = [
      pending.first_name,
      pending.middle_name,
      pending.last_name,
    ].filter(Boolean)
    if (pending.maiden_name) {
      parts.push(`(${pending.maiden_name})`)
    }
    return parts.join(' ')
  }

  const handleDecisionChange = (id: number, decision: 'approve' | 'deny') => {
    setDecisions(prev => ({
      ...prev,
      [id]: decision
    }))
  }

  const handleSubmit = async () => {
    // Get all decisions that have been made, for pending or denied items (not approved)
    const decisionsList = Object.entries(decisions)
      .filter(([id, decision]) => {
        const pending = pendingIdentifications.find(p => p.id === parseInt(id))
        return decision !== null && pending && pending.status !== 'approved'
      })
      .map(([id, decision]) => ({
        id: parseInt(id),
        decision: decision!
      }))

    if (decisionsList.length === 0) {
      alert('Please select Approve or Deny for at least one identification.')
      return
    }

    if (!confirm(`Submit ${decisionsList.length} decision(s)?`)) {
      return
    }

    setSubmitting(true)
    try {
      const response = await pendingIdentificationsApi.approveDeny({
        decisions: decisionsList
      })

      const message = [
        `✅ Approved: ${response.approved}`,
        `❌ Denied: ${response.denied}`,
        response.errors.length > 0 ? `⚠️ Errors: ${response.errors.length}` : ''
      ].filter(Boolean).join('\n')

      alert(message)

      if (response.errors.length > 0) {
        console.error('Errors:', response.errors)
      }

      // Reload the list to show updated status
      await loadPendingIdentifications()
      // Clear decisions
      setDecisions({})
    } catch (err: any) {
      const errorMessage = err.response?.data?.detail || err.message || 'Failed to submit decisions'
      alert(`Error: ${errorMessage}`)
      console.error('Error submitting decisions:', err)
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div>
      <div className="bg-white rounded-lg shadow p-6">
        <h1 className="text-2xl font-bold text-gray-900 mb-6">Approve Identified</h1>
        
        {loading && (
          <div className="text-center py-8">
            <p className="text-gray-600">Loading identified people...</p>
          </div>
        )}

        {error && (
          <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded text-red-700">
            <p className="font-semibold">Error loading data</p>
            <p className="text-sm mt-1">{error}</p>
            <button
              onClick={loadPendingIdentifications}
              className="mt-3 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
            >
              Retry
            </button>
          </div>
        )}

        {!loading && !error && (
          <>
            <div className="mb-4 flex items-center justify-between">
              <div className="text-sm text-gray-600">
                Total pending identifications: <span className="font-semibold">{pendingIdentifications.length}</span>
              </div>
              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={includeDenied}
                    onChange={(e) => setIncludeDenied(e.target.checked)}
                    className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">Include denied</span>
                </label>
                <button
                  onClick={handleSubmit}
                  disabled={submitting || Object.values(decisions).filter(d => d !== null).length === 0}
                  className="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium"
                >
                  {submitting ? 'Submitting...' : 'Submit Decisions'}
                </button>
              </div>
            </div>

            {pendingIdentifications.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <p>No pending identifications found.</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <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">
                        Name
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Date of Birth
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Face
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        User
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Created
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Approve
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {pendingIdentifications.map((pending) => {
                      const isDenied = pending.status === 'denied'
                      const isApproved = pending.status === 'approved'
                      return (
                      <tr key={pending.id} className={`hover:bg-gray-50 ${isDenied ? 'opacity-60 bg-gray-50' : ''}`}>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm font-medium text-gray-900">
                            {formatName(pending)}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-500">
                            {formatDate(pending.date_of_birth)}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center">
                            {pending.photo_id ? (
                              <div
                                className="cursor-pointer hover:opacity-90 transition-opacity"
                                onClick={() => {
                                  const photoUrl = `${apiClient.defaults.baseURL}/api/v1/photos/${pending.photo_id}/image`
                                  window.open(photoUrl, '_blank')
                                }}
                                title="Click to open full photo"
                              >
                                <img
                                  src={`/api/v1/faces/${pending.face_id}/crop`}
                                  alt={`Face ${pending.face_id}`}
                                  className="w-16 h-16 object-cover rounded border border-gray-300"
                                  loading="lazy"
                                  onError={(e) => {
                                    const target = e.target as HTMLImageElement
                                    target.style.display = 'none'
                                    const parent = target.parentElement
                                    if (parent && !parent.querySelector('.error-fallback')) {
                                      const fallback = document.createElement('div')
                                      fallback.className = 'text-gray-400 text-xs error-fallback'
                                      fallback.textContent = `#${pending.face_id}`
                                      parent.appendChild(fallback)
                                    }
                                  }}
                                />
                              </div>
                            ) : (
                              <img
                                src={`/api/v1/faces/${pending.face_id}/crop`}
                                alt={`Face ${pending.face_id}`}
                                className="w-16 h-16 object-cover rounded border border-gray-300"
                                loading="lazy"
                                onError={(e) => {
                                  const target = e.target as HTMLImageElement
                                  target.style.display = 'none'
                                  const parent = target.parentElement
                                  if (parent && !parent.querySelector('.error-fallback')) {
                                    const fallback = document.createElement('div')
                                    fallback.className = 'text-gray-400 text-xs error-fallback'
                                    fallback.textContent = `#${pending.face_id}`
                                    parent.appendChild(fallback)
                                  }
                                }}
                              />
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-500">
                            {pending.user_name || pending.user_email}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-500">
                            {formatDate(pending.created_at)}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {isApproved ? (
                            <div className="text-sm text-green-600 font-medium">Approved</div>
                          ) : (
                            <div className="flex flex-col gap-2">
                              {isDenied && (
                                <span className="text-xs text-red-600 font-medium">(Denied)</span>
                              )}
                              <div className="flex items-center gap-4">
                                <label className="flex items-center gap-2 cursor-pointer">
                                  <input
                                    type="radio"
                                    name={`decision-${pending.id}`}
                                    value="approve"
                                    checked={decisions[pending.id] === 'approve'}
                                    onChange={() => handleDecisionChange(pending.id, 'approve')}
                                    className="w-4 h-4 text-green-600 focus:ring-green-500"
                                  />
                                  <span className="text-sm text-gray-700">Approve</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                  <input
                                    type="radio"
                                    name={`decision-${pending.id}`}
                                    value="deny"
                                    checked={decisions[pending.id] === 'deny'}
                                    onChange={() => handleDecisionChange(pending.id, 'deny')}
                                    className="w-4 h-4 text-red-600 focus:ring-red-500"
                                  />
                                  <span className="text-sm text-gray-700">Deny</span>
                                </label>
                              </div>
                            </div>
                          )}
                        </td>
                      </tr>
                    )
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  )
}

