'use client'

import { useState } from 'react'
import type { SeedURL, Category } from '../types'
import SeedModal from './SeedModal'

export default function SeedsTab({
  seeds,
  allSeeds,
  categories,
  searchQuery,
  setSearchQuery,
  selectedCategory,
  setSelectedCategory,
  onToggleEnabled,
  onDelete,
  onSaved,
}: {
  seeds: SeedURL[]
  allSeeds: SeedURL[]
  categories: Category[]
  searchQuery: string
  setSearchQuery: (q: string) => void
  selectedCategory: string
  setSelectedCategory: (cat: string) => void
  onToggleEnabled: (id: string) => void
  onDelete: (id: string) => void
  onSaved: () => void
}) {
  const [showAddModal, setShowAddModal] = useState(false)
  const [editingSeed, setEditingSeed] = useState<SeedURL | null>(null)

  const filteredSeeds = seeds.filter(seed => {
    const matchesCategory = selectedCategory === 'all' || seed.category === selectedCategory
    const matchesSearch = seed.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         seed.url.toLowerCase().includes(searchQuery.toLowerCase())
    return matchesCategory && matchesSearch
  })

  return (
    <div>
      {/* Header with filters */}
      <div className="flex flex-wrap items-center gap-4 mb-6">
        <div className="flex-1 min-w-[200px]">
          <input
            type="text"
            placeholder="Suche nach Name oder URL..."
            className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
          />
        </div>
        <select
          className="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
          value={selectedCategory}
          onChange={e => setSelectedCategory(e.target.value)}
        >
          <option value="all">Alle Kategorien</option>
          {categories.map(cat => (
            <option key={cat.id} value={cat.name}>{cat.icon} {cat.display_name || cat.name}</option>
          ))}
        </select>
        <button
          onClick={() => setShowAddModal(true)}
          className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors flex items-center gap-2"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          Neue Seed-URL
        </button>
      </div>

      {/* Category Quick Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4 mb-6">
        {categories.map(cat => {
          const count = allSeeds.filter(s => s.category === cat.name).length
          return (
            <button
              key={cat.id}
              onClick={() => setSelectedCategory(selectedCategory === cat.name ? 'all' : cat.name)}
              className={`p-4 rounded-lg border transition-colors text-left ${
                selectedCategory === cat.name
                  ? 'border-primary-500 bg-primary-50'
                  : 'border-slate-200 hover:border-slate-300'
              }`}
            >
              <div className="text-2xl mb-1">{cat.icon}</div>
              <div className="font-medium text-slate-900 text-sm">{cat.display_name || cat.name}</div>
              <div className="text-sm text-slate-500">{count} Seeds</div>
            </button>
          )
        })}
      </div>

      {/* Seeds Table */}
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="text-left py-3 px-4 font-medium text-slate-700">Status</th>
              <th className="text-left py-3 px-4 font-medium text-slate-700">Name</th>
              <th className="text-left py-3 px-4 font-medium text-slate-700">URL</th>
              <th className="text-left py-3 px-4 font-medium text-slate-700">Kategorie</th>
              <th className="text-left py-3 px-4 font-medium text-slate-700">Trust</th>
              <th className="text-left py-3 px-4 font-medium text-slate-700">Dokumente</th>
              <th className="text-left py-3 px-4 font-medium text-slate-700">Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {filteredSeeds.map(seed => (
              <tr key={seed.id} className="border-b border-slate-100 hover:bg-slate-50">
                <td className="py-3 px-4">
                  <button
                    onClick={() => onToggleEnabled(seed.id)}
                    className={`w-10 h-6 rounded-full transition-colors ${
                      seed.enabled ? 'bg-green-500' : 'bg-slate-300'
                    }`}
                  >
                    <span className={`block w-4 h-4 bg-white rounded-full transform transition-transform ${
                      seed.enabled ? 'translate-x-5' : 'translate-x-1'
                    }`} />
                  </button>
                </td>
                <td className="py-3 px-4">
                  <div className="font-medium text-slate-900">{seed.name}</div>
                  <div className="text-sm text-slate-500">{seed.description}</div>
                </td>
                <td className="py-3 px-4">
                  <a href={seed.url} target="_blank" rel="noopener noreferrer" className="text-primary-600 hover:underline text-sm">
                    {seed.url.replace(/^https?:\/\/(www\.)?/, '').slice(0, 30)}...
                  </a>
                </td>
                <td className="py-3 px-4">
                  <span className="inline-flex items-center gap-1 px-2 py-1 bg-slate-100 rounded text-sm">
                    {categories.find(c => c.name === seed.category)?.icon || '📁'}
                    {categories.find(c => c.name === seed.category)?.display_name || seed.category}
                  </span>
                </td>
                <td className="py-3 px-4">
                  <span className={`inline-flex px-2 py-1 rounded text-sm font-medium ${
                    seed.trustBoost >= 0.4 ? 'bg-green-100 text-green-700' :
                    seed.trustBoost >= 0.2 ? 'bg-yellow-100 text-yellow-700' :
                    'bg-slate-100 text-slate-700'
                  }`}>
                    +{seed.trustBoost.toFixed(2)}
                  </span>
                </td>
                <td className="py-3 px-4 text-slate-600">
                  {seed.documentCount?.toLocaleString() || '-'}
                </td>
                <td className="py-3 px-4">
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setEditingSeed(seed)}
                      className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded"
                      title="Bearbeiten"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                      </svg>
                    </button>
                    <button
                      onClick={() => onDelete(seed.id)}
                      className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded"
                      title="Löschen"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {filteredSeeds.length === 0 && (
        <div className="text-center py-12 text-slate-500">
          Keine Seed-URLs gefunden
        </div>
      )}

      {/* Modals */}
      {(showAddModal || editingSeed) && (
        <SeedModal
          seed={editingSeed}
          categories={categories}
          onClose={() => {
            setShowAddModal(false)
            setEditingSeed(null)
          }}
          onSaved={onSaved}
        />
      )}
    </div>
  )
}
