'use client'

import { useState, useEffect } from 'react'

interface Version {
  id: string
  versionNumber: number
  status: string
  changeSummary: string | null
  changedSections: string[]
  createdBy: string
  approvedBy: string | null
  approvedAt: string | null
  createdAt: string | null
}

interface VersionHistoryProps {
  documentType: 'dsfa' | 'vvt' | 'tom' | 'loeschfristen' | 'obligation'
  documentId: string
  apiPath: string
}

export default function VersionHistory({ documentType, documentId, apiPath }: VersionHistoryProps) {
  const [versions, setVersions] = useState<Version[]>([])
  const [loading, setLoading] = useState(true)
  const [expanded, setExpanded] = useState(false)

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch(`/api/sdk/v1/compliance/${apiPath}`)
        if (res.ok) {
          const data = await res.json()
          setVersions(
            (Array.isArray(data) ? data : []).map((v: Record<string, unknown>) => ({
              id: v.id as string,
              versionNumber: v.version_number as number,
              status: v.status as string,
              changeSummary: v.change_summary as string | null,
              changedSections: (v.changed_sections || []) as string[],
              createdBy: v.created_by as string,
              approvedBy: v.approved_by as string | null,
              approvedAt: v.approved_at as string | null,
              createdAt: v.created_at as string | null,
            }))
          )
        }
      } catch (e) {
        console.error('Failed to load versions:', e)
      } finally {
        setLoading(false)
      }
    }
    if (documentId) load()
  }, [documentId, apiPath])

  if (loading) return null
  if (versions.length === 0) return null

  return (
    <div className="mt-4">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 text-sm text-purple-600 hover:text-purple-800 font-medium"
      >
        <svg className={`w-4 h-4 transition-transform ${expanded ? 'rotate-90' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
        </svg>
        Versionen ({versions.length})
      </button>

      {expanded && (
        <div className="mt-3 border-l-2 border-purple-200 pl-4 space-y-3">
          {versions.map(v => (
            <div key={v.id} className="relative">
              <div className="absolute -left-[1.35rem] top-1.5 w-2.5 h-2.5 rounded-full bg-purple-400 border-2 border-white" />
              <div className="text-sm">
                <div className="flex items-center gap-2">
                  <span className="font-medium text-gray-900">v{v.versionNumber}</span>
                  <span className={`px-1.5 py-0.5 rounded text-xs ${
                    v.status === 'approved' ? 'bg-green-100 text-green-700' :
                    v.status === 'draft' ? 'bg-yellow-100 text-yellow-700' :
                    'bg-gray-100 text-gray-600'
                  }`}>
                    {v.status}
                  </span>
                  {v.createdAt && (
                    <span className="text-gray-400 text-xs">
                      {new Date(v.createdAt).toLocaleDateString('de-DE')}
                    </span>
                  )}
                </div>
                {v.changeSummary && (
                  <p className="text-gray-600 text-xs mt-0.5">{v.changeSummary}</p>
                )}
                {v.changedSections.length > 0 && (
                  <div className="flex gap-1 mt-1">
                    {v.changedSections.map((s, i) => (
                      <span key={i} className="px-1.5 py-0.5 bg-purple-50 text-purple-600 rounded text-xs">{s}</span>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
