import React, { useEffect, useRef, useState } from 'react';
import { Image, View } from 'react-native';
import { faLocationArrow } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { Form } from '@unform/mobile';
import * as _ from 'lodash';
import { Observable } from 'rxjs';
import { CreateRange, deleteEmpty, Resolve } from '../../../../services';
import { themeDefault } from '../../../AppProvider/ITheme';
import { FadeIn } from '../../../FadeIn/native';
import { Flex } from '../../../Flex/native';
import { Input } from '../../../Input/native';
import { Pressable } from '../../../Pressable';
import { RSValue } from '../../../RFValue';
import { TextNative } from '../../../TextNative';
import { IFilterComponent } from '../PageListing.interface';
import PropertyImage1 from './images/property1.jpg';
import PropertyImage2 from './images/property2.jpg';
import PropertyImage3 from './images/property3.jpg';
import PropertyImage4 from './images/property4.jpg';
import PropertyImage5 from './images/property5.jpg';
import PropertyImage6 from './images/property6.jpg';

export const Filters: IFilterComponent<any> = React.memo(function Filters({ handleFilters, filters, formRef }): any {
   const [initialData, setInitialData] = useState(configureForm(filters));

   function configureForm(_filters: any): any {
      const filtersAux = { ..._filters };
      return filtersAux;
   }

   useEffect(() => {
      formRef.current.reset();
      formRef.current.setData(configureForm(filters));
   }, [filters]);

   function onSubmit(_filters: any): void {
      const filtersAux = { ..._filters };
      handleFilters(deleteEmpty(filtersAux));
   }

   return (
      <View style={{ padding: 15 }}>
         <Form onSubmit={onSubmit} ref={formRef} initialData={initialData}>
            <Input name="id" title="ID" />

            <Input name="location" title="Localização" />

            <Input name="address" title="Endereço" />

            <Input name="price" title="Preço" />
         </Form>
      </View>
   );
}, _.isEqual);

export const resolveItems: Resolve<any> = (params: any) =>
   new Observable((subscriber) => {
      setTimeout(() => {
         subscriber.next({
            results: [
               {
                  id: parseInt((params?.offset || 0) as any, 10) + 1,
                  image: PropertyImage1,
               },
               {
                  id: parseInt((params?.offset || 0) as any, 10) + 2,
                  image: PropertyImage2,
               },
               {
                  id: parseInt((params?.offset || 0) as any, 10) + 3,
                  image: PropertyImage3,
               },
               {
                  id: parseInt((params?.offset || 0) as any, 10) + 4,
                  image: PropertyImage4,
               },
               {
                  id: parseInt((params?.offset || 0) as any, 10) + 5,
                  image: PropertyImage5,
               },
               {
                  id: parseInt((params?.offset || 0) as any, 10) + 6,
                  image: PropertyImage6,
               },
            ],
            count: 120200,
         });
         subscriber.complete();
         subscriber.unsubscribe();
      }, 800);
   });

export const resolveNotFound: Resolve<any> = (params: any) =>
   new Observable((subscriber) => {
      setTimeout(() => {
         subscriber.next({
            results: [],
            count: 0,
         });
         subscriber.complete();
         subscriber.unsubscribe();
      }, 800);
   });

export const resolveError: Resolve<any> = (params: any) =>
   new Observable((subscriber) => {
      setTimeout(() => {
         subscriber.error({});
         subscriber.complete();
         subscriber.unsubscribe();
      }, 800);
   });

export const resolveManyItems: Resolve<any> = (params: any) =>
   new Observable((subscriber) => {
      setTimeout(() => {
         subscriber.next({
            results:
               params?.offset >= 40
                  ? []
                  : CreateRange(20).map((i) => ({
                       id: parseInt((params?.offset || 0) as any, 10) + i,
                       image: PropertyImage1,
                    })),
            count: 40,
         });
         subscriber.complete();
         subscriber.unsubscribe();
      }, 800);
   });

let error = 2;

export const resolveManyItemsError: Resolve<any> = (params: any) =>
   new Observable((subscriber) => {
      setTimeout(() => {
         if (error == 0 || !params?.offset) {
            subscriber.next({
               results:
                  params?.offset >= 40
                     ? []
                     : CreateRange(20).map((i) => ({
                          id: parseInt((params?.offset || 0) as any, 10) + i,
                          image: PropertyImage1,
                       })),
               count: 40,
            });
         } else {
            subscriber.error({});
         }

         if (!params?.offset) {
            error = 2;
         } else {
            error -= 1;
         }

         subscriber.complete();
         subscriber.unsubscribe();
      }, 800);
   });

export const Card = React.memo(
   function Card({ skeleton = false, selected = false, onSelect = null, property = {} }: any): any {
      const image = property?.image ? property?.image : null;

      return (
         <FadeIn>
            <Pressable
               onLongPress={() => !skeleton && onSelect && onSelect(property)}
               onPress={() => !skeleton && onSelect && onSelect(property)}
               ripple
            >
               <View style={{ padding: RSValue(10), opacity: !selected ? 1.0 : 0.4 }}>
                  {!skeleton && (
                     <View
                        style={{
                           backgroundColor: 'black',
                           padding: 5,
                           position: 'absolute',
                           zIndex: 10,
                           left: 20,
                           top: 20,
                        }}
                     >
                        <TextNative size={12} color="white">
                           COD. {property.id}
                        </TextNative>
                     </View>
                  )}
                  <Image
                     source={image}
                     style={{
                        resizeMode: 'cover',
                        width: '100%',
                        height: RSValue(150),
                        borderRadius: RSValue(20),
                        backgroundColor: '#ddd',
                     }}
                  />
                  <View style={{ paddingTop: RSValue(5), flexDirection: 'row' }}>
                     <Flex flex={1} justifyContent="center">
                        <TextNative
                           size={13}
                           style={{
                              backgroundColor: skeleton ? '#eee' : 'transparent',
                              color: skeleton ? 'transparent' : '#888',
                           }}
                        >
                           The Rose Hill District
                        </TextNative>
                     </Flex>
                     <Flex>
                        <TextNative
                           size={16}
                           color={!skeleton ? themeDefault.primary : 'transparent'}
                           bold
                           style={{ backgroundColor: skeleton ? themeDefault.primary : 'transparent' }}
                        >
                           R$120.000.000
                        </TextNative>
                     </Flex>
                  </View>
                  <View style={{ paddingTop: RSValue(3), flexDirection: 'row' }}>
                     <Flex flex={1} justifyContent="center">
                        <TextNative
                           size={12}
                           color={skeleton ? 'transparent' : '#888'}
                           style={{
                              backgroundColor: skeleton ? '#eee' : 'transparent',
                           }}
                        >
                           {!skeleton && <FontAwesomeIcon icon={faLocationArrow} size={RSValue(10)} color="#444" />}
                           JL. Amarto, Seturan, Caturtunggal
                        </TextNative>
                     </Flex>
                  </View>
               </View>
            </Pressable>
         </FadeIn>
      );
   },
   (o, n) => {
      return _.isEqual(o, n);
   },
);
