import React from 'react';
import MkdSDK from '../utils/MkdSDK';
import { empty } from '../utils/utils';

const sdk = new MkdSDK();
const defaultImage = 'https://via.placeholder.com/150?text=%20';
const DynamicContentType = ({ contentType, contentValue, setContentValue }) => {
  const [previewUrl, setPreviewUrl] = React.useState(defaultImage);
  const handleImageChange = async (e) => {
    const formData = new FormData();
    formData.append('file', e.target.files[0]);
    try {
      const result = await sdk.uploadImage(formData);
      setPreviewUrl(result.url);
      setContentValue(result.url);
    } catch (err) {
      console.error(err);
    }
  };
  switch (contentType) {
    case 'text':
      return (
        <>
          <textarea
            className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            rows={15}
            placeholder='Content'
            onChange={(e) => setContentValue(e.target.value)}
            defaultValue={contentValue}
          ></textarea>
        </>
      );

    case 'image':
      return (
        <>
          <img
            crossOrigin='anonymous'
            src={empty(contentValue) ? previewUrl : contentValue}
            alt='preview'
            height={150}
            width={150}
          />
          <input
            type='file'
            onChange={handleImageChange}
            className={`focus:shadow-outline mb-3 block w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
          />
        </>
      );

    case 'number':
      return (
        <input
          type='number'
          className={`focus:shadow-outline mb-3 block w-full  appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
          onChange={(e) => setContentValue(e.target.value)}
          defaultValue={contentValue}
        />
      );

    case 'team-list':
      return (
        <TeamList
          setContentValue={setContentValue}
          contentValue={contentValue}
        />
      );

    case 'image-list':
      return (
        <ImageList
          setContentValue={setContentValue}
          contentValue={contentValue}
        />
      );

    case 'captioned-image-list':
      return (
        <CaptionedImageList
          setContentValue={setContentValue}
          contentValue={contentValue}
        />
      );

    case 'kvp':
      return (
        <KeyValuePair
          setContentValue={setContentValue}
          contentValue={contentValue}
        />
      );

    default:
      break;
  }
};

export default DynamicContentType;

const ImageList = ({ contentValue, setContentValue }) => {
  let itemsObj = [{ key: '', value_type: 'image', value: null }];
  if (!empty(contentValue)) {
    itemsObj = JSON.parse(contentValue);
  }
  const [items, setItems] = React.useState(itemsObj);

  const handleImageChange = async (e) => {
    const listKey = e.target.getAttribute('listkey');
    const formData = new FormData();
    formData.append('file', e.target.files[0]);
    try {
      const result = await sdk.uploadImage(formData);
      setItems((oldItems) => {
        let updatedItems = oldItems.map((item, index) => {
          if (index == listKey) {
            item.value = result.url;
            return item;
          }
          return item;
        });
        return updatedItems;
      });
      setContentValue(JSON.stringify(items));
    } catch (err) {
      console.error(err);
    }
  };

  const handleKeyChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.key = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  return (
    <div className='block'>
      {items.map((item, index) => (
        <div key={index * 0.23}>
          <img
            crossOrigin='anonymous'
            src={item.value !== null ? item.value : defaultImage}
            alt='preview'
            height={150}
            width={150}
          />
          <div className='flex'>
            <input
              className={`focus:shadow-outline mb-3 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
              type='text'
              placeholder='key'
              listkey={index}
              onChange={handleKeyChange}
              defaultValue={item.key}
            />
            <input
              listkey={index}
              type='file'
              accept='image/*'
              onChange={handleImageChange}
              className={`focus:shadow-outline mb-3 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            />
          </div>
        </div>
      ))}
      <button
        type='button'
        className='focus:shadow-outline my-4 rounded bg-blue-400 px-2 py-1 font-bold text-white hover:bg-blue-700 focus:outline-none'
        onClick={(e) =>
          setItems((old) => [
            ...old,
            { key: '', value_type: 'image', value: null },
          ])
        }
      >
        +
      </button>
    </div>
  );
};

const CaptionedImageList = ({ setContentValue, contentValue }) => {
  let itemsObj = [{ key: '', value_type: 'image', value: null, caption: '' }];

  if (!empty(contentValue)) {
    itemsObj = JSON.parse(contentValue);
  }
  const [items, setItems] = React.useState(itemsObj);

  const handleImageChange = async (e) => {
    const listKey = e.target.getAttribute('listkey');
    const formData = new FormData();
    formData.append('file', e.target.files[0]);
    try {
      const result = await sdk.uploadImage(formData);
      setItems((oldItems) => {
        let updatedItems = oldItems.map((item, index) => {
          if (index == listKey) {
            item.value = result.url;
            return item;
          }
          return item;
        });
        return updatedItems;
      });
      setContentValue(JSON.stringify(items));
    } catch (err) {
      console.error(err);
    }
  };

  const handleKeyChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.key = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  const handleCaptionChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.caption = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  return (
    <div className='block'>
      {items.map((item, index) => (
        <div key={index * 0.23}>
          <img
            crossOrigin='anonymous'
            src={item.value !== null ? item.value : defaultImage}
            alt='preview'
            height={150}
            width={150}
          />
          <div className='flex'>
            <input
              className={`focus:shadow-outline mb-3 mr-2 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
              type='text'
              placeholder='Key'
              listkey={index}
              onChange={handleKeyChange}
              defaultValue={item.key}
            />
            <input
              listkey={index}
              type='file'
              accept='image/*'
              onChange={handleImageChange}
              className={`focus:shadow-outline mb-3 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            />
          </div>
          <input
            className={`focus:shadow-outline mb-3 block w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            type='text'
            placeholder='Caption'
            listkey={index}
            onChange={handleCaptionChange}
            defaultValue={item.caption}
          />
        </div>
      ))}
      <button
        type='button'
        className='focus:shadow-outline my-4 rounded bg-blue-400 px-2 py-1 font-bold text-white hover:bg-blue-700 focus:outline-none'
        onClick={(e) =>
          setItems((old) => [
            ...old,
            { key: '', value_type: 'image', value: null, caption: '' },
          ])
        }
      >
        +
      </button>
    </div>
  );
};
const TeamList = ({ setContentValue, contentValue }) => {
  let itemsObj = [{ name: '', image: null, title: '' }];

  if (!empty(contentValue)) {
    itemsObj = JSON.parse(contentValue);
  }
  const [items, setItems] = React.useState(itemsObj);

  const handleImageChange = async (e) => {
    const listKey = e.target.getAttribute('listkey');
    const formData = new FormData();
    formData.append('file', e.target.files[0]);
    try {
      const result = await sdk.uploadImage(formData);
      setItems((oldItems) => {
        let updatedItems = oldItems.map((item, index) => {
          if (index == listKey) {
            item.image = result.url;
            return item;
          }
          return item;
        });
        return updatedItems;
      });
      setContentValue(JSON.stringify(items));
    } catch (err) {
      console.error(err);
    }
  };

  const handleNameChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.name = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  const handleTitleChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.title = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  return (
    <div className='my-4 block'>
      {items.map((item, index) => (
        <div key={index * 0.23} className='my-4'>
          {/* <div className="flex"> */}
          <input
            className={`focus:shadow-outline mb-3 block w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            type='text'
            placeholder='Title'
            listkey={index}
            onChange={handleTitleChange}
            defaultValue={item.title}
          />
          <input
            className={`focus:shadow-outline mb-3 mr-2 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            type='text'
            placeholder='Name'
            listkey={index}
            onChange={handleNameChange}
            defaultValue={item.name}
          />
          <img
            crossOrigin='anonymous'
            src={item.image !== null ? item.image : defaultImage}
            alt='preview'
            height={150}
            width={150}
          />
          <input
            listkey={index}
            type='file'
            accept='image/*'
            onChange={handleImageChange}
            className={`focus:shadow-outline mb-3 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
          />
          {/* </div> */}
        </div>
      ))}
      <button
        type='button'
        className='focus:shadow-outline my-4 rounded bg-blue-400 px-2 py-1 font-bold text-white hover:bg-blue-700 focus:outline-none'
        onClick={(e) =>
          setItems((old) => [...old, { name: '', image: null, title: '' }])
        }
      >
        +
      </button>
    </div>
  );
};
const KeyValuePair = ({ setContentValue, contentValue }) => {
  let itemsObj = [{ key: '', value_type: 'text', value: '' }];

  if (!empty(contentValue)) {
    itemsObj = JSON.parse(contentValue);
  }

  const [items, setItems] = React.useState(itemsObj);
  const valueTypeMap = [
    {
      key: 'text',
      value: 'Text',
    },
    {
      key: 'number',
      value: 'Number',
    },
    {
      key: 'json',
      value: 'JSON Object',
    },
    {
      key: 'url',
      value: 'URL',
    },
  ];

  const handleKeyChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.key = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  const handleValueChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.value = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  const handleValueTypeChange = (e) => {
    const listKey = e.target.getAttribute('listkey');
    setItems((oldItems) => {
      let updatedItems = oldItems.map((item, index) => {
        if (index == listKey) {
          item.value_type = e.target.value;
          return item;
        }
        return item;
      });
      return updatedItems;
    });
    setContentValue(JSON.stringify(items));
  };

  return (
    <div className='block'>
      {items.map((item, index) => (
        <div key={index * 0.23} className='my-4'>
          <input
            className={`focus:shadow-outline mb-3 mr-2 w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            type='text'
            placeholder='Key'
            listkey={index}
            onChange={handleKeyChange}
            defaultValue={item.key}
          />
          <select
            className={`focus:shadow-outline mb-3 block w-full rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            listkey={index}
            onChange={handleValueTypeChange}
            defaultValue={item.value_type}
          >
            {valueTypeMap.map((type, index) => (
              <option key={index * 122} value={type.key}>
                {type.value}
              </option>
            ))}
          </select>
          <input
            className={`focus:shadow-outline mb-3 block w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none`}
            type='text'
            required
            placeholder='Value'
            listkey={index}
            onChange={handleValueChange}
            defaultValue={item.value}
          />
        </div>
      ))}
      <button
        type='button'
        className='focus:shadow-outline my-4 rounded bg-blue-400 px-2 py-1 font-bold text-white hover:bg-blue-700 focus:outline-none'
        onClick={(e) =>
          setItems((old) => [
            ...old,
            { key: '', value_type: 'text', value: '' },
          ])
        }
      >
        +
      </button>
    </div>
  );
};
