'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { useSDK } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { DSFACard } from '@/components/sdk/dsfa'
import {
  DSFA,
  DSFAStatus,
  DSFA_STATUS_LABELS,
  DSFA_RISK_LEVEL_LABELS,
} from '@/lib/sdk/dsfa/types'
import {
  listDSFAs,
  deleteDSFA,
  exportDSFAAsJSON,
  getDSFAStats,
  createDSFAFromAssessment,
  getDSFAByAssessment,
} from '@/lib/sdk/dsfa/api'

// =============================================================================
// UCCA TRIGGER WARNING COMPONENT
// =============================================================================

interface UCCATriggerWarningProps {
  assessmentId: string
  triggeredRules: string[]
  existingDsfaId?: string
  onCreateDSFA: () => void
}

function UCCATriggerWarning({
  assessmentId,
  triggeredRules,
  existingDsfaId,
  onCreateDSFA,
}: UCCATriggerWarningProps) {
  if (existingDsfaId) {
    return (
      <div className="bg-blue-50 border border-blue-200 rounded-xl p-4 flex items-start gap-4">
        <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
          <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </div>
        <div className="flex-1">
          <h4 className="font-medium text-blue-800">DSFA bereits erstellt</h4>
          <p className="text-sm text-blue-600 mt-1">
            Fuer dieses Assessment wurde bereits eine DSFA angelegt.
          </p>
          <Link
            href={`/sdk/dsfa/${existingDsfaId}`}
            className="inline-flex items-center gap-1 mt-2 text-sm text-blue-700 hover:text-blue-800 font-medium"
          >
            DSFA oeffnen
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="bg-orange-50 border border-orange-200 rounded-xl p-4 flex items-start gap-4">
      <div className="w-10 h-10 bg-orange-100 rounded-full flex items-center justify-center flex-shrink-0">
        <svg className="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
        </svg>
      </div>
      <div className="flex-1">
        <h4 className="font-medium text-orange-800">DSFA erforderlich</h4>
        <p className="text-sm text-orange-600 mt-1">
          Das UCCA-Assessment hat folgende Trigger ausgeloest:
        </p>
        <div className="flex flex-wrap gap-1 mt-2">
          {triggeredRules.map(rule => (
            <span key={rule} className="px-2 py-0.5 text-xs bg-orange-100 text-orange-700 rounded">
              {rule}
            </span>
          ))}
        </div>
        <button
          onClick={onCreateDSFA}
          className="inline-flex items-center gap-1 mt-3 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors text-sm font-medium"
        >
          DSFA aus Assessment erstellen
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        </button>
      </div>
    </div>
  )
}

// =============================================================================
// GENERATOR WIZARD COMPONENT
// =============================================================================

function GeneratorWizard({ onClose, onCreated }: { onClose: () => void; onCreated: (dsfa: DSFA) => void }) {
  const [step, setStep] = useState(1)
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    processingPurpose: '',
    dataCategories: [] as string[],
    legalBasis: '',
  })
  const [isSubmitting, setIsSubmitting] = useState(false)

  const DATA_CATEGORIES = [
    'Kontaktdaten',
    'Identifikationsdaten',
    'Finanzdaten',
    'Gesundheitsdaten',
    'Standortdaten',
    'Nutzungsdaten',
    'Biometrische Daten',
    'Daten Minderjaehriger',
  ]

  const LEGAL_BASES = [
    { value: 'consent', label: 'Einwilligung (Art. 6 Abs. 1 lit. a)' },
    { value: 'contract', label: 'Vertrag (Art. 6 Abs. 1 lit. b)' },
    { value: 'legal_obligation', label: 'Rechtliche Verpflichtung (Art. 6 Abs. 1 lit. c)' },
    { value: 'legitimate_interest', label: 'Berechtigtes Interesse (Art. 6 Abs. 1 lit. f)' },
  ]

  const handleCategoryToggle = (cat: string) => {
    setFormData(prev => ({
      ...prev,
      dataCategories: prev.dataCategories.includes(cat)
        ? prev.dataCategories.filter(c => c !== cat)
        : [...prev.dataCategories, cat],
    }))
  }

  const handleSubmit = async () => {
    setIsSubmitting(true)
    try {
      // For standalone DSFA, we use the regular create endpoint
      const response = await fetch('/api/sdk/v1/dsgvo/dsfas', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formData.name,
          description: formData.description,
          processing_purpose: formData.processingPurpose,
          data_categories: formData.dataCategories,
          legal_basis: formData.legalBasis,
          status: 'draft',
        }),
      })
      if (response.ok) {
        const dsfa = await response.json()
        onCreated(dsfa)
        onClose()
      }
    } catch (error) {
      console.error('Failed to create DSFA:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="bg-white rounded-xl border border-gray-200 p-6">
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-semibold text-gray-900">Neue Standalone-DSFA erstellen</h3>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
          <svg className="w-6 h-6" 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>

      {/* Progress Steps */}
      <div className="flex items-center gap-2 mb-6">
        {[1, 2, 3].map(s => (
          <React.Fragment key={s}>
            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
              s < step ? 'bg-green-500 text-white' :
              s === step ? 'bg-purple-600 text-white' : 'bg-gray-200 text-gray-500'
            }`}>
              {s < step ? (
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              ) : s}
            </div>
            {s < 3 && <div className={`flex-1 h-1 ${s < step ? 'bg-green-500' : 'bg-gray-200'}`} />}
          </React.Fragment>
        ))}
      </div>

      {/* Step Content */}
      <div className="min-h-48">
        {step === 1 && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Titel der DSFA *</label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                placeholder="z.B. DSFA - Mitarbeiter-Monitoring"
                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 der Verarbeitung</label>
              <textarea
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                rows={3}
                placeholder="Beschreiben Sie die geplante Datenverarbeitung..."
                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">Verarbeitungszweck</label>
              <input
                type="text"
                value={formData.processingPurpose}
                onChange={(e) => setFormData(prev => ({ ...prev, processingPurpose: e.target.value }))}
                placeholder="z.B. Automatisierte Bewerberauswahl"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
              />
            </div>
          </div>
        )}
        {step === 2 && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Datenkategorien *</label>
              <div className="grid grid-cols-2 gap-2">
                {DATA_CATEGORIES.map(cat => (
                  <label key={cat} className="flex items-center gap-2 p-2 border rounded-lg hover:bg-gray-50">
                    <input
                      type="checkbox"
                      checked={formData.dataCategories.includes(cat)}
                      onChange={() => handleCategoryToggle(cat)}
                      className="w-4 h-4 text-purple-600"
                    />
                    <span className="text-sm">{cat}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
        )}
        {step === 3 && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Rechtsgrundlage *</label>
              <div className="space-y-2">
                {LEGAL_BASES.map(basis => (
                  <label key={basis.value} className="flex items-center gap-3 p-3 border rounded-lg hover:bg-gray-50 cursor-pointer">
                    <input
                      type="radio"
                      name="legalBasis"
                      value={basis.value}
                      checked={formData.legalBasis === basis.value}
                      onChange={(e) => setFormData(prev => ({ ...prev, legalBasis: e.target.value }))}
                      className="w-4 h-4 text-purple-600"
                    />
                    <span className="text-sm font-medium">{basis.label}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Navigation */}
      <div className="flex items-center justify-between mt-6 pt-4 border-t border-gray-200">
        <button
          onClick={() => step > 1 ? setStep(step - 1) : onClose()}
          className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
        >
          {step === 1 ? 'Abbrechen' : 'Zurueck'}
        </button>
        <button
          onClick={() => step < 3 ? setStep(step + 1) : handleSubmit()}
          disabled={(step === 1 && !formData.name) || (step === 2 && formData.dataCategories.length === 0) || (step === 3 && !formData.legalBasis) || isSubmitting}
          className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed"
        >
          {isSubmitting ? 'Wird erstellt...' : step === 3 ? 'DSFA erstellen' : 'Weiter'}
        </button>
      </div>
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

export default function DSFAPage() {
  const router = useRouter()
  const { state } = useSDK()
  const [dsfas, setDsfas] = useState<DSFA[]>([])
  const [showGenerator, setShowGenerator] = useState(false)
  const [filter, setFilter] = useState<string>('all')
  const [isLoading, setIsLoading] = useState(true)
  const [stats, setStats] = useState({
    total: 0,
    draft: 0,
    in_review: 0,
    approved: 0,
  })

  // UCCA trigger info (would come from SDK state)
  const [uccaTrigger, setUccaTrigger] = useState<{
    assessmentId: string
    triggeredRules: string[]
    existingDsfaId?: string
  } | null>(null)

  // Load DSFAs
  const loadDSFAs = useCallback(async () => {
    setIsLoading(true)
    try {
      const [dsfaList, statsData] = await Promise.all([
        listDSFAs(filter === 'all' ? undefined : filter),
        getDSFAStats(),
      ])
      setDsfas(dsfaList)
      setStats({
        total: statsData.total,
        draft: statsData.status_stats.draft || 0,
        in_review: statsData.status_stats.in_review || 0,
        approved: statsData.status_stats.approved || 0,
      })
    } catch (error) {
      console.error('Failed to load DSFAs:', error)
      // Set empty state on error
      setDsfas([])
    } finally {
      setIsLoading(false)
    }
  }, [filter])

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

  // Check for UCCA trigger from SDK state
  // TODO: Enable when UCCA integration is complete
  // useEffect(() => {
  //   if (state?.uccaAssessment?.dsfa_recommended) {
  //     const assessmentId = state.uccaAssessment.id
  //     const triggeredRules = state.uccaAssessment.triggered_rules
  //       ?.filter((r: { severity: string }) => r.severity === 'BLOCK' || r.severity === 'WARN')
  //       ?.map((r: { code: string }) => r.code) || []
  //
  //     // Check if DSFA already exists
  //     getDSFAByAssessment(assessmentId).then(existingDsfa => {
  //       setUccaTrigger({
  //         assessmentId,
  //         triggeredRules,
  //         existingDsfaId: existingDsfa?.id,
  //       })
  //     })
  //   }
  // }, [state?.uccaAssessment])

  // Handle delete
  const handleDelete = async (id: string) => {
    if (confirm('Moechten Sie diese DSFA wirklich loeschen?')) {
      try {
        await deleteDSFA(id)
        await loadDSFAs()
      } catch (error) {
        console.error('Failed to delete DSFA:', error)
      }
    }
  }

  // Handle export
  const handleExport = async (id: string) => {
    try {
      const blob = await exportDSFAAsJSON(id)
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `dsfa_${id.slice(0, 8)}.json`
      a.click()
      URL.revokeObjectURL(url)
    } catch (error) {
      console.error('Failed to export DSFA:', error)
    }
  }

  // Handle create from assessment
  const handleCreateFromAssessment = async () => {
    if (!uccaTrigger?.assessmentId) return

    try {
      const response = await createDSFAFromAssessment(uccaTrigger.assessmentId)
      router.push(`/sdk/dsfa/${response.dsfa.id}`)
    } catch (error) {
      console.error('Failed to create DSFA from assessment:', error)
    }
  }

  const filteredDSFAs = filter === 'all'
    ? dsfas
    : dsfas.filter(d => d.status === filter)

  const stepInfo = STEP_EXPLANATIONS['dsfa']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="dsfa"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <div className="flex items-center gap-2">
          {!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>
                Standalone DSFA
              </button>
            </>
          )}
        </div>
      </StepHeader>

      {/* UCCA Trigger Warning */}
      {uccaTrigger && (
        <UCCATriggerWarning
          assessmentId={uccaTrigger.assessmentId}
          triggeredRules={uccaTrigger.triggeredRules}
          existingDsfaId={uccaTrigger.existingDsfaId}
          onCreateDSFA={handleCreateFromAssessment}
        />
      )}

      {/* Generator */}
      {showGenerator && (
        <GeneratorWizard
          onClose={() => setShowGenerator(false)}
          onCreated={(dsfa) => {
            router.push(`/sdk/dsfa/${dsfa.id}`)
          }}
        />
      )}

      {/* 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">{stats.total}</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">{stats.draft}</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">{stats.in_review}</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">{stats.approved}</div>
        </div>
      </div>

      {/* Filter */}
      <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' : DSFA_STATUS_LABELS[f as DSFAStatus] || f}
          </button>
        ))}
      </div>

      {/* DSFA List */}
      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <div className="w-8 h-8 border-4 border-purple-600 border-t-transparent rounded-full animate-spin" />
        </div>
      ) : (
        <div className="space-y-4">
          {filteredDSFAs.map(dsfa => (
            <DSFACard
              key={dsfa.id}
              dsfa={dsfa}
              onDelete={handleDelete}
              onExport={handleExport}
            />
          ))}
        </div>
      )}

      {/* Empty State */}
      {!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">
            {filter !== 'all'
              ? `Keine DSFAs mit Status "${DSFA_STATUS_LABELS[filter as DSFAStatus]}".`
              : 'Erstellen Sie eine neue Datenschutz-Folgenabschaetzung.'}
          </p>
          {filter === 'all' && (
            <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>
  )
}
