'use client'

import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { useAuditChecklist } from './_hooks/useAuditChecklist'
import { ChecklistItemCard } from './_components/ChecklistItemCard'
import { LoadingSkeleton } from './_components/LoadingSkeleton'
import { SessionHistory } from './_components/SessionHistory'

export default function AuditChecklistPage() {
  const router = useRouter()
  const [filter, setFilter] = useState<string>('all')
  const {
    state,
    loading,
    error,
    setError,
    activeSessionId,
    pastSessions,
    pdfLanguage,
    setPdfLanguage,
    generatingPdf,
    displayItems,
    handleStatusChange,
    handleNotesChange,
    handleExport,
    handlePdfDownload,
    handleNewChecklist,
  } = useAuditChecklist()

  const filteredItems = filter === 'all'
    ? displayItems
    : displayItems.filter(item => item.status === filter || item.category === filter)

  const compliantCount = displayItems.filter(i => i.status === 'compliant').length
  const nonCompliantCount = displayItems.filter(i => i.status === 'non-compliant').length
  const partialCount = displayItems.filter(i => i.status === 'partial').length
  const notReviewedCount = displayItems.filter(i => i.status === 'not-reviewed').length

  const progress = displayItems.length > 0
    ? Math.round(((compliantCount + partialCount * 0.5) / displayItems.length) * 100)
    : 0

  const stepInfo = STEP_EXPLANATIONS['audit-checklist']

  return (
    <div className="space-y-6">
      <StepHeader
        stepId="audit-checklist"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <div className="flex items-center gap-2">
          <button
            onClick={handleExport}
            className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
          >
            Export JSON
          </button>
          <div className="flex items-center gap-1">
            <select
              value={pdfLanguage}
              onChange={(e) => setPdfLanguage(e.target.value as 'de' | 'en')}
              className="px-2 py-2 border border-gray-300 rounded-l-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            >
              <option value="de">DE</option>
              <option value="en">EN</option>
            </select>
            <button
              onClick={handlePdfDownload}
              disabled={generatingPdf || !activeSessionId}
              className="px-4 py-2 text-purple-600 border border-l-0 border-gray-300 hover:bg-purple-50 rounded-r-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
            >
              {generatingPdf ? 'Generiere...' : 'PDF'}
            </button>
          </div>
          <button
            onClick={handleNewChecklist}
            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 Checkliste
          </button>
        </div>
      </StepHeader>

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 flex items-center justify-between">
          <span>{error}</span>
          <button onClick={() => setError(null)} className="text-red-500 hover:text-red-700">&times;</button>
        </div>
      )}

      {state.requirements.length === 0 && !loading && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <svg className="w-5 h-5 text-amber-600 mt-0.5" 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>
              <h4 className="font-medium text-amber-800">Keine Anforderungen definiert</h4>
              <p className="text-sm text-amber-700 mt-1">
                Bitte definieren Sie zuerst Anforderungen, um die zugehoerige Checkliste zu generieren.
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">Compliance Audit {new Date().getFullYear()}</h2>
            <p className="text-sm text-gray-500 mt-1">Jaehrliche Ueberpruefung der Compliance-Konformitaet</p>
            <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
              <span>Frameworks: DSGVO, AI Act</span>
              <span>Letzte Aktualisierung: {new Date().toLocaleDateString('de-DE')}</span>
              {activeSessionId && (
                <span className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
                  Session aktiv
                </span>
              )}
            </div>
          </div>
          <div className="text-center">
            <div className="text-4xl font-bold text-purple-600">{progress}%</div>
            <div className="text-sm text-gray-500">Fortschritt</div>
          </div>
        </div>
        <div className="mt-4 h-3 bg-gray-100 rounded-full overflow-hidden">
          <div
            className="h-full bg-purple-600 rounded-full transition-all"
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-green-200 p-4">
          <div className="text-sm text-green-600">Konform</div>
          <div className="text-2xl font-bold text-green-600">{compliantCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-4">
          <div className="text-sm text-yellow-600">Teilweise</div>
          <div className="text-2xl font-bold text-yellow-600">{partialCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-4">
          <div className="text-sm text-red-600">Nicht konform</div>
          <div className="text-2xl font-bold text-red-600">{nonCompliantCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <div className="text-sm text-gray-500">Nicht geprueft</div>
          <div className="text-2xl font-bold text-gray-500">{notReviewedCount}</div>
        </div>
      </div>

      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'not-reviewed', 'non-compliant', 'partial', 'compliant'].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 === 'not-reviewed' ? 'Offen' :
             f === 'non-compliant' ? 'Nicht konform' :
             f === 'partial' ? 'Teilweise' : 'Konform'}
          </button>
        ))}
      </div>

      {loading && <LoadingSkeleton />}

      {!loading && (
        <div className="space-y-4">
          {filteredItems.map(item => (
            <ChecklistItemCard
              key={item.id}
              item={item}
              onStatusChange={(status) => handleStatusChange(item.id, status)}
              onNotesChange={(notes) => handleNotesChange(item.id, notes)}
              onAddEvidence={() => router.push('/sdk/evidence')}
            />
          ))}
        </div>
      )}

      {!loading && filteredItems.length === 0 && state.requirements.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 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 2m-6 9l2 2 4-4" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Eintraege gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an.</p>
        </div>
      )}

      <SessionHistory pastSessions={pastSessions} activeSessionId={activeSessionId} />
    </div>
  )
}
