import React, {Fragment, useEffect, useState} from 'react';
import clsx from 'clsx';
import {RefCallBack} from 'react-hook-form';
import {Button} from './buttons/button';
import {LinkIcon} from '../icons/material/Link';
import {TextField} from './forms/input-field/text-field/text-field';
import {Trans} from '../i18n/trans';
import {useSettings} from '../core/settings/use-settings';

export interface SlugEditorProps {
  suffix?: string;
  value?: string;
  onChange?: (value: string) => void;
  className?: string;
  inputRef?: RefCallBack;
  onInputBlur?: () => void;
  showLinkIcon?: boolean;
}
export function SlugEditor({
  suffix,
  value: initialValue,
  onChange,
  className,
  inputRef,
  onInputBlur,
  showLinkIcon = true,
}: SlugEditorProps) {
  const {base_url} = useSettings();
  const fullSuffix = suffix ? `/${suffix}` : '';
  const [isEditing, setIsEditing] = useState(false);
  const [value, setValue] = useState(initialValue);

  useEffect(() => {
    setValue(initialValue);
  }, [initialValue]);

  return (
    <form
      onSubmit={e => {
        e.preventDefault();
        if (!isEditing) {
          setIsEditing(true);
        } else {
          setIsEditing(false);
          if (value) {
            onChange?.(value);
          }
        }
      }}
      className={clsx('flex items-center', className)}
    >
      {showLinkIcon && <LinkIcon className="icon-md text-muted" />}
      <div className="text-primary ml-6 mr-14">
        {base_url}
        {fullSuffix}
        {!isEditing && value && (
          <Fragment>
            <span>/</span>
            <span className="font-medium">{value}</span>
          </Fragment>
        )}
      </div>
      {isEditing && (
        <TextField
          ref={inputRef}
          aria-label="slug"
          autoFocus
          className="mr-14"
          size="xs"
          value={value as string}
          onBlur={onInputBlur}
          onChange={e => {
            setValue(e.target.value);
          }}
        />
      )}
      <Button type="submit" color="chip" variant="outline" size="xs">
        {isEditing ? <Trans message="Save" /> : <Trans message="Edit" />}
      </Button>
    </form>
  );
}
