import { useEffect, useState, useCallback } from 'react'
import {
  reportedPhotosApi,
  ReportedPhotoResponse,
  ReviewDecision,
} from '../api/reportedPhotos'
import { apiClient } from '../api/client'
import { useAuth } from '../context/AuthContext'
import { videosApi } from '../api/videos'

export default function ReportedPhotos() {
  const { isAdmin } = useAuth()
  const [reportedPhotos, setReportedPhotos] = useState<ReportedPhotoResponse[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [decisions, setDecisions] = useState<Record<number, 'keep' | 'remove' | null>>({})
  const [reviewNotes, setReviewNotes] = useState<Record<number, string>>({})
  const [submitting, setSubmitting] = useState(false)
  const [clearing, setClearing] = useState(false)
  const [statusFilter, setStatusFilter] = useState<string>('pending')

  const loadReportedPhotos = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const response = await reportedPhotosApi.listReportedPhotos(
        statusFilter || undefined
      )
      setReportedPhotos(response.items)
      
      // Initialize review notes from existing data
      const existingNotes: Record<number, string> = {}
      response.items.forEach((item) => {
        if (item.review_notes) {
          existingNotes[item.id] = item.review_notes
        }
      })
      setReviewNotes(existingNotes)
    } catch (err: any) {
      setError(err.response?.data?.detail || err.message || 'Failed to load reported photos')
      console.error('Error loading reported photos:', err)
    } finally {
      setLoading(false)
    }
  }, [statusFilter])

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

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

  const handleDecisionChange = (id: number, decision: 'keep' | 'remove') => {
    setDecisions((prev) => {
      const currentDecision = prev[id] ?? null
      const nextDecision = currentDecision === decision ? null : decision
      return {
        ...prev,
        [id]: nextDecision,
      }
    })
  }

  const handleReviewNotesChange = (id: number, notes: string) => {
    setReviewNotes((prev) => ({
      ...prev,
      [id]: notes,
    }))
  }

  const handleSubmit = async () => {
    // Get all decisions that have been made for pending or reviewed items
    const decisionsList: ReviewDecision[] = Object.entries(decisions)
      .filter(([id, decision]) => {
        const reported = reportedPhotos.find((p) => p.id === parseInt(id))
        return decision !== null && reported && (reported.status === 'pending' || reported.status === 'reviewed')
      })
      .map(([id, decision]) => ({
        id: parseInt(id),
        decision: decision!,
        review_notes: reviewNotes[parseInt(id)] || null,
      }))

    if (decisionsList.length === 0) {
      alert('Please select Keep or Remove for at least one reported photo.')
      return
    }

    // Check if there are any 'remove' decisions
    const removeDecisions = decisionsList.filter((d) => d.decision === 'remove')
    const keepDecisions = decisionsList.filter((d) => d.decision === 'keep')

    // Show specific confirmation for removal
    if (removeDecisions.length > 0) {
      const removeCount = removeDecisions.length
      const photoDetails = removeDecisions
        .map((d) => {
          const reported = reportedPhotos.find((p) => p.id === d.id)
          return reported?.photo_filename || `Photo #${reported?.photo_id || d.id}`
        })
        .join('\n  - ')

      const confirmMessage = `⚠️ WARNING: You are about to PERMANENTLY REMOVE ${removeCount} photo(s):\n\n  - ${photoDetails}\n\nThis will:\n  • Delete the photo(s) from the database\n  • Delete all faces detected in the photo(s)\n  • Delete all encodings related to those faces\n\nThis action CANNOT be undone!\n\nAre you sure you want to proceed?`

      if (!confirm(confirmMessage)) {
        return
      }
    }

    // Show general confirmation if there are also 'keep' decisions
    if (keepDecisions.length > 0) {
      const confirmMessage = `Submit ${decisionsList.length} decision(s)?\n\nThis will ${
        removeDecisions.length
      } remove photo(s) and ${keepDecisions.length} keep photo(s).`

      if (!confirm(confirmMessage)) {
        return
      }
    }

    setSubmitting(true)
    try {
      const response = await reportedPhotosApi.reviewReportedPhotos({
        decisions: decisionsList,
      })

      const messageParts = [
        `✅ Kept: ${response.kept}`,
        `❌ Removed: ${response.removed}`,
      ]

      if (import.meta.env.DEV && response.errors.length > 0) {
        messageParts.push(`⚠️ Errors: ${response.errors.length}`)
      }

      const message = messageParts.join('\n')

      alert(message)

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

      // Reload the list to show updated status
      await loadReportedPhotos()
      // Clear decisions and notes
      setDecisions({})
      setReviewNotes({})
    } 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 handleClearDatabase = async () => {
    const confirmMessage = [
      'Delete all kept and removed reported photo records from the auth database?',
      '',
      'Only photos with Pending status will remain.',
      'This action cannot be undone.',
    ].join('\n')

    if (!confirm(confirmMessage)) {
      return
    }

    setClearing(true)
    try {
      const response = await reportedPhotosApi.cleanupReportedPhotos()
      const summary = [
        `✅ Deleted ${response.deleted_records} record(s)`,
        response.warnings && response.warnings.length > 0
          ? `ℹ️ ${response.warnings.join('; ')}`
          : '',
        response.errors.length > 0 ? `⚠️ ${response.errors.join('; ')}` : '',
      ]
        .filter(Boolean)
        .join('\n')

      alert(summary || 'Cleanup complete.')

      if (response.errors.length > 0) {
        console.error('Cleanup errors:', response.errors)
      }
      if (response.warnings && response.warnings.length > 0) {
        console.info('Cleanup warnings:', response.warnings)
      }

      await loadReportedPhotos()
    } catch (err: any) {
      const errorMessage =
        err.response?.data?.detail || err.message || 'Failed to cleanup reported photos'
      alert(`Error: ${errorMessage}`)
      console.error('Error clearing reported photos:', 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 reported photos...</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={loadReportedPhotos}
              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 flex-col gap-3">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="text-sm text-gray-600">
                    Total reported photos:{' '}
                    <span className="font-semibold">{reportedPhotos.length}</span>
                  </div>
                  <select
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                    className="px-3 py-1 border border-gray-300 rounded-md text-sm"
                  >
                    <option value="">All Status</option>
                    <option value="pending">Pending</option>
                    <option value="reviewed">Reviewed</option>
                    <option value="dismissed">Dismissed</option>
                  </select>
                </div>
                <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 className="flex flex-wrap items-center gap-3">
                <button
                  onClick={() => {
                    if (!isAdmin) {
                      return
                    }
                    handleClearDatabase()
                  }}
                  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-200 disabled:text-gray-500 disabled:cursor-not-allowed font-medium"
                  title={
                    isAdmin
                      ? 'Delete kept/removed records'
                      : 'Only admins can clear reported photos'
                  }
                >
                  {clearing ? 'Clearing...' : '🗑️ Clear Database'}
                </button>
                <span className="text-sm text-gray-700">
                  Clear kept/removed records
                </span>
              </div>
            </div>

            {reportedPhotos.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <p>No reported photos 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">
                        Photo
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Reported By
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Reported At
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Report Comment
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Status
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Decision
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Review Notes
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {reportedPhotos.map((reported) => {
                      const isReviewed = reported.status === 'reviewed'
                      const isDismissed = reported.status === 'dismissed'
                      const canMakeDecision = !isDismissed && (reported.status === 'pending' || reported.status === 'reviewed')
                      return (
                        <tr
                          key={reported.id}
                          className={`hover:bg-gray-50 ${
                            isReviewed || isDismissed ? 'opacity-60 bg-gray-50' : ''
                          }`}
                        >
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center">
                              {reported.photo_id ? (
                                <div
                                  className="cursor-pointer hover:opacity-90 transition-opacity"
                                  onClick={() => {
                                    const isVideo = reported.photo_media_type === 'video'
                                    const url = isVideo
                                      ? videosApi.getVideoUrl(reported.photo_id)
                                      : `${apiClient.defaults.baseURL}/api/v1/photos/${reported.photo_id}/image`
                                    window.open(url, '_blank')
                                  }}
                                  title={reported.photo_media_type === 'video' ? 'Click to open video' : 'Click to open full photo'}
                                >
                                  {reported.photo_media_type === 'video' ? (
                                    <img
                                      src={videosApi.getThumbnailUrl(reported.photo_id)}
                                      alt={`Video ${reported.photo_id}`}
                                      className="w-24 h-24 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 = `#${reported.photo_id}`
                                          parent.appendChild(fallback)
                                        }
                                      }}
                                    />
                                  ) : (
                                    <img
                                      src={`/api/v1/photos/${reported.photo_id}/image`}
                                      alt={`Photo ${reported.photo_id}`}
                                      className="w-24 h-24 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 = `#${reported.photo_id}`
                                          parent.appendChild(fallback)
                                        }
                                      }}
                                    />
                                  )}
                                </div>
                              ) : (
                                <div className="text-gray-400 text-xs">Photo not found</div>
                              )}
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                              {reported.photo_filename || `Photo #${reported.photo_id}`}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-900">
                              {reported.user_name || 'Unknown'}
                            </div>
                            <div className="text-sm text-gray-500">
                              {reported.user_email || '-'}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-500">
                              {formatDate(reported.reported_at)}
                            </div>
                          </td>
                        <td className="px-6 py-4">
                          {reported.report_comment ? (
                            <div className="text-sm text-gray-700 whitespace-pre-wrap bg-gray-50 p-2 rounded border border-gray-200">
                              {reported.report_comment}
                            </div>
                          ) : (
                            <span className="text-sm text-gray-400 italic">-</span>
                          )}
                        </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <span
                              className={`px-2 py-1 text-xs font-semibold rounded-full ${
                                reported.status === 'pending'
                                  ? 'bg-yellow-100 text-yellow-800'
                                  : reported.status === 'reviewed'
                                  ? 'bg-green-100 text-green-800'
                                  : 'bg-gray-100 text-gray-800'
                              }`}
                            >
                              {reported.status}
                            </span>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            {canMakeDecision ? (
                              <div className="flex items-center gap-4">
                                <label className="flex items-center gap-2 cursor-pointer">
                                  <input
                                    type="checkbox"
                                    name={`decision-${reported.id}-keep`}
                                    value="keep"
                                    checked={decisions[reported.id] === 'keep'}
                                    onChange={() => handleDecisionChange(reported.id, 'keep')}
                                    className="w-4 h-4 text-green-600 focus:ring-green-500"
                                  />
                                  <span className="text-sm text-gray-700">Keep</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                  <input
                                    type="checkbox"
                                    name={`decision-${reported.id}-remove`}
                                    value="remove"
                                    checked={decisions[reported.id] === 'remove'}
                                    onChange={() => handleDecisionChange(reported.id, 'remove')}
                                    className="w-4 h-4 text-red-600 focus:ring-red-500"
                                  />
                                  <span className="text-sm text-gray-700">Remove</span>
                                </label>
                              </div>
                            ) : (
                              <span className="text-sm text-gray-500 italic">-</span>
                            )}
                          </td>
                          <td className="px-6 py-4">
                            {isReviewed || isDismissed ? (
                              <div className="text-sm text-gray-700 whitespace-pre-wrap">
                                {reported.review_notes ? (
                                  <div className="bg-gray-50 p-2 rounded border border-gray-200">
                                    {reported.review_notes}
                                  </div>
                                ) : (
                                  <span className="text-gray-400 italic">-</span>
                                )}
                              </div>
                            ) : (
                              <div className="flex flex-col gap-2">
                                {reported.review_notes && (
                                  <div className="bg-blue-50 p-2 rounded border border-blue-200 text-sm text-gray-700">
                                    <div className="text-xs text-blue-600 font-medium mb-1">
                                      Existing notes:
                                    </div>
                                    <div className="whitespace-pre-wrap">
                                      {reported.review_notes}
                                    </div>
                                  </div>
                                )}
                                <textarea
                                  value={reviewNotes[reported.id] || ''}
                                  onChange={(e) =>
                                    handleReviewNotesChange(reported.id, e.target.value)
                                  }
                                  placeholder="Optional review notes..."
                                  className="w-full px-2 py-1 text-sm border border-gray-300 rounded-md resize-none"
                                  rows={2}
                                />
                              </div>
                            )}
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  )
}

