'use client'

import React, { useState, useEffect, useMemo } from 'react'
import { Hazard } from './types'
import { RiskAssessmentTable } from './RiskAssessmentTable'

interface BlockData {
  parent_hazard: { hazard: { id: string } }
  children: { hazard: { id: string } }[]
  children_covered_by_parent: boolean
  block_key: string
}

interface BlockInfo {
  isParent: boolean
  isChild: boolean
  isCovered: boolean
  blockKey: string
  parentId: string
  childCount: number
}

interface Props {
  projectId: string
  hazards: Hazard[]
  onReassess?: () => void
  decisions?: Record<string, boolean | null>
  onDecision?: (hazardId: string, acceptable: boolean | null) => void
}

/**
 * Wraps RiskAssessmentTable with block-awareness:
 * - Injects block metadata into hazards so the table can show grouping
 * - Provides controls to ungroup/promote children
 */
export function BlockAwareRiskTable({ projectId, hazards, onReassess, decisions, onDecision }: Props) {
  const [blocks, setBlocks] = useState<BlockData[]>([])
  const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})
  const [ungrouped, setUngrouped] = useState<Record<string, boolean>>({})
  const [pendingAction, setPendingAction] = useState<{ childId: string; childName: string } | null>(null)

  useEffect(() => {
    fetch(`/api/sdk/v1/iace/projects/${projectId}/hazard-blocks`)
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d?.blocks) setBlocks(d.blocks) })
      .catch(() => {})
  }, [projectId])

  // Build lookup: hazardId → block info
  const blockMap = useMemo(() => {
    const map: Record<string, BlockInfo> = {}
    for (const b of blocks) {
      if (b.children.length === 0) continue
      const pid = b.parent_hazard.hazard.id
      map[pid] = {
        isParent: true, isChild: false, isCovered: false,
        blockKey: b.block_key, parentId: pid, childCount: b.children.length,
      }
      for (const c of b.children) {
        if (ungrouped[c.hazard.id]) continue
        map[c.hazard.id] = {
          isParent: false, isChild: true,
          isCovered: b.children_covered_by_parent,
          blockKey: b.block_key, parentId: pid, childCount: 0,
        }
      }
    }
    return map
  }, [blocks, ungrouped])

  // Sort hazards: parents first, then their children, then standalone
  const sortedHazards = useMemo(() => {
    const parents: Hazard[] = []
    const childrenByParent: Record<string, Hazard[]> = {}
    const standalone: Hazard[] = []

    for (const h of hazards) {
      const info = blockMap[h.id]
      if (!info) {
        standalone.push(h)
      } else if (info.isParent) {
        parents.push(h)
        childrenByParent[h.id] = []
      } else if (info.isChild) {
        const arr = childrenByParent[info.parentId]
        if (arr) arr.push(h)
        else standalone.push(h)
      }
    }

    // Sort parents by risk desc
    parents.sort((a, b) => (b.r_inherent || 0) - (a.r_inherent || 0))
    standalone.sort((a, b) => (b.r_inherent || 0) - (a.r_inherent || 0))

    // Interleave: parent → children → parent → children → ... → standalone
    const result: Hazard[] = []
    for (const p of parents) {
      result.push(p)
      const isCollapsed = collapsed[p.id]
      if (!isCollapsed && childrenByParent[p.id]) {
        result.push(...childrenByParent[p.id])
      }
    }
    result.push(...standalone)
    return result
  }, [hazards, blockMap, collapsed])

  const toggleCollapse = (parentId: string) => {
    setCollapsed(prev => ({ ...prev, [parentId]: !prev[parentId] }))
  }

  const handleUngroup = (childId: string) => {
    setUngrouped(prev => ({ ...prev, [childId]: true }))
    setPendingAction(null)
  }

  const handleRegroup = (childId: string) => {
    setUngrouped(prev => {
      const next = { ...prev }
      delete next[childId]
      return next
    })
  }

  // Count blocks with children
  const blockCount = blocks.filter(b => b.children.length > 0).length
  const coveredCount = Object.values(blockMap).filter(b => b.isChild && b.isCovered).length
  const ungroupedCount = Object.keys(ungrouped).length

  return (
    <div className="space-y-2">
      {/* Confirmation dialog */}
      {pendingAction && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 p-5 max-w-md w-full mx-4">
            <h3 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">Gefaehrdung aus Block entfernen?</h3>
            <p className="text-xs text-gray-600 dark:text-gray-400 mb-1">
              <strong>{pendingAction.childName}</strong>
            </p>
            <p className="text-xs text-gray-500 mb-4">
              Der Punkt wird als eigenstaendige Gefaehrdung gefuehrt und muss separat bewertet werden.
              Sie koennen ihn jederzeit ueber &quot;Zurueck in Block&quot; wieder zuordnen.
            </p>
            <div className="flex gap-2">
              <button onClick={() => handleUngroup(pendingAction.childId)}
                className="flex-1 px-3 py-2 text-xs font-medium bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
                Als eigenen Punkt fuehren
              </button>
              <button onClick={() => setPendingAction(null)}
                className="flex-1 px-3 py-2 text-xs font-medium bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 transition-colors">
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Block info bar */}
      {blockCount > 0 && (
        <div className="flex items-center gap-4 px-4 py-2 bg-purple-50 dark:bg-purple-900/20 rounded-lg text-xs">
          <span className="font-medium text-purple-700 dark:text-purple-300">
            {blockCount} Bloecke erkannt
          </span>
          {coveredCount > 0 && (
            <span className="text-green-600">
              {coveredCount} Kinder durch Mutter abgedeckt
            </span>
          )}
          {ungroupedCount > 0 && (
            <button onClick={() => setUngrouped({})}
              className="text-orange-600 hover:text-orange-700 underline">
              {ungroupedCount} entgruppiert — alle zuruecksetzen
            </button>
          )}
        </div>
      )}

      {/* Enhanced table with block decorations */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-xs whitespace-nowrap">
            <thead>
              <tr className="bg-gray-100 dark:bg-gray-750 border-b border-gray-200 dark:border-gray-700">
                <th className="w-8 px-1 py-1.5"></th>
                <th colSpan={2} className="px-3 py-1.5 text-left font-semibold text-gray-700 dark:text-gray-300 border-r border-gray-200 dark:border-gray-600">Gefaehrdung</th>
                <th colSpan={4} className="px-3 py-1.5 text-center font-semibold text-gray-700 dark:text-gray-300 border-r border-gray-200 dark:border-gray-600">Risiko (S x F x P)</th>
                <th className="px-3 py-1.5 text-center font-semibold text-gray-700 dark:text-gray-300">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
              {sortedHazards.map(h => {
                const info = blockMap[h.id]
                const isParent = info?.isParent
                const isChild = info?.isChild
                const isCovered = info?.isCovered
                const childCount = info?.childCount || 0
                const isCollapsedParent = isParent && collapsed[h.id]

                return (
                  <tr key={h.id} className={`transition-colors ${
                    isChild ? 'bg-gray-50/50 dark:bg-gray-850' :
                    isParent ? 'bg-white dark:bg-gray-800' : ''
                  } ${isCovered ? 'opacity-60' : ''} hover:bg-gray-50 dark:hover:bg-gray-750`}>
                    {/* Block indicator */}
                    <td className="px-1 py-2 text-center">
                      {isParent && (
                        <button onClick={() => toggleCollapse(h.id)}
                          className="w-5 h-5 flex items-center justify-center rounded hover:bg-purple-100 text-purple-600 transition-colors"
                          title={`${childCount} Kinder ${isCollapsedParent ? 'anzeigen' : 'verbergen'}`}>
                          <svg className={`w-3 h-3 transition-transform ${isCollapsedParent ? '' : '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>
                        </button>
                      )}
                      {isChild && (
                        <div className="flex items-center justify-center">
                          <button onClick={() => setPendingAction({ childId: h.id, childName: h.name })}
                            className="w-5 h-5 flex items-center justify-center rounded hover:bg-orange-100 text-gray-300 hover:text-orange-500 transition-colors"
                            title="Aus Block entfernen (mit Bestaetigung)">
                            <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                            </svg>
                          </button>
                        </div>
                      )}
                      {/* Show regroup button for ungrouped items */}
                      {!isParent && !isChild && ungrouped[h.id] && (
                        <button onClick={() => handleRegroup(h.id)}
                          className="w-5 h-5 flex items-center justify-center rounded hover:bg-green-100 text-orange-400 hover:text-green-600 transition-colors"
                          title="Zurueck in Block">
                          <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                          </svg>
                        </button>
                      )}
                    </td>
                    {/* Name */}
                    <td className={`px-3 py-2 ${isChild ? 'pl-8' : ''}`}>
                      <div className={`font-medium ${isParent ? 'text-purple-800 dark:text-purple-300' : 'text-gray-900 dark:text-white'}`}>
                        {h.name}
                        {isParent && <span className="ml-1 text-[10px] text-purple-500">({childCount})</span>}
                      </div>
                      {h.hazardous_zone && <div className="text-[10px] text-gray-400 truncate max-w-[200px]">{h.hazardous_zone}</div>}
                    </td>
                    {/* Category */}
                    <td className="px-3 py-2 border-r border-gray-200 dark:border-gray-600 text-gray-500">
                      {h.category?.replace(/_/g, ' ')}
                    </td>
                    {/* Risk */}
                    <td className="px-2 py-2 text-center">{h.severity || '-'}</td>
                    <td className="px-2 py-2 text-center">{h.exposure || '-'}</td>
                    <td className="px-2 py-2 text-center">{h.probability || '-'}</td>
                    <td className="px-2 py-2 text-center font-bold border-r border-gray-200 dark:border-gray-600">
                      {h.r_inherent || '-'}
                    </td>
                    {/* Status */}
                    <td className="px-3 py-2 text-center">
                      {isCovered ? (
                        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-green-100 text-green-700 text-[10px] font-medium">
                          <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                          </svg>
                          Abgedeckt
                        </span>
                      ) : h.r_inherent ? (
                        <span className={`inline-block px-1.5 py-0.5 rounded-full text-[10px] font-medium ${
                          (h.r_inherent || 0) <= 20 ? 'bg-green-100 text-green-700' :
                          (h.r_inherent || 0) <= 60 ? 'bg-yellow-100 text-yellow-700' :
                          'bg-red-100 text-red-700'
                        }`}>
                          {(h.r_inherent || 0) <= 20 ? 'Niedrig' : (h.r_inherent || 0) <= 60 ? 'Mittel' : 'Hoch'}
                        </span>
                      ) : (
                        <span className="text-gray-400">Offen</span>
                      )}
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
