'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  AuditSession,
  AuditChecklistItem,
  AuditStatistics,
  Regulation,
} from './types'
import { Language } from '@/lib/compliance-i18n'

const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000'

export function useAuditChecklist() {
  const [sessions, setSessions] = useState<AuditSession[]>([])
  const [selectedSession, setSelectedSession] = useState<AuditSession | null>(null)
  const [checklistItems, setChecklistItems] = useState<AuditChecklistItem[]>([])
  const [statistics, setStatistics] = useState<AuditStatistics | null>(null)
  const [regulations, setRegulations] = useState<Regulation[]>([])
  const [loading, setLoading] = useState(true)
  const [loadingChecklist, setLoadingChecklist] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Filters
  const [filterStatus, setFilterStatus] = useState<string>('all')
  const [filterRegulation, setFilterRegulation] = useState<string>('all')
  const [searchQuery, setSearchQuery] = useState('')

  // Modal states
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showSignOffModal, setShowSignOffModal] = useState(false)
  const [selectedItem, setSelectedItem] = useState<AuditChecklistItem | null>(null)

  // Language
  const [lang] = useState<Language>('de')

  // Load sessions
  const loadSessions = useCallback(async () => {
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/audit/sessions`)
      if (res.ok) {
        const data = await res.json()
        setSessions(data.sessions || [])
      } else {
        console.error('Failed to load sessions:', res.status)
      }
    } catch (err) {
      console.error('Failed to load sessions:', err)
      setError('Verbindung zum Backend fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }, [])

  // Load regulations for filter
  const loadRegulations = useCallback(async () => {
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/regulations`)
      if (res.ok) {
        const data = await res.json()
        setRegulations(data.regulations || [])
      }
    } catch (err) {
      console.error('Failed to load regulations:', err)
    }
  }, [])

  // Load checklist for selected session
  const loadChecklist = useCallback(async (sessionId: string) => {
    setLoadingChecklist(true)
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/audit/checklist/${sessionId}`)
      if (res.ok) {
        const data = await res.json()
        setChecklistItems(data.items || [])
        setStatistics(data.statistics || null)
        if (data.session) {
          setSelectedSession(data.session)
        }
      } else {
        console.error('Failed to load checklist:', res.status)
      }
    } catch (err) {
      console.error('Failed to load checklist:', err)
    } finally {
      setLoadingChecklist(false)
    }
  }, [])

  useEffect(() => {
    loadSessions()
    loadRegulations()
  }, [loadSessions, loadRegulations])

  useEffect(() => {
    if (selectedSession) {
      loadChecklist(selectedSession.id)
    }
  }, [selectedSession, loadChecklist])

  // Filter checklist items
  const filteredItems = checklistItems.filter(item => {
    if (filterStatus !== 'all' && item.current_result !== filterStatus) return false
    if (filterRegulation !== 'all' && item.regulation_code !== filterRegulation) return false
    if (searchQuery) {
      const query = searchQuery.toLowerCase()
      return (
        item.title.toLowerCase().includes(query) ||
        item.article.toLowerCase().includes(query) ||
        item.regulation_code.toLowerCase().includes(query)
      )
    }
    return true
  })

  // Handle sign-off
  const handleSignOff = async (
    item: AuditChecklistItem,
    result: AuditChecklistItem['current_result'],
    notes: string,
    sign: boolean
  ) => {
    if (!selectedSession) return

    try {
      const res = await fetch(
        `${BACKEND_URL}/api/v1/compliance/audit/checklist/${selectedSession.id}/items/${item.requirement_id}/sign-off`,
        {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ result, notes, sign }),
        }
      )

      if (res.ok) {
        await loadChecklist(selectedSession.id)
        setShowSignOffModal(false)
        setSelectedItem(null)
      } else {
        const err = await res.json()
        alert(`Fehler: ${err.detail || 'Sign-off fehlgeschlagen'}`)
      }
    } catch (err) {
      console.error('Sign-off failed:', err)
      alert('Netzwerkfehler bei Sign-off')
    }
  }

  // Create session
  const handleCreateSession = async (data: {
    name: string
    description?: string
    auditor_name: string
    auditor_email?: string
    regulation_codes?: string[]
  }) => {
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/audit/sessions`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      if (res.ok) {
        await loadSessions()
        setShowCreateModal(false)
      } else {
        const err = await res.json()
        alert(`Fehler: ${err.detail || 'Session konnte nicht erstellt werden'}`)
      }
    } catch (err) {
      console.error('Create session failed:', err)
      alert('Netzwerkfehler')
    }
  }

  return {
    sessions,
    selectedSession,
    setSelectedSession,
    checklistItems,
    filteredItems,
    statistics,
    regulations,
    loading,
    loadingChecklist,
    error,
    filterStatus,
    setFilterStatus,
    filterRegulation,
    setFilterRegulation,
    searchQuery,
    setSearchQuery,
    showCreateModal,
    setShowCreateModal,
    showSignOffModal,
    setShowSignOffModal,
    selectedItem,
    setSelectedItem,
    lang,
    handleSignOff,
    handleCreateSession,
  }
}
