"use client";

import React from "react";
import { Button, Textarea } from "ikoncomponents";
import { DecisionsData } from "../../types";
import { StepErrors } from "../../lib/validation";

interface DecisionsStepProps {
  data: DecisionsData;
  onChange: (field: keyof DecisionsData, value: string[]) => void;
  errors: StepErrors;
}

const FieldError = ({ message }: { message?: string }) =>
  message ? <p className="text-xs text-destructive mt-1">{message}</p> : null;

const DecisionsStep: React.FC<DecisionsStepProps> = ({ data, onChange, errors }) => {
  const addDecision = () => onChange("decisions", [...data.decisions, ""]);

  const updateDecision = (idx: number, val: string) => {
    const updated = data.decisions.map((d, i) => (i === idx ? val : d));
    onChange("decisions", updated);
  };

  const removeDecision = (idx: number) => {
    onChange("decisions", data.decisions.filter((_, i) => i !== idx));
  };

  // Top-level array error (e.g. "At least one decision is required")
  const arrayError = errors["decisions"];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
          SI No
        </span>
        <Button
          variant="outline"
          size="sm"
          onClick={addDecision}
          className="text-emerald-600 border-emerald-300 hover:bg-emerald-50"
        >
          + ADD
        </Button>
      </div>

      {/* Array-level error */}
      {arrayError && (
        <p className="text-xs text-destructive">{arrayError}</p>
      )}

      {data.decisions.map((dec, idx) => {
        // Row-level error: "decisions.0", "decisions.1", etc.
        const rowErr = errors[`decisions.${idx}`];
        return (
          <div key={idx} className="flex gap-3 items-start">
            <span className="text-sm text-muted-foreground font-medium w-6 mt-2">{idx + 1}</span>
            <div className="flex-1">
              <Textarea
                rows={3}
                value={dec}
                onChange={(e) => updateDecision(idx, e.target.value)}
                placeholder="Enter decision..."
                className={rowErr ? "border-destructive" : ""}
              />
              <FieldError message={rowErr} />
            </div>
            {data.decisions.length > 1 && (
              <button
                type="button"
                onClick={() => removeDecision(idx)}
                className="text-muted-foreground hover:text-destructive transition-colors text-xl leading-none mt-2"
              >
                ×
              </button>
            )}
          </div>
        );
      })}
    </div>
  );
};

export default DecisionsStep;