import { useState, useEffect } from 'react';
import { Trash2, Edit2, Save, X, Plus, Link as LinkIcon, ArrowUpRight } from 'lucide-react';
import Button from '../../ui/Button';

const RELATION_TYPES = ['related_to', 'depends_on', 'part_of', 'executed_by'];

/**
 * Right-panel node detail section.
 *
 * Owns only its own UI state (edit mode, form drafts).
 * All persistence is delegated back to the parent via callbacks so this
 * component stays pure-UI and trivially testable.
 *
 * Props:
 *   selectedNode   — the currently selected topic object, or null
 *   topics         — full topic list (used for the relation-target selector)
 *   relations      — full relation list (to show outgoing + incoming edges)
 *   onSave(topic)              — called with the fully-merged updated topic
 *   onDelete()                 — called when the admin confirms deletion
 *   onAddRelation(rel)         — called with { source, target, type }
 *   onRemoveRelation(s,t,type) — called to drop a specific edge
 *   onJumpToNode(id)           — pan canvas to node and select it
 */
export default function NodeDetailPanel({
  selectedNode,
  topics,
  relations,
  onSave,
  onDelete,
  onAddRelation,
  onRemoveRelation,
  onJumpToNode,
}) {
  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState({});
  const [newRelData, setNewRelData] = useState({ target: '', type: 'related_to' });

  // Reset local state whenever the selected node changes.
  useEffect(() => {
    setIsEditing(false);
    setEditData({});
    setNewRelData({ target: '', type: 'related_to' });
  }, [selectedNode?.id]);

  const startEdit = () => {
    setEditData({
      label: selectedNode.label,
      type: selectedNode.type,
      description: selectedNode.description ?? '',
      learning_relevance: selectedNode.learning_relevance || 'standard',
      relevance_locked: selectedNode.relevance_locked,
    });
    setIsEditing(true);
  };

  const handleSave = async () => {
    // Auto-lock relevance whenever the admin changes it manually.
    const relevanceChanged = editData.learning_relevance !== selectedNode.learning_relevance;
    const next = { ...editData };
    if (relevanceChanged && next.relevance_locked === undefined) next.relevance_locked = true;
    await onSave({ ...selectedNode, ...next });
    setIsEditing(false);
  };

  const handleAddRelation = async () => {
    if (!newRelData.target) return;
    await onAddRelation({ source: selectedNode.id, target: newRelData.target, type: newRelData.type });
    setNewRelData({ target: '', type: 'related_to' });
  };

  const outgoing = relations.filter(r => r.source === selectedNode?.id);
  const incoming = relations.filter(r => r.target === selectedNode?.id);

  return (
    <div className="flex-1">
      {/* Header — always visible */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-bold text-lg text-teal">Node Details</h3>
        {selectedNode && !isEditing && (
          <div className="flex items-center gap-1">
            <button
              onClick={startEdit}
              className="p-1.5 text-fg-muted hover:text-teal rounded-[var(--r-sm)]"
              title="Edit"
            >
              <Edit2 size={16} />
            </button>
            <button
              onClick={onDelete}
              className="p-1.5 text-fg-muted hover:text-red-500 rounded-[var(--r-sm)]"
              title="Delete"
            >
              <Trash2 size={16} />
            </button>
          </div>
        )}
      </div>

      {/* Empty state */}
      {!selectedNode && (
        <p className="text-sm text-fg-muted">
          Click a node in the graph to view or edit its details.
        </p>
      )}

      {/* Edit mode */}
      {selectedNode && isEditing && (
        <div className="space-y-4">
          <div>
            <label className="text-xs text-fg-muted uppercase tracking-wider mb-1 block">Label</label>
            <input
              className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg"
              value={editData.label ?? ''}
              onChange={e => setEditData({ ...editData, label: e.target.value })}
            />
          </div>

          <div>
            <label className="text-xs text-fg-muted uppercase tracking-wider mb-1 block">Type</label>
            <select
              className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg"
              value={editData.type ?? 'concept'}
              onChange={e => setEditData({ ...editData, type: e.target.value })}
            >
              <option value="concept">Concept</option>
              <option value="role">Role</option>
              <option value="process">Process</option>
            </select>
          </div>

          <div>
            <label className="text-xs text-fg-muted uppercase tracking-wider mb-1 block">
              Learning Relevance
            </label>
            <select
              className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg"
              value={editData.learning_relevance ?? 'standard'}
              onChange={e => setEditData({ ...editData, learning_relevance: e.target.value })}
            >
              <option value="core">Core</option>
              <option value="standard">Standard</option>
              <option value="peripheral">Peripheral</option>
              <option value="exclude">Exclude</option>
            </select>
            {selectedNode.relevance_locked && (
              <label className="flex items-center gap-2 text-xs text-fg-muted mt-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={editData.relevance_locked !== false}
                  onChange={e => setEditData({ ...editData, relevance_locked: e.target.checked })}
                  className="rounded bg-bg-warm border-transparent focus:ring-0 text-teal"
                />
                Locked — re-extraction will not change this
              </label>
            )}
          </div>

          <div>
            <label className="text-xs text-fg-muted uppercase tracking-wider mb-1 block">
              Description
            </label>
            <textarea
              className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg min-h-[100px]"
              value={editData.description ?? ''}
              onChange={e => setEditData({ ...editData, description: e.target.value })}
            />
          </div>

          <div className="flex gap-2 pt-2">
            <Button onClick={handleSave} className="flex-1 flex items-center justify-center gap-2">
              <Save size={16} /> Save
            </Button>
            <Button
              variant="outline"
              onClick={() => setIsEditing(false)}
              className="flex-1 flex items-center justify-center gap-2"
            >
              <X size={16} /> Cancel
            </Button>
          </div>
        </div>
      )}

      {/* View mode */}
      {selectedNode && !isEditing && (
        <div className="space-y-4">
          <div>
            <p className="text-xs text-fg-muted uppercase tracking-wider mb-1">Label</p>
            <p className="font-medium">{selectedNode.label}</p>
          </div>

          <div>
            <p className="text-xs text-fg-muted uppercase tracking-wider mb-1">Type & Relevance</p>
            <div className="flex gap-2 flex-wrap">
              <span className="inline-block px-2 py-1 bg-bg-warm rounded-[var(--r-pill)] text-xs font-mono">
                {selectedNode.type}
              </span>
              <span className="inline-block px-2 py-1 bg-bg-warm rounded-[var(--r-pill)] text-xs font-mono opacity-80">
                {selectedNode.learning_relevance || 'standard'}
              </span>
              {selectedNode.relevance_locked && (
                <span
                  className="inline-block px-2 py-1 bg-teal/10 text-teal rounded-[var(--r-pill)] text-xs font-mono"
                  title="Re-extraction will not change relevance for this topic."
                >
                  locked
                </span>
              )}
            </div>
          </div>

          <div>
            <p className="text-xs text-fg-muted uppercase tracking-wider mb-1">Description</p>
            <p className="text-sm leading-relaxed">{selectedNode.description}</p>
          </div>

          <div>
            <p className="text-xs text-fg-muted uppercase tracking-wider mb-1">ID</p>
            <p className="text-xs font-mono text-fg-muted break-all">{selectedNode.id}</p>
          </div>

          {/* Relations ───────────────────────────────────────────────────── */}
          <div className="pt-4 border-t border-bg-warm">
            {/* Outgoing relations */}
            <p className="text-xs text-fg-muted uppercase tracking-wider mb-3">
              Outgoing ({outgoing.length})
            </p>
            <div className="space-y-2 mb-4">
              {outgoing.length === 0 && (
                <p className="text-xs text-fg-muted italic">No outgoing relations.</p>
              )}
              {outgoing.map((rel, idx) => {
                const target = topics.find(t => t.id === rel.target);
                return (
                  <div
                    key={idx}
                    className="flex items-center justify-between bg-bg rounded-[var(--r-sm)] p-2 border border-bg-warm"
                  >
                    <div className="text-xs min-w-0 mr-2 flex-1">
                      <span className="font-mono text-teal">{rel.type}</span>
                      {' → '}
                      <span className="truncate">{target ? target.label : rel.target}</span>
                    </div>
                    <div className="flex items-center gap-0.5 shrink-0">
                      {target && (
                        <button
                          onClick={() => onJumpToNode?.(rel.target)}
                          className="text-fg-muted hover:text-teal p-1"
                          title={`Jump to "${target.label}"`}
                        >
                          <ArrowUpRight size={13} />
                        </button>
                      )}
                      <button
                        onClick={() => onRemoveRelation(selectedNode.id, rel.target, rel.type)}
                        className="text-fg-muted hover:text-red-500 p-1"
                        title="Remove relation"
                      >
                        <X size={14} />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Incoming relations */}
            <p className="text-xs text-fg-muted uppercase tracking-wider mb-3">
              Incoming ({incoming.length})
            </p>
            <div className="space-y-2 mb-4">
              {incoming.length === 0 && (
                <p className="text-xs text-fg-muted italic">No incoming relations.</p>
              )}
              {incoming.map((rel, idx) => {
                const source = topics.find(t => t.id === rel.source);
                return (
                  <div
                    key={idx}
                    className="flex items-center justify-between bg-bg rounded-[var(--r-sm)] p-2 border border-bg-warm"
                  >
                    <div className="text-xs min-w-0 mr-2 flex-1">
                      <span className="truncate">{source ? source.label : rel.source}</span>
                      {' → '}
                      <span className="font-mono text-teal">{rel.type}</span>
                    </div>
                    {source && (
                      <button
                        onClick={() => onJumpToNode?.(rel.source)}
                        className="shrink-0 text-fg-muted hover:text-teal p-1"
                        title={`Jump to "${source.label}"`}
                      >
                        <ArrowUpRight size={13} />
                      </button>
                    )}
                  </div>
                );
              })}
            </div>

            {/* Add relation ────────────────────────────────────────────── */}
            <div className="bg-bg rounded-[var(--r-sm)] p-3 border border-bg-warm space-y-2">
              <p className="text-xs font-medium flex items-center gap-1">
                <LinkIcon size={12} /> Add Relation
              </p>
              <select
                className="w-full border border-bg-warm rounded-[var(--r-sm)] px-2 py-1 text-xs bg-paper"
                value={newRelData.type}
                onChange={e => setNewRelData({ ...newRelData, type: e.target.value })}
              >
                {RELATION_TYPES.map(t => (
                  <option key={t} value={t}>{t}</option>
                ))}
              </select>
              <select
                className="w-full border border-bg-warm rounded-[var(--r-sm)] px-2 py-1 text-xs bg-paper"
                value={newRelData.target}
                onChange={e => setNewRelData({ ...newRelData, target: e.target.value })}
              >
                <option value="">— Select target topic —</option>
                {topics
                  .filter(t => t.id !== selectedNode.id)
                  .map(t => (
                    <option key={t.id} value={t.id}>{t.label}</option>
                  ))}
              </select>
              <Button
                onClick={handleAddRelation}
                disabled={!newRelData.target}
                className="w-full py-1 text-xs mt-1"
              >
                <Plus size={14} className="mr-1 inline" /> Add
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
