import m from "mithril"
import moment from "moment"
import _ from "lodash"
import powerform from "powerform"
import { Card, Button, RaisedButton, TextField, Dialog, Snackbar } from "polythene-mithril"
import DatePicker from "../custom/mithril-datepicker"
import {} from "../../css/custom/mithril-datepicker.css"
import { nav } from "./nav"
import Section from "../models/Section"

var Question = {
    view: function(vnode) {
        var data = vnode.attrs.data
        return _.isEmpty(data) ?
        m(".flex#question-new", m(newQuestion))
        : [
            m("div", data.map(function(question) {
                return m(".flex.drag-wrapper", m(viewQuestion, {data: question}))
            }), m(".flex", m(plusButton)))
        ]
    }
}

var plusButton = {
    view: function() {
        return m(".flex#question-new", m(Button, {
            className: "flex",
            label: [
                m("i.fa.fa-plus.fa-fw"),
                m.trust("&nbsp;"),
                "Tambah"
            ],
            style: {
                padding: ".8em",
                fontSize: "14px",
                lineHeight: "14px",
                fontWeight: "500",
                textTransform: "uppercase",
                whiteSpace: "pre",
                transition: ".2s all ease"
            },
            events: {
                onmouseover: function() {
                    this.childNodes[0].style.backgroundColor = "rgba(255, 255, 255, .8)"
                },
                onmouseout: function() {
                    this.childNodes[0].style.backgroundColor = "#fff"
                },
                onclick: function() {
                    m.mount(document.getElementById("question-new"), {
                        view: function() {
                            return m(newQuestion)
                        }
                    })
                }
            }
        }))
    }
}

var editQuestion = {
    view: function(vnode) {
        var data = vnode.attrs.data
        return [
            m(Card, {
                style: {
                    flexGrow: "1"
                },
                content: [
                    {
                        text: {
                            content: [
                                m(TextField, {
                                    label: "Teks",
                                    required: true,
                                    floatingLabel: true,
                                    tight: true,
                                    value: data.text,
                                    events: {
                                        oninput: m.withAttr("value", function(value) {
                                            data.text = value
                                        })
                                    }
                                }),
                                m(TextField, {
                                    label: "Deskripsi",
                                    floatingLabel: true,
                                    tight: true,
                                    value: data.description,
                                    events: {
                                        oninput: m.withAttr("value", function(value) {
                                            data.description = value
                                        })
                                    }
                                }),
                                m("div", {
                                    style: {
                                        textAlign: "right"
                                    }
                                }, [
                                    m(RaisedButton, {
                                        label: [
                                            m("i.fa.fa-check.fa-fw"),
                                            m.trust("&nbsp;"),
                                            "Simpan"
                                        ],
                                        tone: "dark",
                                        style: {
                                            padding: ".6em .8em",
                                            fontSize: "14px",
                                            lineHeight: "14px",
                                            fontWeight: "500",
                                            textTransform: "uppercase",
                                            whiteSpace: "pre",
                                            backgroundColor: "#009933"
                                        },
                                        events: {
                                            onclick: function() {
                                                m.mount(
                                                    vnode.attrs.parent,
                                                    {
                                                        view: function() {
                                                            return m(viewQuestion, {data: data})
                                                        }
                                                    }
                                                )
                                            }
                                        }
                                    }),
                                    m(RaisedButton, {
                                        label: [
                                            m("i.fa.fa-check.fa-fw"),
                                            m.trust("&nbsp;"),
                                            "Batal"
                                        ],
                                        tone: "dark",
                                        style: {
                                            padding: ".6em .8em",
                                            fontSize: "14px",
                                            lineHeight: "14px",
                                            fontWeight: "500",
                                            textTransform: "uppercase",
                                            whiteSpace: "pre",
                                            backgroundColor: "#ff0000"
                                        },
                                        events: {
                                            onclick: function() {
                                                m.mount(
                                                    vnode.attrs.parent,
                                                    {
                                                        view: function() {
                                                            return m(viewQuestion, {data: data})
                                                        }
                                                    }
                                                )
                                            }
                                        }
                                    })
                                ])
                            ]
                        }
                    }
                ]
            })
        ]
    }
}

var newQuestion = {
    data: {},
    form: powerform({
        req: function(v) {
            if (!v || v == "" || _.isEmpty(v) || _.isNil(v)) {
                return "Kolom ini harus diisi"
            }
        }
    }),
    oninit: function() {
        newQuestion.data = {}
    },
    oncreate: function() {
        document.getElementById("question-text")
        .querySelector("input").focus()
    },
    view: function() {
        return [
            m(Card, {
                style: {
                    flexGrow: "1"
                },
                content: [
                    {
                        text: {
                            content: [
                                m("form", {
                                    onsubmit: function(e) {
                                        e.preventDefault()
                                        if (newQuestion.form.isValid()) {
                                            var target = document.getElementById("question-new")
                                            .parentNode
                                            var targetParent = Array.prototype
                                            .slice.call(target.parentNode.childNodes)
                                            var index = targetParent.indexOf(target) + 1
                                            newQuestion.data.number = index
                                            Section.current.questions
                                            .push(newQuestion.data)
                                            m.mount(
                                                document.getElementById("question-new"),
                                                {
                                                    view: function() {
                                                        return m(newQuestion)
                                                    }
                                                }
                                            )
                                        }
                                    }
                                }, [
                                    m(TextField, {
                                        id: "question-text",
                                        label: "Teks",
                                        floatingLabel: true,
                                        tight: true,
                                        value: newQuestion.data.text,
                                        events: {
                                            oninput: m.withAttr("value", function(value) {
                                                newQuestion.data.text = value
                                                newQuestion.form.req(value)
                                            })
                                        },
                                        validate: function() {
                                            return {
                                                valid: newQuestion.form.req.isValid(),
                                                error: newQuestion.form.req.error()
                                            }
                                        }
                                    }),
                                    m(TextField, {
                                        id: "question-description",
                                        label: "Deskripsi",
                                        floatingLabel: true,
                                        tight: true,
                                        value: newQuestion.data.description,
                                        events: {
                                            oninput: m.withAttr("value", function(value) {
                                                newQuestion.data.description = value
                                            })
                                        }
                                    }),
                                    m("div", {
                                        style: {
                                            textAlign: "right"
                                        }
                                    }, [
                                        m(RaisedButton, {
                                            element: "button",
                                            type: "submit",
                                            label: [
                                                m("i.fa.fa-check.fa-fw"),
                                                m.trust("&nbsp;"),
                                                "Tambah"
                                            ],
                                            tone: "dark",
                                            style: {
                                                padding: ".6em .8em",
                                                fontSize: "14px",
                                                lineHeight: "14px",
                                                fontWeight: "500",
                                                textTransform: "uppercase",
                                                whiteSpace: "pre",
                                                backgroundColor: "#009933"
                                            }
                                        }),
                                        m(RaisedButton, {
                                            label: [
                                                m("i.fa.fa-check.fa-fw"),
                                                m.trust("&nbsp;"),
                                                "Batal"
                                            ],
                                            tone: "dark",
                                            style: {
                                                padding: ".6em .8em",
                                                fontSize: "14px",
                                                lineHeight: "14px",
                                                fontWeight: "500",
                                                textTransform: "uppercase",
                                                whiteSpace: "pre",
                                                backgroundColor: "#ff0000"
                                            },
                                            events: {
                                                onclick: function() {
                                                    newQuestion.data = {}
                                                    m.mount(
                                                        document.getElementById("question-new"),
                                                        {
                                                            view: function() {
                                                                return m(plusButton)
                                                            }
                                                        }
                                                    )
                                                }
                                            }
                                        })
                                    ])
                                ])
                            ]
                        }
                    }
                ]
            })
        ]
    }
}

var trashSVG = "<svg width=\"1792\" height=\"1792\" viewBox=\"0 0 1792 1792\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\"><path d=\"M704 736v576q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h64q14 0 23 9t9 23zm256 0v576q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h64q14 0 23 9t9 23zm256 0v576q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h64q14 0 23 9t9 23zm128 724v-948h-896v948q0 22 7 40.5t14.5 27 10.5 8.5h832q3 0 10.5-8.5t14.5-27 7-40.5zm-672-1076h448l-48-117q-7-9-17-11h-317q-10 2-17 11zm928 32v64q0 14-9 23t-23 9h-96v948q0 83-47 143.5t-113 60.5h-832q-66 0-113-58.5t-47-141.5v-952h-96q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h309l70-167q15-37 54-63t79-26h320q40 0 79 26t54 63l70 167h309q14 0 23 9t9 23z\"/></svg>"

var viewQuestion = {
    oncreate: function() {
        var drags = document.getElementsByClassName("draggable")
        for (var i = 0; i < drags.length; i++) {
            drags[i].draggable = true
            drags[i].ondragstart = sCard.onDrag
            drags[i].parentNode.ondrop = sCard.onDrop
            drags[i].parentNode.ondragover = sCard.onDragOver
            drags[i].parentNode.ondragleave = sCard.onDragLeave
        }
    },
    view: function(vnode) {
        var data = vnode.attrs.data
        return [
            m(Card, {
                style: {
                    flexGrow: "1"
                },
                id: "question-" + data.number,
                className: "draggable",
                content: [
                    {
                        text: {
                            content: [
                                m("i.fa.fa-times.fa-fw#remove" + data.id, {
                                    style: {
                                        position: "absolute",
                                        right: "0",
                                        cursor: "pointer"
                                    }
                                }),
                                m("h5", data.text),
                                m("div", data.description)
                            ]
                        }
                    }
                ],
                events: {
                    onclick: function(e) {
                        var parent = this.parentNode
                        if (e.target != document.querySelector("#remove" + data.id)) {
                            return m.mount(parent, {
                                view: function() {
                                    return m(editQuestion, {data: data, parent: parent})
                                }
                            })
                        } else {
                            Dialog.show({
                                body: [
                                    m(".pe-dialog-pane__title", "Hapus " + data.text),
                                    m("div", "Pertanyaan ini akan dihapus setelah klik pada tombol 'Simpan'.")
                                ],
                                footerButtons: [
                                    m(Button, {
                                        label: "Konfirmasi",
                                        events: {
                                            onclick: function() {
                                                _.remove(
                                                    Section.current.questions,
                                                    function(o) {
                                                        return o.id == data.id
                                                    }
                                                )
                                                // var target = document.getElementById("question-" + data.number)
                                                // target.parentNode.removeChild(target)
                                                for (var i = 0; i < Section.current.questions.length; i++) {
                                                    Section.current.questions[i].number = i + 1
                                                }
                                                Dialog.hide()
                                            }
                                        }
                                    }),
                                    m(Button, {
                                        label: "Batal",
                                        events: {
                                            onclick: Dialog.hide
                                        }
                                    })
                                ],
                                backdrop: true,
                                didHide: function() {
                                    if (document.body.querySelector(".flex .pe-dialog__holder") != null) {
                                        document.body.querySelector(".flex").removeChild(
                                            document.body.querySelector(".flex .pe-dialog__holder")
                                        )
                                    }
                                    document.body.className = ""
                                }
                            })
                        }
                    },
                    onmousedown: function() {
                        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent) == false) {
                            Snackbar.show({
                                id: "protip",
                                title: [
                                    m("span", {
                                        style: {color: "rgb(255, 153, 0)"}
                                    }, "Tips", m("i.fa.fa-lightbulb-o.fa-fw[aria-hidden=true]")),
                                    ": Tahan dan geser item untuk memindahkan urutan"
                                ],
                                action: m(Button, {
                                    id: "protip-button",
                                    label: m("i.fa.fa-times[aria-hidden=true]"),
                                    events: {
                                        onclick: function() {
                                            Snackbar.hide()
                                        },
                                        oncreate: function() {
                                            document.body
                                            .querySelector(".flex #protip #protip-button")
                                            .style.minWidth = "0"
                                        }
                                    }
                                }),
                                timeout: 5,
                                didHide: function() {
                                    if (document.body.querySelector(".flex #protip") != null) {
                                        document.body.querySelector(".flex").removeChild(
                                            document.body.querySelector(".flex #protip").parentNode
                                        )
                                    }
                                    document.body.className = ""
                                }
                            })
                        }
                    }
                }
            })
        ]
    }
}

var sCard = {
    onDrag: function(e) {
        e.dataTransfer.setData("element", e.target.id)
    },
    onDrop: function(e) {
        e.preventDefault()
        var data = document.getElementById(e.dataTransfer.getData("element"))
        var dataParent = data.parentNode
        var target = this
        var newIndex = Array.prototype.slice.call(target.parentNode.childNodes)
        .indexOf(this)
        var oldIndex = Array.prototype.slice.call(dataParent.parentNode.childNodes)
        .indexOf(dataParent)
        Section.current.questions[oldIndex].number = newIndex + 1
        Section.current.questions[newIndex].number = oldIndex + 1
        Section.current.questions = _.sortBy(Section.current.questions, function(o) {
            return o.number
        })
        m.redraw()

        target.style.backgroundColor = "transparent"
    },
    onDragOver: function(e) {
        e.preventDefault()
        this.style.backgroundColor = "rgba(0, 0, 0, .2)"
    },
    onDragLeave: function(e) {
        e.preventDefault()
        this.style.backgroundColor = "transparent"
    },
    form: powerform({
        req: function(v) {
            if (!v || v == "" || _.isEmpty(v) || _.isNil(v)) {
                return "Kolom ini harus diisi"
            }
        }
    }),
    oninit: function() {
        sCard.form.req(Section.current.title)
    },
    view: function() {
        return m("form", {
            onsubmit: function(e) {
                e.preventDefault()
                if (sCard.form.isValid()) {
                    m.route.set("/user/sections/" + Section.current.id)
                }
            },
            style: {
                flexGrow: "1",
                display: "flex"
            }
        }, m(Card, {
            style: {flexGrow: "1"},
            content: [
                {
                    text: {
                        content: [
                            m(TextField, {
                                label: "Judul",
                                floatingLabel: true,
                                tight: true,
                                value: Section.current.title,
                                events: {
                                    oninput: m.withAttr("value", function(v) {
                                        Section.current.title = v
                                        sCard.form.req(v)
                                    })
                                },
                                validate: function() {
                                    return {
                                        valid: sCard.form.req.isValid(),
                                        error: sCard.form.req.error()
                                    }
                                }
                            }),
                            m(TextField, {
                                label: "Deskripsi",
                                floatingLabel: true,
                                tight: true,
                                value: Section.current.description,
                                events: {
                                    oninput: m.withAttr("value", function(v) {
                                        Section.current.description = v
                                    })
                                }
                            }),
                            m(".flex", {
                                style: {
                                    fontSize: "larger"
                                }
                            }, "Pertanyaan"),
                            m(Question, {data: Section.current.questions})
                        ]
                    }
                },
                {
                    actions: {
                        bordered: true,
                        content: [
                            m(RaisedButton, {
                                element: "button",
                                label: [
                                    m("i.fa.fa-floppy-o.fa-fw"),
                                    m.trust("&nbsp;"),
                                    "Simpan"
                                ],
                                style: {
                                    padding: ".6em .8em",
                                    fontSize: "14px",
                                    lineHeight: "14px",
                                    fontWeight: "500",
                                    textTransform: "uppercase",
                                    whiteSpace: "pre",
                                    backgroundColor: "#00cc00"
                                },
                                tone: "dark",
                            }),
                            m(".flex"),
                            m(RaisedButton, {
                                label: [
                                    m("i.fa.fa-times.fa-fw"),
                                    m.trust("&nbsp;"),
                                    "Hapus"
                                ],
                                style: {
                                    padding: ".6em .8em",
                                    fontSize: "14px",
                                    lineHeight: "14px",
                                    fontWeight: "500",
                                    textTransform: "uppercase",
                                    whiteSpace: "pre",
                                    backgroundColor: "#ff0000"
                                },
                                tone: "dark",
                                events: {
                                    onclick: function() {
                                        Dialog.show({
                                            body: [
                                                m(".pe-dialog-pane__title", "Hapus seksi"),
                                                m("div", "Apakah Anda yakin akan menghapus seksi ini?")
                                            ],
                                            footerButtons: [
                                                m(Button, {
                                                    label: "Ya",
                                                    events: {
                                                        onclick: function() {
                                                            m.route.set("/user/questionnaires/" + Section.current.questionnaire.id)
                                                        }
                                                    }
                                                }),
                                                m(Button, {
                                                    label: "Tidak",
                                                    events: {
                                                        onclick: Dialog.hide
                                                    }
                                                })
                                            ],
                                            backdrop: true,
                                            didHide: function() {
                                                if (document.body.querySelector(".flex .pe-dialog__holder") != null) {
                                                    document.body.querySelector(".flex").removeChild(
                                                        document.body.querySelector(".flex .pe-dialog__holder")
                                                    )
                                                }
                                                document.body.className = ""
                                            }
                                        })
                                    }
                                }
                            })
                        ]
                    }
                }
            ]
        }))
    }
}

export const editSection = {
    oninit: function() {
        Section.fetchCurrent()
        Section.current.questions = _.sortBy(Section.current.questions, function(o) {
            return o.number
        })
    },
    view: function() {
        return [
            m(nav, {
                title: "Seksi - " + Section.current.title,
                back: "/user/sections/" + Section.current.id
            }),
            m(".flex", m(sCard), m(Dialog), m(Snackbar)),
        ]
    }
}
