'use client'

import { useState, useCallback, useEffect, useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { useSDK } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { DocumentUploadSection, type UploadedDocument } from '@/components/sdk'
import { DSFACard, type DSFA } from './_components/DSFACard'
import { GeneratorWizard } from './_components/GeneratorWizard'
import { prefillDSFAFromScope, isDSFARequired } from '@/lib/sdk/dsfa/prefill-from-scope'

export default function DSFAPage() {
  const router = useRouter()
  const { state } = useSDK()
  const [dsfas, setDsfas] = useState<DSFA[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showGenerator, setShowGenerator] = useState(false)
  const [filter, setFilter] = useState<string>('all')

  // Pre-fill from Company Profile + Scope answers
  const scopeAnswers = state.complianceScope?.answers || []
  const prefill = useMemo(
    () => prefillDSFAFromScope(state.companyProfile || null, scopeAnswers),
    [state.companyProfile, scopeAnswers]
  )
  const dsfaCheck = useMemo(
    () => isDSFARequired(scopeAnswers, state.companyProfile?.headquartersState),
    [scopeAnswers, state.companyProfile?.headquartersState]
  )

  const loadDSFAs = useCallback(async () => {
    setIsLoading(true)
    setError(null)
    try {
      const res = await fetch('/api/sdk/v1/dsfa?tenant_id=default')
      if (!res.ok) throw new Error(`Fehler: ${res.status}`)
      const data = await res.json()
      const mapped: DSFA[] = (Array.isArray(data) ? data : []).map((d: Record<string, unknown>) => ({
        id: d.id as string,
        title: d.title as string,
        description: (d.description as string) || '',
        status: (d.status as DSFA['status']) || 'draft',
        createdAt: d.created_at as string,
        updatedAt: d.updated_at as string,
        approvedBy: (d.approved_by as string) || null,
        riskLevel: (d.risk_level as DSFA['riskLevel']) || 'low',
        processingActivity: (d.processing_activity as string) || '',
        dataCategories: (d.data_categories as string[]) || [],
        recipients: (d.recipients as string[]) || [],
        measures: (d.measures as string[]) || [],
      }))
      setDsfas(mapped)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setIsLoading(false)
    }
  }, [])

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

  const handleCreateDSFA = useCallback(async (data: Partial<DSFA>) => {
    const res = await fetch('/api/sdk/v1/dsfa?tenant_id=default', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        title: data.title,
        description: data.description || '',
        processing_activity: data.processingActivity || '',
        data_categories: data.dataCategories || [],
        recipients: data.recipients || [],
        measures: data.measures || [],
        risk_level: data.riskLevel || 'low',
        status: data.status || 'draft',
      }),
    })
    if (!res.ok) throw new Error(`Fehler beim Erstellen: ${res.status}`)
    await loadDSFAs()
  }, [loadDSFAs])

  const handleStatusChange = useCallback(async (id: string, status: string) => {
    const res = await fetch(`/api/sdk/v1/dsfa/${id}/status?tenant_id=default`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status }),
    })
    if (!res.ok) throw new Error(`Statuswechsel fehlgeschlagen: ${res.status}`)
    await loadDSFAs()
  }, [loadDSFAs])

  const handleDeleteDSFA = useCallback(async (id: string) => {
    if (!confirm('DSFA wirklich loeschen?')) return
    const res = await fetch(`/api/sdk/v1/dsfa/${id}?tenant_id=default`, { method: 'DELETE' })
    if (!res.ok) throw new Error(`Loeschen fehlgeschlagen: ${res.status}`)
    await loadDSFAs()
  }, [loadDSFAs])

  const handleDocumentProcessed = useCallback((doc: UploadedDocument) => {
    console.log('[DSFA Page] Document processed:', doc)
  }, [])

  const handleOpenInEditor = useCallback((doc: UploadedDocument) => {
    router.push(`/sdk/workflow?documentType=dsfa&documentId=${doc.id}&mode=change`)
  }, [router])

  const filteredDSFAs = filter === 'all' ? dsfas : dsfas.filter(d => d.status === filter)
  const draftCount = dsfas.filter(d => d.status === 'draft').length
  const inReviewCount = dsfas.filter(d => d.status === 'in-review').length
  const approvedCount = dsfas.filter(d => d.status === 'approved').length
  const stepInfo = STEP_EXPLANATIONS['dsfa']

  return (
    <div className="space-y-6">
      <StepHeader
        stepId="dsfa"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        {!showGenerator && (
          <button
            onClick={() => setShowGenerator(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>
            Neue DSFA
          </button>
        )}
      </StepHeader>

      <div className="px-4 py-2 bg-emerald-50 border border-emerald-200 rounded-lg text-xs text-emerald-800 flex items-start gap-2">
        <span className="font-semibold">Quellen &amp; Lizenz:</span>
        <span>
          Inhalte gemaess <strong>DSGVO Art. 35</strong> (EU 2016/679) — Lizenzregel R1
          (Hoheitsrecht/EU_LAW, woertlich uebernehmbar). Vorlagen-Texte aus
          Aufsichtsbehoerden ebenfalls R1.{' '}
          <a href="/sdk/licenses" className="underline">Quellenverzeichnis</a>
        </span>
      </div>

      {/* DSFA Requirement Check */}
      {dsfaCheck.required && dsfas.length === 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-5">
          <h3 className="font-semibold text-red-800">DSFA erforderlich (Art. 35 DSGVO)</h3>
          <p className="text-sm text-red-700 mt-1">Basierend auf Ihrem Scope-Profiling wurde festgestellt:</p>
          <ul className="mt-2 space-y-1">
            {dsfaCheck.triggers.map(t => (
              <li key={t} className="text-sm text-red-600 flex items-center gap-2">
                <span className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0" />
                {t}
              </li>
            ))}
          </ul>
          {dsfaCheck.blacklistMatches.length > 0 && (
            <div className="mt-3 pt-3 border-t border-red-200">
              <p className="text-xs font-medium text-red-800 mb-1">
                Blacklist {dsfaCheck.authority || 'Aufsichtsbehoerde'} (Art. 35 Abs. 4):
              </p>
              <ul className="space-y-1">
                {dsfaCheck.blacklistMatches.map(m => (
                  <li key={m} className="text-xs text-red-600 flex items-center gap-2">
                    <span className="w-1 h-1 bg-red-400 rounded-full flex-shrink-0" />
                    {m}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}

      {showGenerator && (
        <GeneratorWizard
          onClose={() => setShowGenerator(false)}
          onSubmit={handleCreateDSFA}
          prefill={prefill}
        />
      )}

      <DocumentUploadSection
        documentType="dsfa"
        onDocumentProcessed={handleDocumentProcessed}
        onOpenInEditor={handleOpenInEditor}
      />

      <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">{dsfas.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="text-sm text-gray-500">Entwuerfe</div>
          <div className="text-3xl font-bold text-gray-500">{draftCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">In Pruefung</div>
          <div className="text-3xl font-bold text-yellow-600">{inReviewCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Genehmigt</div>
          <div className="text-3xl font-bold text-green-600">{approvedCount}</div>
        </div>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-red-700 text-sm">
          Fehler beim Laden: {error}
          <button onClick={loadDSFAs} className="ml-4 underline">Erneut versuchen</button>
        </div>
      )}

      <div className="flex items-center gap-2">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'draft', 'in-review', 'approved', 'needs-update'].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 === 'draft' ? 'Entwuerfe' :
             f === 'in-review' ? 'In Pruefung' :
             f === 'approved' ? 'Genehmigt' : 'Update erforderlich'}
          </button>
        ))}
      </div>

      {isLoading && (
        <div className="text-center py-12 text-gray-500">Lade DSFAs...</div>
      )}

      {!isLoading && (
        <div className="space-y-4">
          {filteredDSFAs.map(dsfa => (
            <DSFACard
              key={dsfa.id}
              dsfa={dsfa}
              onStatusChange={handleStatusChange}
              onDelete={handleDeleteDSFA}
            />
          ))}
        </div>
      )}

      {!isLoading && filteredDSFAs.length === 0 && !showGenerator && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-purple-600" 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 DSFAs gefunden</h3>
          <p className="mt-2 text-gray-500">Erstellen Sie eine neue Datenschutz-Folgenabschaetzung.</p>
          <button
            onClick={() => setShowGenerator(true)}
            className="mt-4 px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            Erste DSFA erstellen
          </button>
        </div>
      )}
    </div>
  )
}
