'use client'

import { useState, useEffect } from 'react'
import { Mitigation, Hazard, ProtectiveMeasure, MitigationFormData } from '../_components/types'

export function useMitigations(projectId: string) {
  const [mitigations, setMitigations] = useState<Mitigation[]>([])
  const [hazards, setHazards] = useState<Hazard[]>([])
  const [loading, setLoading] = useState(true)
  const [hierarchyWarning, setHierarchyWarning] = useState<boolean>(false)
  const [measures, setMeasures] = useState<ProtectiveMeasure[]>([])

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

  async function fetchData() {
    try {
      const [mitRes, hazRes] = await Promise.all([
        fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations`),
        fetch(`/api/sdk/v1/iace/projects/${projectId}/hazards`),
      ])
      let hazardList: Hazard[] = []
      if (hazRes.ok) {
        const json = await hazRes.json()
        hazardList = (json.hazards || json || []).map((h: Record<string, unknown>) => ({ id: h.id as string, name: h.name as string, risk_level: h.risk_level as string, category: h.category as string, operational_states: (h.operational_states || []) as string[] }))
        setHazards(hazardList)
      }
      if (mitRes.ok) {
        const json = await mitRes.json()
        const raw = json.mitigations || json || []
        // Map API fields (name, hazard_id) to frontend fields (title, linked_hazard_ids/names)
        const hazardMap = Object.fromEntries(hazardList.map((h) => [h.id, h.name]))
        const hazardStatesMap = Object.fromEntries(hazardList.map((h) => [h.id, (h as unknown as Record<string, unknown>).operational_states || []]))
        const mits: Mitigation[] = raw.map((m: Record<string, unknown>) => ({
          id: m.id as string,
          title: (m.title || m.name || '') as string,
          description: (m.description || '') as string,
          reduction_type: (m.reduction_type === 'protective' ? 'protection' : m.reduction_type || 'design') as Mitigation['reduction_type'],
          status: (m.status || 'planned') as Mitigation['status'],
          linked_hazard_ids: m.linked_hazard_ids ? (m.linked_hazard_ids as string[]) : m.hazard_id ? [m.hazard_id as string] : [],
          linked_hazard_names: m.linked_hazard_ids
            ? (m.linked_hazard_ids as string[]).map((id) => hazardMap[id] || id)
            : m.hazard_id ? [hazardMap[m.hazard_id as string] || (m.hazard_id as string)] : [],
          created_at: (m.created_at || '') as string,
          verified_at: (m.verified_at || null) as string | null,
          verified_by: (m.verified_by || null) as string | null,
          is_relevant: Boolean(m.is_relevant),
          is_customer_standard: Boolean(m.is_customer_standard),
          operational_states: (() => {
            const ids = m.linked_hazard_ids ? (m.linked_hazard_ids as string[]) : m.hazard_id ? [m.hazard_id as string] : []
            const states = new Set<string>()
            ids.forEach((id) => { ((hazardStatesMap[id] || []) as string[]).forEach((s) => states.add(s)) })
            return [...states]
          })(),
        }))
        setMitigations(mits)
        validateHierarchy(mits)
      }
    } catch (err) {
      console.error('Failed to fetch data:', err)
    } finally {
      setLoading(false)
    }
  }

  async function validateHierarchy(mits: Mitigation[]) {
    if (mits.length === 0) return
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/validate-mitigation-hierarchy`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          mitigations: mits.map((m) => ({
            reduction_type: m.reduction_type,
            linked_hazard_ids: m.linked_hazard_ids,
          })),
        }),
      })
      if (res.ok) {
        const json = await res.json()
        setHierarchyWarning(json.has_warning === true)
      }
    } catch {
      // Non-critical, ignore
    }
  }

  async function fetchMeasuresLibrary(type?: string) {
    try {
      const url = type
        ? `/api/sdk/v1/iace/protective-measures-library?reduction_type=${type}`
        : '/api/sdk/v1/iace/protective-measures-library'
      const res = await fetch(url)
      if (res.ok) {
        const json = await res.json()
        setMeasures(json.protective_measures || [])
      }
    } catch (err) {
      console.error('Failed to fetch measures library:', err)
    }
  }

  async function handleSubmit(data: MitigationFormData) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      if (res.ok) {
        await fetchData()
        return true
      }
    } catch (err) {
      console.error('Failed to add mitigation:', err)
    }
    return false
  }

  async function handleAddSuggestedMeasure(title: string, description: string, reductionType: string, hazardId: string) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title, description, reduction_type: reductionType, linked_hazard_ids: [hazardId] }),
      })
      if (res.ok) await fetchData()
    } catch (err) {
      console.error('Failed to add suggested measure:', err)
    }
  }

  async function handleVerify(id: string) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations/${id}/verify`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })
      if (res.ok) await fetchData()
    } catch (err) {
      console.error('Failed to verify mitigation:', err)
    }
  }

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

  // Bulk delete without per-row confirm; caller owns the confirm-step.
  async function handleDeleteSilent(id: string) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations/${id}`, { method: 'DELETE' })
      if (!res.ok) console.error('delete failed for', id, res.status)
    } catch (err) {
      console.error('Failed to delete mitigation:', err)
    }
  }

  // Flag a mitigation as relevant for this project (or unflag). Optimistic:
  // updates local state immediately, refetches afterwards.
  async function handleSetRelevant(id: string, value: boolean) {
    setMitigations((prev) => prev.map((m) => m.id === id ? { ...m, status: m.status } : m))
    try {
      await fetch(`/api/sdk/v1/iace/mitigations/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_relevant: value }),
      })
      await fetchData()
    } catch (err) {
      console.error('Failed to set relevant flag:', err)
    }
  }

  // Mark a mitigation as "customer standard" — already implemented at the
  // customer's site, no evidence required. Implies is_relevant=true (server
  // enforces this via the CHECK constraint).
  async function handleSetCustomerStandard(id: string, value: boolean) {
    try {
      await fetch(`/api/sdk/v1/iace/mitigations/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_customer_standard: value }),
      })
      await fetchData()
    } catch (err) {
      console.error('Failed to set customer-standard flag:', err)
    }
  }

  const byType = {
    design: mitigations.filter((m) => m.reduction_type === 'design'),
    protection: mitigations.filter((m) => m.reduction_type === 'protection'),
    information: mitigations.filter((m) => m.reduction_type === 'information'),
  }

  return {
    mitigations, hazards, loading, hierarchyWarning, setHierarchyWarning,
    measures, byType, fetchData,
    fetchMeasuresLibrary, handleSubmit, handleAddSuggestedMeasure, handleVerify,
    handleDelete, handleDeleteSilent, handleSetRelevant, handleSetCustomerStandard,
  }
}
