import { useEffect, useState, useCallback } from 'react'
import pendingIdentificationsApi, { 
  PendingIdentification, 
  IdentificationReportResponse,
  UserIdentificationStats 
} from '../api/pendingIdentifications'
import { apiClient } from '../api/client'
import { useAuth } from '../context/AuthContext'

export default function ApproveIdentified() {
  const { isAdmin } = useAuth()
  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 [showReport, setShowReport] = useState(false)
  const [reportData, setReportData] = useState<IdentificationReportResponse | null>(null)
  const [reportLoading, setReportLoading] = useState(false)
  const [reportError, setReportError] = useState<string | null>(null)
  const [dateFrom, setDateFrom] = useState<string>('')
  const [dateTo, setDateTo] = useState<string>('')
  const [clearing, setClearing] = useState(false)

  const loadPendingIdentifications = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const response = await pendingIdentificationsApi.list(includeDenied)
      setPendingIdentifications(response.items)
    } catch (err: any) {
      let errorMessage = 'Failed to load pending identifications'
      if (err.response?.data?.detail) {
        errorMessage = err.response.data.detail
      } else if (err.message) {
        errorMessage = err.message
        // Provide more context for network errors
        if (err.message === 'Network Error' || err.code === 'ERR_NETWORK') {
          errorMessage = `Network Error: Cannot connect to backend API (${apiClient.defaults.baseURL}). Please check:\n1. Backend is running\n2. You are logged in\n3. CORS is configured correctly`
        }
      }
      setError(errorMessage)
      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 => {
      const currentDecision = prev[id]
      // If clicking the same checkbox, deselect it
      if (currentDecision === decision) {
        const updated = { ...prev }
        delete updated[id]
        return updated
      }
      // Otherwise, set the new decision (this will automatically deselect the other)
      return {
        ...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)
    }
  }

  const loadReport = useCallback(async () => {
    setReportLoading(true)
    setReportError(null)
    try {
      const response = await pendingIdentificationsApi.getReport(
        dateFrom || undefined,
        dateTo || undefined
      )
      setReportData(response)
    } catch (err: any) {
      setReportError(err.response?.data?.detail || err.message || 'Failed to load report')
      console.error('Error loading report:', err)
    } finally {
      setReportLoading(false)
    }
  }, [dateFrom, dateTo])

  // Removed unused handleOpenReport function

  const handleCloseReport = () => {
    setShowReport(false)
    setReportData(null)
    setReportError(null)
    setDateFrom('')
    setDateTo('')
  }

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

  const handleClearDenied = async () => {
    if (!confirm('Are you sure you want to delete all denied records? This action cannot be undone.')) {
      return
    }

    setClearing(true)
    try {
      const response = await pendingIdentificationsApi.clearDenied()
      
      const message = [
        `✅ Deleted ${response.deleted_records} denied record(s)`,
        response.errors.length > 0 ? `⚠️ Errors: ${response.errors.length}` : ''
      ].filter(Boolean).join('\n')

      alert(message)

      if (response.errors.length > 0) {
        console.error('Errors:', response.errors)
        alert('Errors:\n' + response.errors.join('\n'))
      }

      // Reload the list to reflect changes
      await loadPendingIdentifications()
    } catch (err: any) {
      const errorMessage = err.response?.data?.detail || err.message || 'Failed to clear denied records'
      alert(`Error: ${errorMessage}`)
      console.error('Error clearing denied records:', err)
    } finally {
      setClearing(false)
    }
  }

  return (
    <div>
      <div className="bg-white rounded-lg shadow p-6">
        
        {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-3 py-1.5 text-sm bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 font-medium"
            >
              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">
                <button
                  onClick={() => {
                    if (!isAdmin) {
                      return
                    }
                    handleClearDenied()
                  }}
                  disabled={clearing || !isAdmin}
                  className="px-3 py-1.5 text-sm bg-red-100 text-red-700 rounded-md hover:bg-red-200 disabled:bg-gray-300 disabled:text-gray-500 disabled:cursor-not-allowed font-medium"
                  title={
                    isAdmin
                      ? 'Delete all denied records from the database'
                      : 'Only admins can clear denied records'
                  }
                >
                  {clearing ? 'Clearing...' : '🗑️ Clear Database'}
                </button>
                <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-900">
                            {pending.user_name || 'Unknown'}
                          </div>
                          <div className="text-sm text-gray-500">
                            {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="checkbox"
                                    checked={decisions[pending.id] === 'approve'}
                                    onChange={() => {
                                      const currentDecision = decisions[pending.id]
                                      if (currentDecision === 'approve') {
                                        // Deselect if already selected
                                        handleDecisionChange(pending.id, 'approve')
                                      } else {
                                        // Select approve (this will deselect deny if selected)
                                        handleDecisionChange(pending.id, 'approve')
                                      }
                                    }}
                                    className="w-4 h-4 text-green-600 focus:ring-green-500 rounded"
                                  />
                                  <span className="text-sm text-gray-700">Approve</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                  <input
                                    type="checkbox"
                                    checked={decisions[pending.id] === 'deny'}
                                    onChange={() => {
                                      const currentDecision = decisions[pending.id]
                                      if (currentDecision === 'deny') {
                                        // Deselect if already selected
                                        handleDecisionChange(pending.id, 'deny')
                                      } else {
                                        // Select deny (this will deselect approve if selected)
                                        handleDecisionChange(pending.id, 'deny')
                                      }
                                    }}
                                    className="w-4 h-4 text-red-600 focus:ring-red-500 rounded"
                                  />
                                  <span className="text-sm text-gray-700">Deny</span>
                                </label>
                              </div>
                            </div>
                          )}
                        </td>
                      </tr>
                    )
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}
      </div>

      {/* Report Modal */}
      {showReport && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-hidden flex flex-col">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <h2 className="text-xl font-bold text-gray-900">Identification Report</h2>
              <button
                onClick={handleCloseReport}
                className="text-gray-400 hover:text-gray-600 text-2xl font-bold"
              >
                ×
              </button>
            </div>

            <div className="px-6 py-4 border-b border-gray-200">
              <div className="flex items-center gap-4">
                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Date From
                  </label>
                  <input
                    type="date"
                    value={dateFrom}
                    onChange={(e) => setDateFrom(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Date To
                  </label>
                  <input
                    type="date"
                    value={dateTo}
                    onChange={(e) => setDateTo(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div className="flex items-end">
                  <button
                    onClick={loadReport}
                    disabled={reportLoading}
                    className="px-3 py-1.5 text-sm bg-blue-100 text-blue-700 rounded-md hover:bg-blue-200 disabled:bg-gray-300 disabled:text-gray-500 disabled:cursor-not-allowed font-medium"
                  >
                    {reportLoading ? 'Loading...' : 'Apply Filter'}
                  </button>
                </div>
              </div>
            </div>

            <div className="flex-1 overflow-y-auto px-6 py-4">
              {reportLoading && (
                <div className="text-center py-8">
                  <p className="text-gray-600">Loading report...</p>
                </div>
              )}

              {reportError && (
                <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded text-red-700">
                  <p className="font-semibold">Error loading report</p>
                  <p className="text-sm mt-1">{reportError}</p>
                </div>
              )}

              {!reportLoading && !reportError && reportData && (
                <>
                  <div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded">
                    <div className="grid grid-cols-3 gap-4 text-sm">
                      <div>
                        <span className="font-semibold text-gray-700">Total Users:</span>{' '}
                        <span className="text-gray-900">{reportData.total_users}</span>
                      </div>
                      <div>
                        <span className="font-semibold text-gray-700">Total Faces:</span>{' '}
                        <span className="text-gray-900">{reportData.total_faces}</span>
                      </div>
                      <div>
                        <span className="font-semibold text-gray-700">Average per User:</span>{' '}
                        <span className="text-gray-900">
                          {reportData.total_users > 0
                            ? Math.round((reportData.total_faces / reportData.total_users) * 10) / 10
                            : 0}
                        </span>
                      </div>
                    </div>
                  </div>

                  {reportData.items.length === 0 ? (
                    <div className="text-center py-8 text-gray-500">
                      <p>No identifications found for the selected date range.</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">
                              User
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              Email
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              Faces Identified
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              First Identification
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              Last Identification
                            </th>
                          </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200">
                          {reportData.items.map((stat: UserIdentificationStats) => (
                            <tr key={stat.user_id} className="hover:bg-gray-50">
                              <td className="px-6 py-4 whitespace-nowrap">
                                <div className="text-sm font-medium text-gray-900">
                                  {stat.full_name}
                                </div>
                                <div className="text-sm text-gray-500">{stat.username}</div>
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap">
                                <div className="text-sm text-gray-500">{stat.email}</div>
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap">
                                <div className="text-sm font-semibold text-gray-900">
                                  {stat.face_count}
                                </div>
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap">
                                <div className="text-sm text-gray-500">
                                  {formatDateTime(stat.first_identification_date)}
                                </div>
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap">
                                <div className="text-sm text-gray-500">
                                  {formatDateTime(stat.last_identification_date)}
                                </div>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

