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

interface Source {
  id: number
  url: string
  domain: string
  title?: string
  type: string
  status: string
  risk_level: number
  created_at: string
}

const SourcesManagement: NextPage = () => {
  const [sources, setSources] = useState<Source[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState('pending')

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

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

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

      if (response.ok) {
        fetchSources() // Refresh the list
      }
    } catch (error) {
      console.error('Failed to update source:', error)
    }
  }

  const getRiskColor = (level: number) => {
    if (level >= 4) return '#ef4444'
    if (level >= 3) return '#f59e0b'
    return '#6b7280'
  }

  return (
    <div>
      <Head>
        <title>Správa zdrojov - Infohliadka</title>
      </Head>

      <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
        <h1>Správa zdrojov</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="verified">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' }}>Typ</th>
                  <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Riziko</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>
                {sources.map((source) => (
                  <tr key={source.id}>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      <a href={source.url} target="_blank" rel="noopener noreferrer">
                        {source.domain}
                      </a>
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>{source.type}</td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      <span style={{ color: getRiskColor(source.risk_level), fontWeight: 'bold' }}>
                        {source.risk_level}
                      </span>
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>{source.status}</td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      {new Date(source.created_at).toLocaleDateString('sk-SK')}
                    </td>
                    <td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
                      {source.status === 'pending' && (
                        <div style={{ display: 'flex', gap: '5px' }}>
                          <button 
                            onClick={() => updateSource(source.id, 'verified', source.risk_level)}
                            style={{ 
                              padding: '4px 8px', 
                              backgroundColor: '#10b981', 
                              color: 'white', 
                              border: 'none', 
                              borderRadius: '4px',
                              cursor: 'pointer'
                            }}
                          >
                            Schváliť
                          </button>
                          <button 
                            onClick={() => updateSource(source.id, 'rejected', 0)}
                            style={{ 
                              padding: '4px 8px', 
                              backgroundColor: '#ef4444', 
                              color: 'white', 
                              border: 'none', 
                              borderRadius: '4px',
                              cursor: 'pointer'
                            }}
                          >
                            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 SourcesManagement
