import { useState } from "react"
import type { NextPage } from "next"
import Head from "next/head"
import Link from "next/link"

const BulkImport: NextPage = () => {
  const [importData, setImportData] = useState("")
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<any>(null)

  const handleImport = async () => {
    if (!importData.trim()) return
    
    setLoading(true)
    try {
      const lines = importData.trim().split('\n')
      const sources = lines.map(line => {
        const [domain, risk_level] = line.split(',')
        return {
          domain: domain?.trim(),
          risk_level: parseInt(risk_level?.trim()) || 3
        }
      }).filter(s => s.domain)

      const response = await fetch('/api/admin/bulk-import', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sources })
      })
      
      const data = await response.json()
      setResult(data)
    } catch (error) {
      setResult({ error: 'Import failed' })
    }
    setLoading(false)
  }

  return (
    <div>
      <Head>
        <title>Bulk Import - Infohliadka</title>
      </Head>
      
      <div style={{ padding: '20px' }}>
        <div style={{ marginBottom: '20px' }}>
          <Link href="/admin">← Back to Admin</Link>
        </div>
        
        <h1>Bulk Import Sources</h1>
        <p>Import multiple sources at once. Format: domain,risk_level (one per line)</p>
        
        <textarea
          value={importData}
          onChange={(e) => setImportData(e.target.value)}
          placeholder="example.com,4&#10;badsite.sk,5&#10;spam.org,2"
          rows={10}
          style={{ width: '100%', marginBottom: '10px' }}
        />
        
        <button 
          onClick={handleImport}
          disabled={loading || !importData.trim()}
          style={{ 
            padding: '10px 20px', 
            backgroundColor: loading ? '#ccc' : '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px'
          }}
        >
          {loading ? 'Importing...' : 'Import Sources'}
        </button>
        
        {result && (
          <div style={{ marginTop: '20px', padding: '15px', backgroundColor: '#f8f9fa', border: '1px solid #ddd' }}>
            <h3>Import Result:</h3>
            {result.error ? (
              <p style={{ color: 'red' }}>Error: {result.error}</p>
            ) : (
              <div>
                <p>Total processed: {result.total}</p>
                <p>Successfully imported: {result.imported}</p>
                <p>Skipped (duplicates/invalid): {result.skipped}</p>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}

export default BulkImport