import { useState, useEffect, useCallback } from 'react'
import { useWebsiteProjects } from '../hooks/useWebsiteProjects'
import AssignedProjectCard from './AssignedProjectCard'

export default function TicketAssignedProjectsPanel({ ticket, refreshKey = 0 }) {
  const { fetchByTicketId } = useWebsiteProjects()
  const [projects, setProjects] = useState([])
  const [loading, setLoading] = useState(true)

  const loadProjects = useCallback(async () => {
    if (!ticket?.$id) return
    setLoading(true)
    try {
      setProjects(await fetchByTicketId(ticket.$id))
    } catch {
      setProjects([])
    } finally {
      setLoading(false)
    }
  }, [ticket?.$id, fetchByTicketId])

  useEffect(() => { loadProjects() }, [loadProjects, refreshKey])

  if (loading || projects.length === 0) return null

  return (
    <div style={{ background: 'rgba(45,55,72,0.5)', borderRadius: 12, padding: 20, border: '1px solid rgba(59,130,246,0.3)', marginTop: 20 }}>
      <h5 style={{ fontWeight: 'bold', marginBottom: 12 }}>Zugewiesene Projekte ({projects.length})</h5>
      {projects.map((project) => (
        <AssignedProjectCard key={project.$id} project={project} />
      ))}
    </div>
  )
}
