import React, { useState } from 'react';
import {
  TableListItem,
  ListItemEditable,
  ListItemEditableSize,
  ListItemEditableMargins,
  ListItemEditableProps,
  FormField,
  Input,
} from '@wix/design-system';
import { useWixPatternsContainer } from '@wix/bex-core/react';

export interface TagItemEditableProps extends Partial<ListItemEditableProps> {
  tagName?: string;
  isLastTag: boolean;
  errorMessage: string | null;
  onApprove: (value: string) => void;
  onCancel: () => void;
  maxLength: number;
}

export const TagItemEditable = ({
  tagName,
  isLastTag,
  errorMessage,
  onApprove,
  onCancel,
  maxLength,
}: TagItemEditableProps) => {
  const { translate: t } = useWixPatternsContainer();
  const [currentValueLength, setCurrentValueLength] = useState(
    tagName?.length ?? 0,
  );

  return (
    <TableListItem
      options={[
        {
          value: (
            <FormField
              dataHook="manage-tags-modal-tag-form-field"
              status={errorMessage ? 'error' : undefined}
              statusMessage={errorMessage}
            >
              <ListItemEditable
                dataHook="manage-tags-modal-tag-editable"
                value={tagName ?? ''}
                onEnterPressed={(e: React.KeyboardEvent<HTMLInputElement>) => {
                  onApprove(e.currentTarget.value);
                }}
                onChange={(e) => setCurrentValueLength(e.target.value.length)}
                onApprove={onApprove}
                onCancel={onCancel}
                placeholder={t(
                  'cairo.tags.manageTags.modal.list.input.placeholder',
                )}
                cancelButtonTooltipContent={t(
                  'cairo.tags.manageTags.modal.list.input.cancel.CTA',
                )}
                approveButtonTooltipContent={t(
                  'cairo.tags.manageTags.modal.list.input.save.CTA',
                )}
                approveButtonDisabledOnEmpty={false}
                autoFocus
                size={'small' as keyof typeof ListItemEditableSize}
                margins={'none' as ListItemEditableMargins}
                suffix={
                  <Input.Affix>
                    {`${currentValueLength} / ${maxLength}`}
                  </Input.Affix>
                }
              />
            </FormField>
          ),
        },
      ]}
      verticalPadding="tiny"
      showDivider={!isLastTag}
    />
  );
};
