import { useState, useEffect, useCallback } from 'react'
import type { NextPage } from 'next'
import Head from 'next/head'
import Link from 'next/link'

interface Report {
  id: number
  source_url: string
  source_domain: string
  reporter_email?: string
  reporter_name?: string
  category_suggestions: string[]
  description: string
  priority: string
  status: string
  created_at: string
}

const ReportsManagement: NextPage = () => {
  const [reports, setReports] = useState<Report[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState('pending')

  const fetchReports = useCallback(async () => {
    try {
      const response = await fetch(`/api/admin/reports?status=${filter}`)
      if (response.ok) {
        const data = await response.json()
        setReports(data)
      }
    } catch (error) {
      console.error('Failed to fetch reports:', error)
    } finally {
      setLoading(false)
    }
  }, [filter])

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

  const updateReport = async (id: number, status: string, notes?: string) => {
    try {
      const response = await fetch(`/api/admin/reports/${id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          status,
          admin_notes: notes,
        }),
      })

      if (response.ok) {
        fetchReports()
      }
    } catch (error) {
      console.error('Failed to update report:', error)
    }
  }

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'urgent': return '#dc2626'
      case 'high': return '#ea580c'
      case 'medium': return '#d97706'
      default: return '#6b7280'
    }
  }

  return (
    <div>
      <Head>
        <title>Správa hlásení - Infohliadka</title>
      </Head>

      <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
        <h1>Správa hlásení</h1>
        
        <div style={{ marginBottom: '20px' }}>
          <label>Filter: </label>
          <select 
            value={filter} 
            onChange={(e) => setFilter(e.target.value)}
            style={{ padding: '8px', marginLeft: '10px' }}
          >
            <option value="pending">Čakajúce</option>
            <option value="in_review">V spracovaní</option>
            <option value="approved">Schválené</option>
            <option value="rejected">Zamietnuté</option>
          </select>
        </div>

        {loading ? (
          <div>Loading...</div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ backgroundColor: '#f3f4f6' }}>
                  <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Doména</th>
                  <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Kategórie</th>
                  <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Priorita</th>
                  <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Status</th>
                  <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Dátum</th>
                  <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Akcie</th>
                </tr>
              </thead>
              <tbody>
                {reports.map((report) => (
                  <tr key={report.id}>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      <a href={report.source_url} target="_blank" rel="noopener noreferrer">
                        {report.source_domain}
                      </a>
                      <div style={{ fontSize: '12px', color: '#6b7280' }}>
                        {report.reporter_name || 'Anonymous'}
                      </div>
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      {report.category_suggestions.join(', ')}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      <span style={{ color: getPriorityColor(report.priority), fontWeight: 'bold' }}>
                        {report.priority}
                      </span>
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>{report.status}</td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      {new Date(report.created_at).toLocaleDateString('sk-SK')}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      {report.status === 'pending' && (
                        <div style={{ display: 'flex', gap: '5px', flexDirection: 'column' }}>
                          <button 
                            onClick={() => updateReport(report.id, 'approved')}
                            style={{ 
                              padding: '4px 8px', 
                              backgroundColor: '#10b981', 
                              color: 'white', 
                              border: 'none', 
                              borderRadius: '4px',
                              cursor: 'pointer',
                              fontSize: '12px'
                            }}
                          >
                            Schváliť
                          </button>
                          <button 
                            onClick={() => updateReport(report.id, 'rejected', 'Insufficient evidence')}
                            style={{ 
                              padding: '4px 8px', 
                              backgroundColor: '#ef4444', 
                              color: 'white', 
                              border: 'none', 
                              borderRadius: '4px',
                              cursor: 'pointer',
                              fontSize: '12px'
                            }}
                          >
                            Zamietnuť
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <div style={{ marginTop: '30px' }}>
          <Link href="/admin" style={{ 
            padding: '10px 20px', 
            backgroundColor: '#6b7280', 
            color: 'white', 
            textDecoration: 'none', 
            borderRadius: '6px' 
          }}>
            ← Späť na dashboard
          </Link>
        </div>
      </div>
    </div>
  )
}

export default ReportsManagement