import React, { useEffect, useRef, useState } from 'react';
import { action } from '@storybook/addon-actions';
import { storiesOf } from '@storybook/react';
import { FormHandles } from '@devesharp/unform-core';
import { Form } from '@devesharp/unform-web';
import { Observable } from 'rxjs';
import styled from 'styled-components';
import { IAutocompleteItem } from '../AutocompletePure';
import { CloseBtn } from '../CloseBtn';
import { InputTags } from './InputTags';

const css = styled.div;

const Style = css`
   background: white !important;

   .tag-custom {
      cursor: pointer;
      margin: 0px 3px 3px 0px;
      border-radius: 10px;
      padding: 3px 10px;
      font-size: 13px;
      font-weight: 600;
      display: inline-flex !important;
      flex-direction: row;
      max-width: 100%;
      align-items: center;
      position: relative;
      overflow: hidden;
   }

   .item-text {
      z-index: 1;
      position: relative;
      display: inline-block;
      white-space: nowrap;
      display: inline-flex !important;
      flex-direction: row;
      justify-content: center;
      align-content: center;
      align-items: center;
   }

   .tag-rainbow {
      height: 100%;
      width: 100%;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      position: absolute;
      background: linear-gradient(
         124deg,
         #ff2400,
         #e81d1d,
         #e8b71d,
         #e3e81d,
         #1de840,
         #1ddde8,
         #2b1de8,
         #dd00f3,
         #dd00f3
      );
      background-size: 1800% 1800%;

      -webkit-animation: rainbow 18s ease infinite;
      -z-animation: rainbow 18s ease infinite;
      -o-animation: rainbow 18s ease infinite;
      animation: rainbow 18s ease infinite;
   }

   @-webkit-keyframes rainbow {
      0% {
         background-position: 0% 82%;
      }
      50% {
         background-position: 100% 19%;
      }
      100% {
         background-position: 0% 82%;
      }
   }
   @-moz-keyframes rainbow {
      0% {
         background-position: 0% 82%;
      }
      50% {
         background-position: 100% 19%;
      }
      100% {
         background-position: 0% 82%;
      }
   }
   @-o-keyframes rainbow {
      0% {
         background-position: 0% 82%;
      }
      50% {
         background-position: 100% 19%;
      }
      100% {
         background-position: 0% 82%;
      }
   }
   @keyframes rainbow {
      0% {
         background-position: 0% 82%;
      }
      50% {
         background-position: 100% 19%;
      }
      100% {
         background-position: 0% 82%;
      }
   }
`;

const fetchGroupMock = (): Observable<IAutocompleteItem[]> =>
   new Observable((observable) => {
      setTimeout(() => {
         observable.next([
            { name: 'Star Platinum', value: 1 },
            { name: "Magician's Red", value: 2 },
            { name: 'Hermit Purple', value: 3 },
            { name: 'Hierophant Green', value: 4 },
            { name: 'Silver Chariot', value: 5 },
            { name: 'The Fool', value: 6 },
            { name: 'The World', value: 7 },
            { name: 'Tower of Gray', value: 8 },
            { name: 'Dark Blue Moon', value: 9 },
            { name: 'Strength', value: 10 },
            { name: 'Ebony Devil', value: 11 },
            { name: 'Yellow Temperance', value: 12 },
            { name: 'Hanged Man', value: 13 },
            { name: 'Emperor', value: 14 },
            { name: 'Empress', value: 15 },
            { name: 'Wheel of Fortune', value: 16 },
            { name: 'Justice', value: 17 },
            { name: 'Lovers', value: 18 },
            { name: 'Sun', value: 19 },
         ]);
         observable.complete();
         observable.unsubscribe();
      }, 100);
   });

const fetchGroupMock5 = (): Observable<IAutocompleteItem[]> =>
   new Observable((observable) => {
      setTimeout(() => {
         observable.next([{ name: 'KKK', value: 1 }]);
         observable.complete();
         observable.unsubscribe();
      }, 100);
   });

const fetchSimpleMock = (): Observable<any> =>
   new Observable((observable) => {
      setTimeout(() => {
         observable.next(['São Paulo', 'Suzano', 'Guarulhos']);
         observable.complete();
         observable.unsubscribe();
      }, 100);
   });

storiesOf('Components/InputTags', module)
   .add('default', () => {
      return (
         <div className="m-4 max-input">
            <Form onSubmit={(v) => action('onSubmit')(v)}>
               <InputTags name="tags" fetchItems={fetchGroupMock} title="Tags" placeholder="Buscar..." />

               <button data-testid="submit" type="submit">
                  Submit
               </button>
            </Form>
         </div>
      );
   })
   .add('with sync initialSearch', () => {
      const [s, setS] = useState(false);
      function fetchGroupMock2(b): any {
         return s ? fetchGroupMock(b) : fetchGroupMock5(b);
      }
      return (
         <div className="m-4 max-input">
            <Form onSubmit={(v) => action('onSubmit')(v)}>
               <InputTags
                  persistOpenAutoCompleteItemsAfterSelect
                  name="tags"
                  fetchItems={fetchGroupMock2}
                  initialSearch="initialSearch"
                  title="Tags"
                  placeholder="Buscar..."
               />

               <button data-testid="submit" type="submit">
                  Submit
               </button>

               <button data-testid="submit" type="button" onClick={() => setS((n) => !n)}>
                  Submit2
               </button>
            </Form>
         </div>
      );
   })
   .add('with state values', () => {
      const [tags, setTags] = useState<any[]>([]);

      function clearTags(): void {
         setTags([]);
      }

      return (
         <div className="m-4 max-input">
            <InputTags
               tags={tags}
               onChange={(t) => setTags(t)}
               fetchItems={fetchGroupMock}
               title="Tags"
               placeholder="Buscar..."
            />

            <button onClick={clearTags}>Limpar tags</button>
         </div>
      );
   })
   .add('with default value', () => {
      return (
         <div className="m-4 max-input">
            <Form
               onSubmit={(v) => action('onSubmit')(v)}
               initialData={{
                  tags: [
                     {
                        name: 'The World',
                        value: 7,
                     },
                  ],
               }}
            >
               <InputTags name="tags" fetchItems={fetchGroupMock} title="Tags" placeholder="Buscar..." />

               <button data-testid="submit" type="submit">
                  Submit
               </button>
            </Form>
         </div>
      );
   })
   .add('with default value invalid', () => {
      return (
         <div className="m-4 max-input">
            <Form
               onSubmit={(v) => action('onSubmit')(v)}
               initialData={{
                  tags: null,
               }}
            >
               <InputTags name="tags" fetchItems={fetchGroupMock} title="Tags" placeholder="Buscar..." />

               <button data-testid="submit" type="submit">
                  Submit
               </button>
            </Form>
         </div>
      );
   })
   .add('with custom tags', () => {
      function Tag({ tag, removeTag }: any): any {
         return (
            <div className="tag-custom" onClick={() => removeTag && removeTag(tag)}>
               <div className="tag-rainbow" />
               <div className="item-text">
                  <div className="name">{tag.name}</div>
                  <div className="close-btn">
                     <CloseBtn size={10} color="white" />
                  </div>
               </div>
            </div>
         );
      }
      return (
         <Style>
            <div className="m-4 max-input">
               <Form
                  onSubmit={(v) => action('onSubmit')(v)}
                  initialData={{
                     tags: [
                        {
                           name: 'The World',
                           value: 7,
                        },
                     ],
                  }}
               >
                  <InputTags
                     name="tags"
                     fetchItems={fetchGroupMock}
                     title="Tags"
                     placeholder="Buscar..."
                     CustomTag={Tag}
                  />

                  <button data-testid="submit" type="submit">
                     Submit
                  </button>
               </Form>
            </div>
         </Style>
      );
   })
   .add('with error', () => {
      const formRef = useRef<FormHandles>();

      useEffect(() => {
         formRef.current.setFieldError('tags', 'Field Invalid');
      }, []);

      return (
         <div className="m-4 max-input">
            <Form ref={formRef} onSubmit={(v) => action('onSubmit')(v)}>
               <InputTags name="tags" fetchItems={fetchGroupMock} title="Tags" placeholder="Buscar..." />

               <button data-testid="submit" type="submit">
                  Submit
               </button>
            </Form>
         </div>
      );
   });
