﻿import { Plus, X } from "lucide-react";
import { compactQuestions } from "./utils";

interface BusinessQuestionsEditorProps {
  value: string[];
  onChange: (questions: string[]) => void;
  disabled?: boolean;
}

export function BusinessQuestionsEditor({ value, onChange, disabled }: BusinessQuestionsEditorProps) {
  const questions = value.length ? value : [""];

  const update = (index: number, next: string) => {
    const copy = [...questions];
    copy[index] = next;
    onChange(copy);
  };

  const remove = (index: number) => {
    if (questions.length <= 2) return;
    const next = questions.filter((_, i) => i !== index);
    onChange(next.length ? next : [""]);
  };

  const canAdd = questions.length < 5;
  const canRemove = questions.length > 2;

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <label className="text-xs font-medium text-slate-600">Business questions ({questions.length}/5)</label>
        {canAdd && (
          <button
            type="button"
            onClick={() => onChange([...questions, ""])}
            disabled={disabled}
            className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-50 disabled:opacity-40"
          >
            <Plus className="h-3 w-3" />
            Add
          </button>
        )}
      </div>
      <div className="space-y-2">
        {questions.map((question, index) => (
          <div key={index} className="flex gap-2">
            <input
              value={question}
              onChange={(event) => update(index, event.target.value)}
              disabled={disabled}
              placeholder={index === 0 ? "What should this analysis answer?" : "Add another question"}
              className="min-w-0 flex-1 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 outline-none transition placeholder:text-slate-400 focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 disabled:bg-slate-50"
            />
            {canRemove && (
              <button
                type="button"
                aria-label="Remove question"
                onClick={() => remove(index)}
                disabled={disabled}
                className="rounded-lg border border-slate-200 p-2 text-slate-500 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:opacity-40"
              >
                <X className="h-4 w-4" />
              </button>
            )}
          </div>
        ))}
      </div>
      {compactQuestions(questions).length < 2 && <p className="text-xs text-red-600">Add at least 2 questions (max 5).</p>}
    </div>
  );
}
