import { useEffect, useState } from 'react'
import { IconTrash, IconX } from '@tabler/icons-react'
import { Card, Button, Field } from '../ui'
import { useEmployees } from '../../hooks/useEmployees'
import { NODE_KIND, NODE_STATUS, NODE_STATUS_LABELS } from '../../lib/roadmaps'

const STATUS_ORDER = [NODE_STATUS.OPEN, NODE_STATUS.IN_PROGRESS, NODE_STATUS.DONE]

/**
 * Seitliches Detail-Panel fuer den ausgewaehlten Knoten:
 * Titel, Status, Zustaendiger, Deadline, Notizen, eingehende Verbindungen.
 */
export default function NodeDetailPanel({
  node,
  nodes,
  readOnly,
  onClose,
  onSave,
  onSetStatus,
  onDelete,
  onDisconnect,
}) {
  const { employees } = useEmployees()
  const [form, setForm] = useState({ title: '', assignedTo: '', deadline: '', notes: '' })
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    setForm({
      title: node.title || '',
      assignedTo: node.assignedTo || '',
      deadline: node.deadline || '',
      notes: node.notes || '',
    })
    setError('')
  }, [node.$id]) // eslint-disable-line react-hooks/exhaustive-deps

  const isStart = node.kind === NODE_KIND.START
  const incoming = (node.sourceIds || [])
    .map((id) => nodes.find((n) => n.$id === id))
    .filter(Boolean)

  const handleSave = async () => {
    if (!form.title.trim()) {
      setError('Titel darf nicht leer sein.')
      return
    }
    setSaving(true)
    setError('')
    const employee = employees.find((e) => e.userId === form.assignedTo)
    const result = await onSave(node, {
      title: form.title.trim(),
      assignedTo: form.assignedTo,
      assignedName: employee?.displayName || '',
      deadline: form.deadline,
      notes: form.notes,
    })
    setSaving(false)
    if (!result.success) setError(result.error)
  }

  return (
    <Card
      title={isStart ? 'Start-Knoten' : node.kind === NODE_KIND.GOAL ? 'Ziel-Knoten' : 'Schritt'}
      actions={<Button variant="ghost" onClick={onClose}><IconX size={16} /></Button>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <Field label="Titel">
          <input
            type="text"
            value={form.title}
            maxLength={128}
            disabled={readOnly}
            onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
          />
        </Field>

        {!isStart && (
          <Field label="Status">
            <div style={{ display: 'flex', gap: 6 }}>
              {STATUS_ORDER.map((status) => (
                <Button
                  key={status}
                  variant={node.status === status ? 'primary' : 'default'}
                  disabled={readOnly}
                  onClick={() => onSetStatus(node, status)}
                >
                  {NODE_STATUS_LABELS[status]}
                </Button>
              ))}
            </div>
          </Field>
        )}

        {!isStart && (
          <Field label="Zustaendig">
            <select
              value={form.assignedTo}
              disabled={readOnly}
              onChange={(e) => setForm((f) => ({ ...f, assignedTo: e.target.value }))}
            >
              <option value="">Niemand</option>
              {employees.map((e) => (
                <option key={e.userId} value={e.userId}>{e.displayName}</option>
              ))}
            </select>
          </Field>
        )}

        {!isStart && (
          <Field label="Deadline">
            <input
              type="date"
              value={form.deadline}
              disabled={readOnly}
              onChange={(e) => setForm((f) => ({ ...f, deadline: e.target.value }))}
            />
          </Field>
        )}

        <Field label="Notizen">
          <textarea
            rows={4}
            value={form.notes}
            maxLength={2000}
            disabled={readOnly}
            placeholder="Details, Anforderungen, Links…"
            onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
          />
        </Field>

        {incoming.length > 0 && (
          <Field label="Eingehende Verbindungen">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {incoming.map((source) => (
                <div key={source.$id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }}>
                  <span className="muted">{source.title}</span>
                  {!readOnly && (
                    <Button variant="ghost" title="Verbindung loesen" onClick={() => onDisconnect(source.$id, node)}>
                      <IconX size={14} />
                    </Button>
                  )}
                </div>
              ))}
            </div>
          </Field>
        )}

        {error && <p style={{ color: 'var(--danger, #ef4444)', fontSize: 13 }}>{error}</p>}

        {!readOnly && (
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
            {!isStart ? (
              <Button variant="ghost" onClick={() => onDelete(node)} title="Knoten loeschen">
                <IconTrash size={15} /> Loeschen
              </Button>
            ) : <span />}
            <Button variant="primary" onClick={handleSave} disabled={saving}>
              {saving ? 'Speichere…' : 'Speichern'}
            </Button>
          </div>
        )}
      </div>
    </Card>
  )
}
