import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'
import customFieldsService from 'app/services/tenant/CustomFieldsService'
import { Box, styled } from '@mui/system'
import { Breadcrumb, SimpleCard } from 'app/components'
import PanToolIcon from '@mui/icons-material/PanTool'
import PinchIcon from '@mui/icons-material/Pinch'
import { Grid, Fab } from '@mui/material'
import SaveIcon from '@mui/icons-material/Save'
import { toast } from 'react-toastify'
import _ from 'lodash'
import { MatxLoading } from 'app/components'
import FAQSService from 'app/services/allThingsLocals/FAQSService'
import FrontendFAQSService from 'app/services/allThingsLocals/FrontendFAQSService'

const Container = styled('div')(({ theme }) => ({
    margin: '30px',
    [theme.breakpoints.down('sm')]: {
        margin: '16px',
    },
    '& .breadcrumb': {
        marginBottom: '30px',
        [theme.breakpoints.down('sm')]: {
            marginBottom: '16px',
        },
    },
}))

const Save = styled(Fab)(({ theme }) => ({
    position: 'absolute',
    top: theme.spacing(5),
    right: theme.spacing(5),
}))

// fake data generator
const getItems = (count, offset = 0) =>
    Array.from({ length: count }, (v, k) => k).map((k) => ({
        id: `item-${k + offset}-${new Date().getTime()}`,
        content: `item ${k + offset}`,
    }))

const reorder = (list, startIndex, endIndex) => {
    const result = Array.from(list)
    const [removed] = result.splice(startIndex, 1)
    result.splice(endIndex, 0, removed)

    return result
}

/**
 * Moves an item from one list to another list.
 */
const move = (source, destination, droppableSource, droppableDestination) => {
    const sourceClone = Array.from(source)
    const destClone = Array.from(destination)
    const [removed] = sourceClone.splice(droppableSource.index, 1)

    destClone.splice(droppableDestination.index, 0, removed)

    const result = {}
    result[droppableSource.droppableId] = sourceClone
    result[droppableDestination.droppableId] = destClone

    return result
}
const grid = 8

const getItemStyle = (isDragging, draggableStyle) => ({
    // some basic styles to make the items look a bit nicer
    userSelect: 'none',
    padding: '1.2rem',
    margin: `0 0 0.5rem 0`,

    // change background colour if dragging
    background: isDragging ? '#196e27' : '#11579c',
    color: 'white',
    borderRadius: '0.5rem',
    // styles we need to apply on draggables
    ...draggableStyle,
})
const getListStyle = (isDraggingOver) => ({
    background: isDraggingOver ? '#2B324C' : 'white',
    paddingLeft: '2rem',
    paddingRight: '2rem',
    width: '100%',
})

export default function DraggableFAQS({ userType }) {
    const [state, setState] = useState([getItems(10), []])
    const [allCustomFields, setAllCustomFields] = useState([])
    const [fetching, setFetching] = useState(false)
    const [isLoading, setIsLoading] = useState(false)

    const findNonDuplicate = (array, fields) => {
        for (var i = array.length - 1; i >= 0; i--) {
            for (var j = 0; j < fields.length; j++) {
                if (array[i] && array[i]._id === fields[j]._id) {
                    array.splice(i, 1)
                }
            }
        }
        return array
    }

    React.useEffect(() => {
        setIsLoading(true)

        FAQSService.getAllFAQS().then((res) => {
            FrontendFAQSService.getByType({ userType }).then((res2) => {
                console.log('FAQS ALL: ', res)
                console.log('USER FAFQS: ', res2)
                let arrRes = [...res]
                let fields = res2.faqs || []
                arrRes = findNonDuplicate(arrRes, fields)
                let array2 = [arrRes, fields]
                console.log('NEW ARRAY: ', array2)
                setState(array2)
                setIsLoading(false)
            })
        })
    }, [])
    function onDragEnd(result) {
        const { source, destination } = result

        // dropped outside the list
        if (!destination) {
            return
        }
        const sInd = +source.droppableId
        const dInd = +destination.droppableId

        if (sInd === dInd) {
            const items = reorder(state[sInd], source.index, destination.index)
            const newState = [...state]
            newState[sInd] = items
            setState(newState)
        } else {
            const result = move(state[sInd], state[dInd], source, destination)
            const newState = [...state]
            newState[sInd] = result[sInd]
            newState[dInd] = result[dInd]

            setState(newState.filter((group) => group.length))
        }
    }

    if (isLoading) {
        return <MatxLoading />
    }

    return (
        <div>
            <Container>
                <SimpleCard title="Drag and drop FAQ">
                    <div style={{ display: 'flex' }}>
                        <DragDropContext onDragEnd={onDragEnd}>
                            {state.map((el, ind) => (
                                <Droppable key={ind} droppableId={`${ind}`}>
                                    {(provided, snapshot) => (
                                        <div
                                            ref={provided.innerRef}
                                            style={getListStyle(
                                                snapshot.isDraggingOver
                                            )}
                                            {...provided.droppableProps}
                                        >
                                            {ind == 0 ? (
                                                <h2>All FAQS</h2>
                                            ) : (
                                                <h2>User FAQS</h2>
                                            )}
                                            {el.map((item, index) => (
                                                <Draggable
                                                    key={item._id}
                                                    draggableId={item._id}
                                                    index={index}
                                                >
                                                    {(provided, snapshot) => (
                                                        <div
                                                            ref={
                                                                provided.innerRef
                                                            }
                                                            {...provided.draggableProps}
                                                            {...provided.dragHandleProps}
                                                            style={getItemStyle(
                                                                snapshot.isDragging,
                                                                provided
                                                                    .draggableProps
                                                                    .style
                                                            )}
                                                        >
                                                            <Grid
                                                                container
                                                                spacing={2}
                                                            >
                                                                <Grid
                                                                    item
                                                                    lg={3}
                                                                    md={3}
                                                                    sm={3}
                                                                    xs={3}
                                                                >
                                                                    <PinchIcon />
                                                                </Grid>
                                                                <Grid
                                                                    item
                                                                    lg={6}
                                                                    md={6}
                                                                    sm={6}
                                                                    xs={6}
                                                                >
                                                                    {
                                                                        item.question
                                                                    }
                                                                </Grid>
                                                            </Grid>
                                                        </div>
                                                    )}
                                                </Draggable>
                                            ))}
                                            {provided.placeholder}
                                        </div>
                                    )}
                                </Droppable>
                            ))}
                        </DragDropContext>
                    </div>
                    <Save
                        color="primary"
                        aria-label="add"
                        style={{
                            position: 'absolute',
                        }}
                        disabled={fetching}
                        onClick={() => {
                            // setIsLoading(true)
                            console.log('DATE TO SEND:', {
                                userType,
                                faqs: state[1],
                            })
                            FrontendFAQSService.addFrontendFAQ({
                                userType,
                                faqs: state[1],
                            }).then((res) => {
                                toast.success('Data Updated')
                            })
                        }}
                    >
                        <SaveIcon />
                    </Save>
                </SimpleCard>
            </Container>
        </div>
    )
}
