import { useMemo, useState } from "react";
import { ToggleButtonGroup } from "../common";
import AssignItemForModal from "../modals/AssignItemForModal";
import "../../styles/components/AddItemForm.css";
import SuggestionList from "../items/SuggestionList";

export default function AddItemForm({
  onAdd,
  onSuggest,
  suggestions,
  buttonText = "Add",
  householdMembers = [],
  currentUserId = null
}) {
  const [itemName, setItemName] = useState("");
  const [quantity, setQuantity] = useState(1);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [assignmentMode, setAssignmentMode] = useState("me");
  const [assignedUserId, setAssignedUserId] = useState(null);
  const [showAssignModal, setShowAssignModal] = useState(false);

  const numericCurrentUserId =
    currentUserId == null ? null : Number.parseInt(String(currentUserId), 10);

  const otherMembers = useMemo(
    () => householdMembers.filter((member) => Number(member.id) !== numericCurrentUserId),
    [householdMembers, numericCurrentUserId]
  );

  const assignedMemberLabel = useMemo(() => {
    if (assignmentMode !== "others" || assignedUserId == null) return "";
    const member = otherMembers.find((item) => Number(item.id) === Number(assignedUserId));
    return member ? (member.display_name || member.name || member.username || `User ${member.id}`) : "";
  }, [assignmentMode, assignedUserId, otherMembers]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!itemName.trim()) return;

    if (assignmentMode === "others" && assignedUserId == null) {
      if (otherMembers.length > 0) {
        setShowAssignModal(true);
      }
      return;
    }

    const targetUserId = assignmentMode === "others" ? Number(assignedUserId) : null;
    onAdd(itemName, quantity, targetUserId);
    setItemName("");
    setQuantity(1);
    setAssignmentMode("me");
    setAssignedUserId(null);
    setShowAssignModal(false);
  };

  const handleInputChange = (text) => {
    setItemName(text);
    onSuggest(text);
  };

  const handleSuggestionSelect = (suggestion) => {
    setItemName(suggestion);
    setShowSuggestions(false);
    onSuggest(suggestion); // Trigger button text update
  };

  const incrementQuantity = () => {
    setQuantity(prev => prev + 1);
  };

  const decrementQuantity = () => {
    setQuantity(prev => Math.max(1, prev - 1));
  };

  const handleAssignmentModeChange = (mode) => {
    if (mode === "me") {
      setAssignmentMode("me");
      setAssignedUserId(null);
      setShowAssignModal(false);
      return;
    }

    if (otherMembers.length === 0) {
      setAssignmentMode("me");
      setAssignedUserId(null);
      return;
    }

    setAssignmentMode("others");
    setShowAssignModal(true);
  };

  const handleAssignCancel = () => {
    setShowAssignModal(false);
    setAssignmentMode("me");
    setAssignedUserId(null);
  };

  const handleAssignConfirm = (memberId) => {
    setShowAssignModal(false);
    setAssignmentMode("others");
    setAssignedUserId(Number(memberId));
  };

  const isDisabled = !itemName.trim();

  return (
    <div className="add-item-form-container">
      <form onSubmit={handleSubmit} className="add-item-form">
        <div className="add-item-form-input-row">
          <div className="add-item-form-field">
            <input
              type="text"
              className="add-item-form-input"
              placeholder="Enter item name"
              value={itemName}
              onChange={(e) => handleInputChange(e.target.value)}
              onBlur={() => setTimeout(() => setShowSuggestions(false), 150)}
              onClick={() => setShowSuggestions(true)}
            />

            {showSuggestions && suggestions.length > 0 && (
              <SuggestionList
                suggestions={suggestions}
                onSelect={handleSuggestionSelect}
              />
            )}
          </div>

          <ToggleButtonGroup
            value={assignmentMode}
            ariaLabel="Item assignment mode"
            className="tbg-group add-item-form-assignee-toggle"
            sizeClassName="tbg-size-xxs"
            options={[
              { value: "me", label: "Me" },
              { value: "others", label: "Others", disabled: otherMembers.length === 0 }
            ]}
            onChange={handleAssignmentModeChange}
          />
        </div>

        {assignmentMode === "others" && assignedMemberLabel ? (
          <p className="add-item-form-assignee-hint">Adding for: {assignedMemberLabel}</p>
        ) : null}

        <div className="add-item-form-actions">
          <div className="add-item-form-quantity-control">
            <button
              type="button"
              className="quantity-btn quantity-btn-minus"
              onClick={decrementQuantity}
              disabled={quantity <= 1}
            >
              −
            </button>
            <input
              type="number"
              min="1"
              className="add-item-form-quantity-input"
              value={quantity}
              readOnly
            />
            <button
              type="button"
              className="quantity-btn quantity-btn-plus"
              onClick={incrementQuantity}
            >
              +
            </button>
          </div>

          <button
            type="submit"
            className={`add-item-form-submit ${isDisabled ? 'disabled' : ''}`}
            disabled={isDisabled}
          >
            {buttonText}
          </button>
        </div>
      </form>

      <AssignItemForModal
        isOpen={showAssignModal}
        members={otherMembers}
        onCancel={handleAssignCancel}
        onConfirm={handleAssignConfirm}
      />
    </div>
  );
}
