import React, { memo, useState } from 'react';
import { Handle, Position } from '@xyflow/react';

const DEFAULT_WEIGHT = 0.5;

function ParamField({ name, schema, value, onChange }) {
  return (
    <label className="canvas-param-field">
      <span>{schema?.label || name}</span>
      <input
        type="number"
        value={value ?? schema?.default ?? 0}
        step={schema?.step ?? 1}
        onChange={(e) => onChange(name, Number(e.target.value))}
      />
    </label>
  );
}

function ScoreNodeCard({ data }) {
  const {
    meta, weight, params, summary, description, accent, icon,
    onWeightChange, onParamsChange,
  } = data;
  const [expanded, setExpanded] = useState(false);

  const active = weight > 0;

  const toggleActive = () => {
    if (active) onWeightChange(0);
    else        onWeightChange(DEFAULT_WEIGHT);
  };

  const updateParam = (key, v) =>
    onParamsChange({ ...params, [key]: v });

  return (
    <div
      className={`canvas-node canvas-node--score ${active ? '' : 'is-inactive'}`}
      style={{ '--canvas-accent': accent || '#3b82f6' }}
    >
      <Handle type="target" position={Position.Left} isConnectable={false} />
      <div className="canvas-node-title">
        <span className="canvas-node-icon">{icon}</span>
        <span>{meta?.label || meta?.name}</span>
        {description && (
          <span className="canvas-node-info" title={description}>ⓘ</span>
        )}
      </div>
      {summary && <div className="canvas-node-summary">{summary}</div>}
      <div className="canvas-node-weight">
        <input
          type="range"
          min={0}
          max={1}
          step={0.05}
          value={weight}
          onChange={(e) => onWeightChange(Number(e.target.value))}
          aria-label="가중치"
        />
        <span className="canvas-node-weight-value">{weight.toFixed(2)}</span>
      </div>
      <label className="canvas-node-active">
        <input
          type="checkbox"
          checked={active}
          onChange={toggleActive}
        />
        <span>활성</span>
      </label>
      <button
        type="button"
        className="canvas-node-expand"
        onClick={() => setExpanded((v) => !v)}
      >
        {expanded ? '▴ 파라미터' : '▾ 파라미터'}
      </button>
      {expanded && (
        <div className="canvas-node-params">
          {Object.entries(meta?.param_schema || {}).map(([key, schema]) => (
            <ParamField
              key={key}
              name={key}
              schema={schema}
              value={params?.[key]}
              onChange={updateParam}
            />
          ))}
        </div>
      )}
      <Handle type="source" position={Position.Right} isConnectable={false} />
    </div>
  );
}

export default memo(ScoreNodeCard);
