'use client'

import { useState, useEffect } from 'react'
import { Component, ComponentFormData, LibraryComponent, EnergySource, PresenceStatus, buildTree } from '../_components/types'

export function useComponents(projectId: string) {
  const [components, setComponents] = useState<Component[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchComponents()
  }, [projectId]) // eslint-disable-line react-hooks/exhaustive-deps

  async function fetchComponents() {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/components`)
      if (res.ok) {
        const json = await res.json()
        setComponents(json.components || json || [])
      }
    } catch (err) {
      console.error('Failed to fetch components:', err)
    } finally {
      setLoading(false)
    }
  }

  async function handleSubmit(data: ComponentFormData, editingId?: string) {
    try {
      const url = editingId
        ? `/api/sdk/v1/iace/projects/${projectId}/components/${editingId}`
        : `/api/sdk/v1/iace/projects/${projectId}/components`
      const method = editingId ? 'PUT' : 'POST'

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      if (res.ok) {
        await fetchComponents()
        return true
      }
    } catch (err) {
      console.error('Failed to save component:', err)
    }
    return false
  }

  // Move a component between presence states (vorhanden / nicht_vorhanden /
  // geloescht). Used for the expert's bidirectional review of auto-detected
  // components.
  async function setPresence(id: string, status: PresenceStatus) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/components/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ presence_status: status }),
      })
      if (res.ok) await fetchComponents()
    } catch (err) {
      console.error('Failed to set presence:', err)
    }
  }

  // Mark a component as a bought CE product (robot, actuator, SPS ...). Safe
  // semantics: no hazard suppression — only provenance + PL/SIL note.
  async function setCEMarked(id: string, value: boolean) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/components/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ce_marked: value }),
      })
      if (res.ok) await fetchComponents()
    } catch (err) {
      console.error('Failed to set ce_marked:', err)
    }
  }

  // Soft-delete: the component moves to the "Geloescht" list (restorable); it is
  // not removed from the project, so nothing silently disappears.
  async function handleDelete(id: string) {
    await setPresence(id, 'geloescht')
  }

  async function handleAddFromLibrary(libraryComps: LibraryComponent[], energySrcs: EnergySource[]) {
    const energySourceIds = energySrcs.map(e => e.id)
    for (const comp of libraryComps) {
      try {
        await fetch(`/api/sdk/v1/iace/projects/${projectId}/components`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            name: comp.name_de,
            type: comp.maps_to_component_type,
            description: comp.description_de,
            safety_relevant: false,
            library_component_id: comp.id,
            energy_source_ids: energySourceIds,
            tags: comp.tags,
          }),
        })
      } catch (err) {
        console.error(`Failed to add component ${comp.id}:`, err)
      }
    }
    await fetchComponents()
  }

  return {
    components,
    loading,
    tree: buildTree(components),
    handleSubmit,
    handleDelete,
    handleAddFromLibrary,
    setPresence,
    setCEMarked,
  }
}
