'use client'

import React, { useState, useMemo, useCallback } from 'react'
import {
  type InformationAsset,
  type AssetCategory,
  type AssetClassification,
  type ProtectionLevel,
  ASSET_CATEGORY_LABELS,
  CLASSIFICATION_LABELS,
  PROTECTION_LABELS,
} from '../_types'

// ============================================================================
// Local storage key (persisted in SDK state via JSONB)
// ============================================================================

const STORAGE_KEY = 'isms_assets'

function loadAssets(): InformationAsset[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) : []
  } catch { return [] }
}

function saveAssets(assets: InformationAsset[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(assets))
}

// ============================================================================
// Protection level colors
// ============================================================================

const protectionColors: Record<ProtectionLevel, string> = {
  normal: 'bg-green-100 text-green-800',
  high: 'bg-amber-100 text-amber-800',
  very_high: 'bg-red-100 text-red-800',
}

const classificationColors: Record<AssetClassification, string> = {
  PUBLIC: 'bg-gray-100 text-gray-600',
  INTERNAL: 'bg-blue-100 text-blue-700',
  CONFIDENTIAL: 'bg-amber-100 text-amber-800',
  STRICTLY_CONFIDENTIAL: 'bg-red-100 text-red-800',
}

// ============================================================================
// Component
// ============================================================================

export function AssetsTab() {
  const [assets, setAssets] = useState<InformationAsset[]>(() => loadAssets())
  const [showForm, setShowForm] = useState(false)
  const [filterCategory, setFilterCategory] = useState<AssetCategory | 'ALL'>('ALL')
  const [editingId, setEditingId] = useState<string | null>(null)

  // Form state
  const [form, setForm] = useState<Partial<InformationAsset>>({
    category: 'SOFTWARE',
    classification: 'INTERNAL',
    protectionNeed: { confidentiality: 'normal', integrity: 'normal', availability: 'normal' },
  })

  const filtered = useMemo(() => {
    if (filterCategory === 'ALL') return assets
    return assets.filter((a) => a.category === filterCategory)
  }, [assets, filterCategory])

  const stats = useMemo(() => ({
    total: assets.length,
    byCategory: Object.entries(ASSET_CATEGORY_LABELS).map(([cat, label]) => ({
      category: cat,
      label,
      count: assets.filter((a) => a.category === cat).length,
    })),
    highProtection: assets.filter(
      (a) =>
        a.protectionNeed.confidentiality === 'very_high' ||
        a.protectionNeed.integrity === 'very_high' ||
        a.protectionNeed.availability === 'very_high'
    ).length,
  }), [assets])

  const handleSave = useCallback(() => {
    if (!form.name || !form.category || !form.owner) return

    const now = new Date().toISOString()
    const asset: InformationAsset = {
      id: editingId || `asset_${Date.now()}`,
      name: form.name || '',
      category: form.category as AssetCategory,
      description: form.description || '',
      owner: form.owner || '',
      location: form.location || '',
      classification: form.classification as AssetClassification || 'INTERNAL',
      protectionNeed: form.protectionNeed || { confidentiality: 'normal', integrity: 'normal', availability: 'normal' },
      vendor: form.vendor,
      notes: form.notes,
      createdAt: editingId ? (assets.find((a) => a.id === editingId)?.createdAt || now) : now,
      updatedAt: now,
    }

    const updated = editingId
      ? assets.map((a) => (a.id === editingId ? asset : a))
      : [...assets, asset]

    setAssets(updated)
    saveAssets(updated)
    setShowForm(false)
    setEditingId(null)
    setForm({
      category: 'SOFTWARE',
      classification: 'INTERNAL',
      protectionNeed: { confidentiality: 'normal', integrity: 'normal', availability: 'normal' },
    })
  }, [form, editingId, assets])

  const handleDelete = useCallback((id: string) => {
    const updated = assets.filter((a) => a.id !== id)
    setAssets(updated)
    saveAssets(updated)
  }, [assets])

  const handleEdit = useCallback((asset: InformationAsset) => {
    setForm(asset)
    setEditingId(asset.id)
    setShowForm(true)
  }, [])

  const handleExport = useCallback(() => {
    const csv = [
      ['Name', 'Kategorie', 'Eigentuemer', 'Standort', 'Klassifizierung', 'C', 'I', 'A', 'Beschreibung'].join(';'),
      ...assets.map((a) =>
        [a.name, ASSET_CATEGORY_LABELS[a.category], a.owner, a.location,
         CLASSIFICATION_LABELS[a.classification],
         PROTECTION_LABELS[a.protectionNeed.confidentiality],
         PROTECTION_LABELS[a.protectionNeed.integrity],
         PROTECTION_LABELS[a.protectionNeed.availability],
         a.description].join(';')
      ),
    ].join('\n')
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `asset-register-${new Date().toISOString().slice(0, 10)}.csv`
    a.click()
    URL.revokeObjectURL(url)
  }, [assets])

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <div className="text-xs text-gray-500 uppercase">Gesamt</div>
          <div className="text-2xl font-bold text-gray-900 mt-1">{stats.total}</div>
        </div>
        {stats.byCategory.filter((s) => s.count > 0).slice(0, 2).map((s) => (
          <div key={s.category} className="bg-white rounded-xl border border-gray-200 p-4">
            <div className="text-xs text-gray-500 uppercase">{s.label}</div>
            <div className="text-2xl font-bold text-gray-900 mt-1">{s.count}</div>
          </div>
        ))}
        <div className="bg-white rounded-xl border border-red-200 p-4">
          <div className="text-xs text-red-600 uppercase">Sehr hoher Schutzbedarf</div>
          <div className="text-2xl font-bold text-red-700 mt-1">{stats.highProtection}</div>
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center justify-between">
        <div className="flex gap-2">
          {(['ALL', ...Object.keys(ASSET_CATEGORY_LABELS)] as const).map((cat) => (
            <button
              key={cat}
              onClick={() => setFilterCategory(cat as AssetCategory | 'ALL')}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                filterCategory === cat ? 'bg-purple-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              {cat === 'ALL' ? 'Alle' : ASSET_CATEGORY_LABELS[cat as AssetCategory]}
            </button>
          ))}
        </div>
        <div className="flex gap-2">
          <button onClick={handleExport} className="px-3 py-1.5 rounded-lg text-sm font-medium bg-gray-100 text-gray-600 hover:bg-gray-200">
            CSV Export
          </button>
          <button onClick={() => { setShowForm(true); setEditingId(null) }} className="px-4 py-1.5 rounded-lg text-sm font-medium bg-purple-600 text-white hover:bg-purple-700">
            + Asset hinzufuegen
          </button>
        </div>
      </div>

      {/* Form */}
      {showForm && (
        <div className="bg-white rounded-xl border border-purple-200 p-6 space-y-4">
          <h3 className="font-semibold text-gray-900">{editingId ? 'Asset bearbeiten' : 'Neues Asset'}</h3>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Name *</label>
              <input value={form.name || ''} onChange={(e) => setForm({ ...form, name: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="z.B. PostgreSQL Produktions-DB" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Kategorie *</label>
              <select value={form.category || 'SOFTWARE'} onChange={(e) => setForm({ ...form, category: e.target.value as AssetCategory })} className="w-full border rounded-lg px-3 py-2 text-sm">
                {Object.entries(ASSET_CATEGORY_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Eigentuemer *</label>
              <input value={form.owner || ''} onChange={(e) => setForm({ ...form, owner: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="Person oder Abteilung" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Standort</label>
              <input value={form.location || ''} onChange={(e) => setForm({ ...form, location: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="z.B. Hetzner Cloud EU" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Klassifizierung</label>
              <select value={form.classification || 'INTERNAL'} onChange={(e) => setForm({ ...form, classification: e.target.value as AssetClassification })} className="w-full border rounded-lg px-3 py-2 text-sm">
                {Object.entries(CLASSIFICATION_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Vendor/Anbieter</label>
              <input value={form.vendor || ''} onChange={(e) => setForm({ ...form, vendor: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="Optional" />
            </div>
          </div>

          {/* Protection need */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Schutzbedarf (CIA)</label>
            <div className="grid grid-cols-3 gap-4">
              {(['confidentiality', 'integrity', 'availability'] as const).map((dim) => (
                <div key={dim}>
                  <label className="block text-xs text-gray-500 mb-1">
                    {dim === 'confidentiality' ? 'Vertraulichkeit' : dim === 'integrity' ? 'Integritaet' : 'Verfuegbarkeit'}
                  </label>
                  <select
                    value={form.protectionNeed?.[dim] || 'normal'}
                    onChange={(e) => setForm({ ...form, protectionNeed: { ...form.protectionNeed!, [dim]: e.target.value as ProtectionLevel } })}
                    className="w-full border rounded-lg px-3 py-2 text-sm"
                  >
                    {Object.entries(PROTECTION_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                  </select>
                </div>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
            <textarea value={form.description || ''} onChange={(e) => setForm({ ...form, description: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" rows={2} />
          </div>

          <div className="flex gap-2 justify-end">
            <button onClick={() => { setShowForm(false); setEditingId(null) }} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
            <button onClick={handleSave} className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700">Speichern</button>
          </div>
        </div>
      )}

      {/* Table */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Name</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Kategorie</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Eigentuemer</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Klassifizierung</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">C</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">I</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">A</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Aktionen</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {filtered.length === 0 ? (
              <tr>
                <td colSpan={8} className="px-4 py-8 text-center text-gray-400">
                  Keine Assets erfasst. Klicken Sie auf "Asset hinzufuegen".
                </td>
              </tr>
            ) : (
              filtered.map((a) => (
                <tr key={a.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-medium text-gray-900">{a.name}</td>
                  <td className="px-4 py-3 text-gray-600">{ASSET_CATEGORY_LABELS[a.category]}</td>
                  <td className="px-4 py-3 text-gray-600">{a.owner}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${classificationColors[a.classification]}`}>
                      {CLASSIFICATION_LABELS[a.classification]}
                    </span>
                  </td>
                  <td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs ${protectionColors[a.protectionNeed.confidentiality]}`}>{PROTECTION_LABELS[a.protectionNeed.confidentiality]}</span></td>
                  <td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs ${protectionColors[a.protectionNeed.integrity]}`}>{PROTECTION_LABELS[a.protectionNeed.integrity]}</span></td>
                  <td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs ${protectionColors[a.protectionNeed.availability]}`}>{PROTECTION_LABELS[a.protectionNeed.availability]}</span></td>
                  <td className="px-4 py-3">
                    <div className="flex gap-2">
                      <button onClick={() => handleEdit(a)} className="text-xs text-blue-600 hover:text-blue-800">Bearbeiten</button>
                      <button onClick={() => handleDelete(a.id)} className="text-xs text-red-500 hover:text-red-700">Loeschen</button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
