'use client'

import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { DocumentCard } from './_components/DocumentCard'
import { useConsentDocuments } from './_hooks/useConsentDocuments'

export default function ConsentPage() {
  const router = useRouter()
  const [filter, setFilter] = useState<string>('all')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [newDocForm, setNewDocForm] = useState({ type: 'privacy_policy', name: '', description: '', content: '' })
  const [creating, setCreating] = useState(false)

  const {
    documents,
    loading,
    error,
    previewDoc,
    setPreviewDoc,
    handleRagSuggest,
    handleCreateDocument,
    handleDeleteDocument,
    handlePreview,
  } = useConsentDocuments()

  const filteredDocuments = filter === 'all'
    ? documents
    : documents.filter(d => d.type === filter || d.status === filter)

  const activeCount = documents.filter(d => d.status === 'active').length
  const draftCount = documents.filter(d => d.status === 'draft').length

  async function onRagSuggest() {
    const text = await handleRagSuggest(newDocForm.type, newDocForm.name)
    if (text) setNewDocForm(d => ({ ...d, content: text }))
  }

  async function onCreateDocument() {
    setCreating(true)
    const ok = await handleCreateDocument(newDocForm)
    if (ok) {
      setShowCreateModal(false)
      setNewDocForm({ type: 'privacy_policy', name: '', description: '', content: '' })
    }
    setCreating(false)
  }

  function handleEdit(id: string) {
    router.push('/sdk/workflow')
  }

  const stepInfo = STEP_EXPLANATIONS['consent']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="consent"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
          Neues Dokument
        </button>
      </StepHeader>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="text-sm text-gray-500">Gesamt</div>
          <div className="text-3xl font-bold text-gray-900">{documents.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Aktiv</div>
          <div className="text-3xl font-bold text-green-600">{activeCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">Entwuerfe</div>
          <div className="text-3xl font-bold text-yellow-600">{draftCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Sprachen</div>
          <div className="text-3xl font-bold text-blue-600">
            {[...new Set(documents.map(d => d.language))].length}
          </div>
        </div>
      </div>

      {/* Loading / Error */}
      {loading && (
        <div className="text-center py-8 text-gray-500">Lade Dokumente...</div>
      )}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          {error}
        </div>
      )}

      {/* Quick Actions */}
      <div className="bg-gradient-to-r from-purple-50 to-blue-50 rounded-xl border border-purple-200 p-6">
        <h3 className="font-semibold text-gray-900 mb-4">Schnellaktionen</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <button
            onClick={() => router.push('/sdk/document-generator')}
            className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center"
          >
            <svg className="w-8 h-8 mx-auto text-blue-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            <span className="text-sm font-medium">Datenschutz generieren</span>
          </button>
          <button
            onClick={() => router.push('/sdk/document-generator')}
            className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center"
          >
            <svg className="w-8 h-8 mx-auto text-green-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            <span className="text-sm font-medium">AGB generieren</span>
          </button>
          <button
            onClick={() => router.push('/sdk/document-generator')}
            className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center"
          >
            <svg className="w-8 h-8 mx-auto text-yellow-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
            </svg>
            <span className="text-sm font-medium">Cookie-Richtlinie</span>
          </button>
          <button
            onClick={() => router.push('/sdk/document-generator')}
            className="p-4 bg-white rounded-lg border border-gray-200 hover:border-purple-300 hover:shadow transition-all text-center"
          >
            <svg className="w-8 h-8 mx-auto text-purple-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
            </svg>
            <span className="text-sm font-medium">AVV-Vorlage</span>
          </button>
        </div>
      </div>

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'privacy-policy', 'terms', 'cookie-policy', 'dpa', 'active', 'draft'].map(f => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`px-3 py-1 text-sm rounded-full transition-colors ${
              filter === f
                ? 'bg-purple-600 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            {f === 'all' ? 'Alle' :
             f === 'privacy-policy' ? 'Datenschutz' :
             f === 'terms' ? 'AGB' :
             f === 'cookie-policy' ? 'Cookie' :
             f === 'dpa' ? 'AVV' :
             f === 'active' ? 'Aktiv' : 'Entwuerfe'}
          </button>
        ))}
      </div>

      {/* Documents List */}
      <div className="space-y-4">
        {filteredDocuments.map(document => (
          <DocumentCard
            key={document.id}
            document={document}
            onDelete={handleDeleteDocument}
            onEdit={handleEdit}
            onPreview={handlePreview}
          />
        ))}
      </div>

      {filteredDocuments.length === 0 && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Dokumente gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder erstellen Sie ein neues Dokument.</p>
        </div>
      )}

      {/* Preview Modal */}
      {previewDoc && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[80vh] flex flex-col">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <h2 className="text-lg font-bold text-gray-900">{previewDoc.name}</h2>
              <button
                onClick={() => setPreviewDoc(null)}
                className="text-gray-400 hover:text-gray-600"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div
              className="p-6 overflow-y-auto prose max-w-none"
              dangerouslySetInnerHTML={{ __html: previewDoc.content }}
            />
          </div>
        </div>
      )}

      {/* Create Document Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
            <div className="px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-bold text-gray-900">Neues Dokument erstellen</h2>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Dokumenttyp</label>
                <select
                  value={newDocForm.type}
                  onChange={(e) => setNewDocForm({ ...newDocForm, type: e.target.value })}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                >
                  <option value="privacy_policy">Datenschutzerklärung</option>
                  <option value="terms">AGB</option>
                  <option value="cookie_policy">Cookie-Richtlinie</option>
                  <option value="imprint">Impressum</option>
                  <option value="dpa">AVV (Auftragsverarbeitung)</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
                <input
                  type="text"
                  value={newDocForm.name}
                  onChange={(e) => setNewDocForm({ ...newDocForm, name: e.target.value })}
                  placeholder="z.B. Datenschutzerklärung Website"
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung (optional)</label>
                <textarea
                  rows={2}
                  value={newDocForm.description}
                  onChange={(e) => setNewDocForm({ ...newDocForm, description: e.target.value })}
                  placeholder="Kurze Beschreibung..."
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                />
              </div>
              <div>
                <div className="flex justify-between items-center mb-1">
                  <label className="text-sm font-medium text-gray-700">Inhalt (optional)</label>
                  <button
                    type="button"
                    onClick={onRagSuggest}
                    className="text-xs text-blue-600 hover:underline"
                  >
                    Aus RAG-Vorlagen laden →
                  </button>
                </div>
                <textarea
                  rows={4}
                  value={newDocForm.content}
                  onChange={(e) => setNewDocForm({ ...newDocForm, content: e.target.value })}
                  placeholder="Dokumentinhalt oder über RAG-Vorlagen laden..."
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                />
              </div>
            </div>
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                Abbrechen
              </button>
              <button
                onClick={onCreateDocument}
                disabled={creating || !newDocForm.name.trim()}
                className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50"
              >
                {creating ? 'Erstellen...' : 'Erstellen'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
