import { useState, useEffect, useCallback } from 'react'
import { FaPlus, FaTimes } from 'react-icons/fa'
import { useWebsiteProjects } from '../hooks/useWebsiteProjects'
import { createProjectFromTemplate } from '../lib/projectAdminApi'
import AssignedProjectCard from './AssignedProjectCard'

function slugify(v) {
  return String(v || '').toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100)
}

export default function TicketProjectsModal({ isOpen, onClose, ticket, onUpdated }) {
  const { fetchAllProjects, fetchByTicketId, assignProjects, unassignProject } = useWebsiteProjects()
  const [assigned, setAssigned] = useState([])
  const [available, setAvailable] = useState([])
  const [selectedIds, setSelectedIds] = useState([])
  const [loading, setLoading] = useState(true)
  const [actionLoading, setActionLoading] = useState(false)
  const [error, setError] = useState('')
  const [createForm, setCreateForm] = useState({ displayName: '', subdomain: '', repoName: '' })

  const loadProjects = useCallback(async () => {
    if (!ticket?.$id) return
    setLoading(true)
    setError('')
    try {
      const [all, mine] = await Promise.all([fetchAllProjects(), fetchByTicketId(ticket.$id)])
      setAssigned(mine)
      const assignedIds = new Set(mine.map((p) => p.$id))
      setAvailable((all || []).filter((p) => p.repoFullName && !assignedIds.has(p.$id)))
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }, [ticket, fetchAllProjects, fetchByTicketId])

  useEffect(() => { if (isOpen) loadProjects() }, [isOpen, loadProjects])

  if (!isOpen) return null

  const handleAssign = async () => {
    if (!selectedIds.length) return
    setActionLoading(true)
    const r = await assignProjects(selectedIds, { customerId: ticket.customerId || '', ticketId: ticket.$id })
    setActionLoading(false)
    if (r.success) { setSelectedIds([]); await loadProjects(); onUpdated?.() } else setError(r.error)
  }

  const handleCreate = async (e) => {
    e.preventDefault()
    setActionLoading(true)
    setError('')
    try {
      await createProjectFromTemplate({
        repoName: createForm.repoName || createForm.subdomain,
        displayName: createForm.displayName,
        subdomain: slugify(createForm.subdomain),
        customerId: ticket.customerId || '',
        ticketId: ticket.$id,
      })
      setCreateForm({ displayName: '', subdomain: '', repoName: '' })
      await loadProjects()
      onUpdated?.()
    } catch (err) {
      setError(err.message)
    } finally {
      setActionLoading(false)
    }
  }

  const handleUnassign = async (projectId) => {
    setActionLoading(true)
    await unassignProject(projectId)
    setActionLoading(false)
    await loadProjects()
    onUpdated?.()
  }

  return (
    <div className="overlay ticket-projects-overlay">
      <span className="overlay-close" onClick={onClose}>{'\u00d7'}</span>
      <div className="overlay-content ticket-projects-modal">
        <div className="ticket-projects-modal-header">
          <h2>Projekte bearbeiten</h2>
          <button type="button" className="btn btn-sm" onClick={onClose} aria-label="Schliessen"><FaTimes /></button>
        </div>
        {error && <div className="bg-red text-white p-2 mb-2">{error}</div>}
        {loading ? <p className="text-grey">Projekte werden geladen...</p> : (
          <div className="ticket-projects-modal-grid">
            <section className="ticket-projects-modal-section">
              <h6>Zugewiesen</h6>
              {assigned.length === 0 ? <p className="text-grey">Keine Projekte zugewiesen.</p> : assigned.map((p) => (
                <AssignedProjectCard key={p.$id} project={p} showActions onUnassign={handleUnassign} />
              ))}
            </section>
            <div className="ticket-projects-modal-side">
              <section className="ticket-projects-modal-section">
                <h6>Verfuegbar zuweisen</h6>
                {available.length === 0 ? <p className="text-grey">Keine weiteren Projekte verfuegbar.</p> : (
                  <div className="ticket-projects-available-list">
                    {available.map((p) => (
                      <label key={p.$id} className="ticket-projects-available-item">
                        <input type="checkbox" checked={selectedIds.includes(p.$id)} onChange={() => setSelectedIds((s) => s.includes(p.$id) ? s.filter((x) => x !== p.$id) : [...s, p.$id])} />
                        <span>{p.projectName} ({p.subdomain || p.repoFullName})</span>
                      </label>
                    ))}
                  </div>
                )}
                <button type="button" className="btn btn-teal mt-2" disabled={!selectedIds.length || actionLoading} onClick={handleAssign}>Zuweisen</button>
              </section>
              <section className="ticket-projects-modal-section">
                <h6><FaPlus /> Neues Projekt</h6>
                <form onSubmit={handleCreate} className="ticket-projects-create-form">
                  <input className="form-control" placeholder="Anzeigename" value={createForm.displayName} onChange={(e) => setCreateForm((f) => ({ ...f, displayName: e.target.value }))} required />
                  <input className="form-control" placeholder="Subdomain" value={createForm.subdomain} onChange={(e) => setCreateForm((f) => ({ ...f, subdomain: e.target.value, repoName: f.repoName || slugify(e.target.value) }))} required />
                  <button type="submit" className="btn btn-dark" disabled={actionLoading}>{actionLoading ? 'Wird angelegt...' : 'Anlegen & zuweisen'}</button>
                </form>
              </section>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
