<script>
    import { onMount } from "svelte";

    import { Row, Col, Button, Icon, ButtonToolbar, FormGroup, Label, Input, ButtonGroup, Tooltip } from "sveltestrap";

    import DragDrop from "@/components/DragDrop.svelte";

    import { storeMdjs } from "@/stores/mdjs.store";
    import { storeFiles, storeUrlFiles, storeDeletedFiles, storeNewFiles } from "@/stores/files.store";
    import { user } from "@/stores/app.store";
    import { XmlConverter } from "@/libs/xml-converter/xml-converter";

    import LabelField from "./elements/LabelField.svelte";
    import InputField from "./elements/InputField.svelte";
    import Image from "../Image.svelte";

    export let field;
    export let type;
    export let roles;
    export let value = {};
    export let id = 0;
    export let onRemoveItem = false;
    export let onSaveItem = false;
    export let onCloneItem = false;
    export let onDuplicateItem = false;
    export let onAddUserContact = false;
    export let error;

    let detailedView = {};

    let individualName = "";
    let positionName = "";
    let organisationName = "";
    let phoneVoices = "";
    let emails = "";
    let deliveryPoints = "";
    let postalCode = "";
    let city = "";
    let logoUrl = "";
    let logoImage = "";
    let logoDescription = "";
    let role = "";

    $: isReady = $storeMdjs;
    $: individualName = getValue(value, "individualName");
    $: positionName = getValue(value, "positionName");
    $: organisationName = getValue(value, "organisationName");
    $: phoneVoices = getValue(value, "phoneVoices");
    $: emails = getValue(value, "emails");
    $: deliveryPoints = getValue(value, "deliveryPoints");
    $: postalCode = getValue(value, "postalCode");
    $: city = getValue(value, "city");
    $: logoUrl = getValue(value, "logoUrl");
    $: logoDescription = getValue(value, "logoDescription");
    $: role = getValue(value, "role");
    $: $storeUrlFiles[type + "-" + id] = Array.isArray(logoUrl) ? logoUrl[0] : logoUrl;

    function getValue(item, fieldName) {
        return converter.getValue(item, fieldName)[0] || "";
    }

    const converter = new XmlConverter();

    onMount(() => {});

    function onSave(fieldName, fieldValue, id) {
        value = converter.setValue(value, fieldName, [fieldValue]);
        onSaveItem(id, value);
    }

    function onRemove(e) {
        e.preventDefault();
        e.stopPropagation();
        if (onRemoveItem) {
            onRemoveItem(id);
        }
    }

    function onClone(e, id) {
        // console.log("clone");
        e.preventDefault();
        e.stopPropagation();
        onCloneItem(id);
    }
    function onDuplicate(e, id) {
        // console.log("duplicate");
        e.preventDefault();
        e.stopPropagation();
        onDuplicateItem(id);
    }
    function onAddUser(e, id) {
        // console.log("duplicate");
        e.preventDefault();
        e.stopPropagation();
        onAddUserContact(id);
    }
    function onDetails(e, id) {
        e.preventDefault();
        e.stopPropagation();
        detailedView[type + "-" + id] = !detailedView[type + "-" + id];
    }

    function OnDrop(files) {
        if (files[0]) {
            $storeNewFiles[type + "-" + id] = files[0];
            logoUrl = "file:///" + files[0].name;
            onSave("logoUrl", logoUrl);

            var reader = new FileReader();
            reader.onload = function (e) {
                logoImage = e.target.result;
            };
            reader.readAsDataURL(files[0]);
        }
    }

    function onRemoveImage() {
        if (logoImage) {
            logoImage = "";
            $storeDeletedFiles[type + "-" + id] = $storeNewFiles[type + "-" + id].name;
            delete $storeNewFiles[type + "-" + id];
        }
        logoUrl = "";
        onSave("logoUrl", "", id);
    }
</script>

{#if isReady}
    <Row>
        <!-- contacts.role -->
        <Col md="6">
            <InputField
                label={field.role.label}
                type={field.role.type}
                value={role}
                help={field.role.help}
                {error}
                field={field.role.name}
                list={roles}
                {id}
                {onSave}
            />
        </Col>
        <!-- toolbar -->
        <Col md="6">
            <ButtonToolbar class="float-end gap-1">
                <Button
                    id={"button-add-user-" + type + "-" + id}
                    outline
                    color="dark"
                    size="sm"
                    on:click={(e) => {
                        onAddUser(e, id);
                    }}><Icon name="person-plus" /></Button
                >
                <Tooltip target={"button-add-user-" + type + "-" + id} placement="top">Ajouter l'utilisateur connecté comme contact</Tooltip>
                <Button
                    id={"button-clone-" + type + "-" + id}
                    outline
                    color="dark"
                    size="sm"
                    on:click={(e) => {
                        onClone(e, id);
                    }}><Icon name="files" /></Button
                >
                <Tooltip target={"button-clone-" + type + "-" + id} placement="top">Cloner ce contact</Tooltip>
                <Button
                    id={"button-duplicate-" + type + "-" + id}
                    outline
                    color="dark"
                    size="sm"
                    on:click={(e) => {
                        onDuplicate(e, id);
                    }}><Icon name="file-earmark-arrow-down" /></Button
                >
                <Tooltip target={"button-duplicate-" + type + "-" + id} placement="top"
                    >Copier ce contact comme {type == "mdContacts"
                        ? "contact pour les données"
                        : "contact pour les métadonnées"}</Tooltip
                >
                <Button
                    id={"button-remove-" + type + "-" + id}
                    outline
                    color="dark"
                    size="sm"
                    on:click={(e) => {
                        onRemove(e, id);
                    }}><Icon name="dash" /></Button
                >
                <Tooltip target={"button-remove-" + type + "-" + id} placement="top">Supprimer ce contact</Tooltip>
            </ButtonToolbar>
            <!-- <FormGroup inline check class="float-end px-1">
                <Input
                    type="switch"
                    id={"detailed-view-" + type + "-" + id}
                    name={"detailed-view-" + type + "-" + id}
                    label=""
                    class=""
                    inline
                    checked={detailedView[type + "-" + id] == true}
                    value={false}
                    on:change={(e) => {
                        onDetails(e, id);
                    }}
                />
            </FormGroup>
            <Label for={"detailed-view-" + type + "-" + id} check class="float-end">Détails:</Label> -->
            <ButtonGroup size="sm" class="float-end me-3">
                <Button
                    id={"detailed-view-" + type + "-" + id}
                    name={"detailed-view-" + type + "-" + id}
                    outline={!detailedView[type + "-" + id]}
                    color={detailedView[type + "-" + id] ? "primary" : "secondary"}
                    class=""
                    on:click={(e) => {
                        onDetails(e, id);
                    }}
                >
                    <small>
                        {#if detailedView[type + "-" + id]}
                            <Icon name="check" />
                        {/if}
                        Détails
                    </small>
                </Button>
                <Tooltip target={"detailed-view-" + type + "-" + id} placement="top"
                    >{detailedView[type + "-" + id] ? "Cacher" : "Afficher"} les détails du contact</Tooltip
                >
            </ButtonGroup>
        </Col>
    </Row>
    <Row>
        <Col md="6">
            <!-- DONE: contacts.organisationName -->
            <InputField
                label={field.organisationName.label}
                type={field.organisationName.type}
                value={organisationName}
                help={field.organisationName.help}
                {error}
                field={field.organisationName.name}
                {id}
                {onSave}
            />
        </Col>
        <Col md="6">
            <!-- DONE: contacts.email -->
            <InputField
                label={field.emails.label}
                type={field.emails.type}
                value={emails}
                help={field.emails.help}
                {error}
                field={field.emails.name}
                {id}
                {onSave}
            />
        </Col>
    </Row>
    <Row>
        <!-- DONE: logo -->
        <Col md="12">
            <LabelField label={field.logo.label} help={field.logo.help} field={field.logo.name} />
        </Col>
    </Row>
    <Row>
        <Col md="10">
            {#if $user.editor}
                <DragDrop
                    {OnDrop}
                    autoUpload={false}
                    multiple={true}
                    accept="image/*"
                    text="Déposez un logo (*.jpg ou *.png) - Taille maximale: 1 Mo"
                />
            {/if}
            <InputField
                type={field.logoUrl.type}
                value={logoUrl}
                help={field.logoUrl.help}
                field={field.logoUrl.name}
                placeholder={field.logoUrl.placeholder}
                small={true}
                disabled={logoImage}
                css="mt-2"
                {id}
                {onSave}
            />
        </Col>
        <Col md="4" class="d-none">
            <InputField
                hidden={true}
                label={field.logoDescription.label}
                type={field.logoDescription.type}
                value={"Logo " + id}
                help={field.logoDescription.help}
                field={field.logoDescription.name}
                {id}
                {onSave}
            />
        </Col>
        <Col md="2" class="mx-auto">
            {#if logoImage && $user.editor}
                <Image src={logoImage} alt={"Logo " + id} {onRemoveImage} displayButton={logoImage} />
            {:else}
                <Image src={logoUrl} alt={"Logo " + id} {onRemoveImage} displayButton={logoUrl} />
            {/if}
        </Col>
    </Row>

    {#if detailedView[type + "-" + id]}
        <Row>
            <Col md="6">
                <!-- DONE: contacts.individualName -->
                <InputField
                    label={field.individualName.label}
                    type={field.individualName.type}
                    value={individualName}
                    help={field.individualName.help}
                    field={field.individualName.name}
                    {id}
                    {onSave}
                />
                <!-- DONE: contacts.positionName -->
                <InputField
                    label={field.positionName.label}
                    type={field.positionName.type}
                    value={positionName}
                    help={field.positionName.help}
                    field={field.positionName.name}
                    {id}
                    {onSave}
                />
                <!-- DONE: contacts.phoneVoice -->
                <InputField
                    label={field.phoneVoices.label}
                    type={field.phoneVoices.type}
                    value={phoneVoices}
                    help={field.phoneVoices.help}
                    field={field.phoneVoices.name}
                    {id}
                    {onSave}
                />
            </Col>
            <Col md="6">
                <!-- DONE: contacts.deliveryPoint -->
                <InputField
                    label={field.deliveryPoints.label}
                    type={field.deliveryPoints.type}
                    value={deliveryPoints}
                    help={field.deliveryPoints.help}
                    field={field.deliveryPoints.name}
                    rows={3}
                    {id}
                    {onSave}
                />
                <Row>
                    <!-- DONE: contacts.postalCode -->
                    <Col md="4">
                        <InputField
                            label={field.postalCode.label}
                            type={field.postalCode.type}
                            value={postalCode}
                            help={field.postalCode.help}
                            field={field.postalCode.name}
                            {id}
                            {onSave}
                        />
                    </Col>
                    <!-- DONE: contacts.city -->
                    <Col md="8">
                        <InputField
                            label={field.city.label}
                            type={field.city.type}
                            value={city}
                            help={field.city.help}
                            field={field.city.name}
                            {id}
                            {onSave}
                        />
                    </Col>
                </Row>
            </Col>
        </Row>
    {/if}
{/if}

<style>
</style>
