'use client'

import React, { useState, useEffect, useRef } from 'react'
import { useParams } from 'next/navigation'

interface EvidenceFile {
  id: string
  filename: string
  file_type: string
  file_size: number
  description: string
  uploaded_at: string
  uploaded_by: string
  linked_mitigation_ids: string[]
  linked_mitigation_names: string[]
  linked_verification_ids: string[]
  linked_verification_names: string[]
}

interface Linkable {
  id: string
  name: string
}

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

function FileIcon({ type }: { type: string }) {
  const isPdf = type.includes('pdf')
  const isImage = type.includes('image')
  const isDoc = type.includes('word') || type.includes('document')
  const isSpreadsheet = type.includes('sheet') || type.includes('excel')

  const color = isPdf ? 'text-red-500' : isImage ? 'text-blue-500' : isDoc ? 'text-blue-600' : isSpreadsheet ? 'text-green-600' : 'text-gray-500'

  return (
    <svg className={`w-8 h-8 ${color}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} 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>
  )
}

function LinkBadges({ names, type }: { names: string[]; type: 'mitigation' | 'verification' }) {
  if (names.length === 0) return null
  const color = type === 'mitigation' ? 'bg-blue-50 text-blue-700' : 'bg-green-50 text-green-700'
  return (
    <div className="flex flex-wrap gap-1">
      {names.map((name, i) => (
        <span key={i} className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs ${color}`}>
          {name}
        </span>
      ))}
    </div>
  )
}

function LinkModal({
  evidence,
  mitigations,
  verifications,
  onSave,
  onClose,
}: {
  evidence: EvidenceFile
  mitigations: Linkable[]
  verifications: Linkable[]
  onSave: (evidenceId: string, mitIds: string[], verIds: string[]) => void
  onClose: () => void
}) {
  const [selectedMitigations, setSelectedMitigations] = useState<string[]>(evidence.linked_mitigation_ids)
  const [selectedVerifications, setSelectedVerifications] = useState<string[]>(evidence.linked_verification_ids)

  function toggle(list: string[], setList: (v: string[]) => void, id: string) {
    setList(list.includes(id) ? list.filter((x) => x !== id) : [...list, id])
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-lg max-h-[80vh] flex flex-col">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              Nachweis verknuepfen: {evidence.filename}
            </h3>
            <button onClick={onClose} className="p-1 text-gray-400 hover:text-gray-600 rounded">
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
        <div className="flex-1 overflow-auto p-6 space-y-6">
          {mitigations.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Massnahmen</h4>
              <div className="space-y-1">
                {mitigations.map((m) => (
                  <label key={m.id} className="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-50 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedMitigations.includes(m.id)}
                      onChange={() => toggle(selectedMitigations, setSelectedMitigations, m.id)}
                      className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">{m.name}</span>
                  </label>
                ))}
              </div>
            </div>
          )}
          {verifications.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Verifikationen</h4>
              <div className="space-y-1">
                {verifications.map((v) => (
                  <label key={v.id} className="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-50 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedVerifications.includes(v.id)}
                      onChange={() => toggle(selectedVerifications, setSelectedVerifications, v.id)}
                      className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">{v.name}</span>
                  </label>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="p-6 border-t border-gray-200 dark:border-gray-700 flex items-center gap-3">
          <button
            onClick={() => onSave(evidence.id, selectedMitigations, selectedVerifications)}
            className="px-6 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors font-medium"
          >
            Speichern
          </button>
          <button onClick={onClose} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Abbrechen
          </button>
        </div>
      </div>
    </div>
  )
}

export default function EvidencePage() {
  const params = useParams()
  const projectId = params.projectId as string
  const [files, setFiles] = useState<EvidenceFile[]>([])
  const [mitigations, setMitigations] = useState<Linkable[]>([])
  const [verifications, setVerifications] = useState<Linkable[]>([])
  const [loading, setLoading] = useState(true)
  const [uploading, setUploading] = useState(false)
  const [dragging, setDragging] = useState(false)
  const [linkingFile, setLinkingFile] = useState<EvidenceFile | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    fetchData()
  }, [projectId])

  async function fetchData() {
    try {
      const [evRes, mitRes, verRes] = await Promise.all([
        fetch(`/api/sdk/v1/iace/projects/${projectId}/evidence`),
        fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations`),
        fetch(`/api/sdk/v1/iace/projects/${projectId}/verifications`),
      ])
      if (evRes.ok) {
        const json = await evRes.json()
        setFiles(json.evidence || json || [])
      }
      if (mitRes.ok) {
        const json = await mitRes.json()
        setMitigations((json.mitigations || json || []).map((m: { id: string; title: string }) => ({ id: m.id, name: m.title })))
      }
      if (verRes.ok) {
        const json = await verRes.json()
        setVerifications((json.verifications || json || []).map((v: { id: string; title: string }) => ({ id: v.id, name: v.title })))
      }
    } catch (err) {
      console.error('Failed to fetch data:', err)
    } finally {
      setLoading(false)
    }
  }

  async function handleUpload(fileList: FileList) {
    setUploading(true)
    try {
      for (let i = 0; i < fileList.length; i++) {
        const file = fileList[i]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('description', '')

        await fetch(`/api/sdk/v1/iace/projects/${projectId}/evidence`, {
          method: 'POST',
          body: formData,
        })
      }
      await fetchData()
    } catch (err) {
      console.error('Failed to upload:', err)
    } finally {
      setUploading(false)
    }
  }

  function handleDrop(e: React.DragEvent) {
    e.preventDefault()
    setDragging(false)
    if (e.dataTransfer.files.length > 0) {
      handleUpload(e.dataTransfer.files)
    }
  }

  function handleDragOver(e: React.DragEvent) {
    e.preventDefault()
    setDragging(true)
  }

  function handleDragLeave() {
    setDragging(false)
  }

  async function handleLink(evidenceId: string, mitIds: string[], verIds: string[]) {
    try {
      await fetch(`/api/sdk/v1/iace/projects/${projectId}/evidence/${evidenceId}/link`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          linked_mitigation_ids: mitIds,
          linked_verification_ids: verIds,
        }),
      })
      setLinkingFile(null)
      await fetchData()
    } catch (err) {
      console.error('Failed to link evidence:', err)
    }
  }

  async function handleDelete(id: string) {
    if (!confirm('Nachweis wirklich loeschen?')) return
    try {
      await fetch(`/api/sdk/v1/iace/projects/${projectId}/evidence/${id}`, { method: 'DELETE' })
      await fetchData()
    } catch (err) {
      console.error('Failed to delete evidence:', err)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Nachweise</h1>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
          Laden Sie Nachweisdokumente hoch und verknuepfen Sie diese mit Massnahmen und Verifikationen.
        </p>
      </div>

      {/* Upload Area */}
      <div
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onClick={() => fileInputRef.current?.click()}
        className={`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-colors ${
          dragging
            ? 'border-purple-400 bg-purple-50 dark:bg-purple-900/20'
            : 'border-gray-300 hover:border-purple-300 hover:bg-gray-50 dark:hover:bg-gray-800'
        }`}
      >
        <input
          ref={fileInputRef}
          type="file"
          multiple
          className="hidden"
          onChange={(e) => e.target.files && handleUpload(e.target.files)}
        />
        {uploading ? (
          <div className="flex items-center justify-center gap-3">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600" />
            <span className="text-sm text-gray-600">Wird hochgeladen...</span>
          </div>
        ) : (
          <>
            <svg className="w-10 h-10 mx-auto text-gray-400 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
            </svg>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              <span className="font-medium text-purple-600">Dateien auswaehlen</span> oder hierher ziehen
            </p>
            <p className="text-xs text-gray-400 mt-1">PDF, Word, Excel, Bilder und andere Dokumente</p>
          </>
        )}
      </div>

      {/* Link Modal */}
      {linkingFile && (
        <LinkModal
          evidence={linkingFile}
          mitigations={mitigations}
          verifications={verifications}
          onSave={handleLink}
          onClose={() => setLinkingFile(null)}
        />
      )}

      {/* File List */}
      {files.length > 0 ? (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
            <h2 className="text-sm font-semibold text-gray-900 dark:text-white">
              Hochgeladene Nachweise ({files.length})
            </h2>
          </div>
          <div className="divide-y divide-gray-200 dark:divide-gray-700">
            {files.map((file) => (
              <div key={file.id} className="px-6 py-4 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors">
                <div className="flex items-start gap-4">
                  <FileIcon type={file.file_type} />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-gray-900 dark:text-white truncate">
                        {file.filename}
                      </span>
                      <span className="text-xs text-gray-400">{formatFileSize(file.file_size)}</span>
                    </div>
                    {file.description && (
                      <p className="text-xs text-gray-500 mt-0.5">{file.description}</p>
                    )}
                    <div className="mt-2 space-y-1">
                      <LinkBadges names={file.linked_mitigation_names} type="mitigation" />
                      <LinkBadges names={file.linked_verification_names} type="verification" />
                    </div>
                    <div className="text-xs text-gray-400 mt-1">
                      Hochgeladen am {new Date(file.uploaded_at).toLocaleDateString('de-DE')}
                    </div>
                  </div>
                  <div className="flex items-center gap-1 flex-shrink-0">
                    <button
                      onClick={() => setLinkingFile(file)}
                      className="text-xs px-2.5 py-1 border border-gray-200 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      Verknuepfen
                    </button>
                    <button
                      onClick={() => handleDelete(file.id)}
                      className="p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                    >
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-purple-100 dark:bg-purple-900/30 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <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 dark:text-white">Keine Nachweise vorhanden</h3>
          <p className="mt-2 text-gray-500 max-w-md mx-auto">
            Laden Sie Testberichte, Zertifikate, Analyseergebnisse und andere Nachweisdokumente
            hoch und verknuepfen Sie diese mit den entsprechenden Massnahmen.
          </p>
        </div>
      )}
    </div>
  )
}
