import React, { useCallback, useState } from "react";
import { Page } from "@/pages/base";
import { Button, Card, CardContent, CardHeader, Checkbox, Container, Typography } from "@material-ui/core";
import { Async } from "@/components/async";
import { useTranslation } from "react-i18next";
import { useAsync } from "@/hooks";
import api from "@/management/api";
import { useSpacing } from "@/styles";
import { EditionManagement, EditionManagementProps } from "./manage";
import { ReportFieldDefinition } from "@/data/report";
import { FieldPreview } from "@/management/report/fields/list";
import { toggleValueInArray } from "@/management/edition/form";
import { Actions } from "@/components";
import { useHistory } from "react-router-dom";

const title = "edition.settings.schema";

export function EditionReportSchema({ edition }: EditionManagementProps) {
    const { t } = useTranslation("management");
    const spacing = useSpacing(2);
    const history = useHistory();

    const fields = useAsync<ReportFieldDefinition[]>(useCallback(() => api.field.all(), []))
    const [selected, setSelected] = useState<ReportFieldDefinition[]>(edition.schema);

    const isSelected = (field: ReportFieldDefinition) => selected.findIndex(f => f.id === field.id) !== -1;
    const handleCheckboxClick = (field: ReportFieldDefinition) => () => {
        setSelected(toggleValueInArray(selected, field, (a, b) => a.id === b.id));
    }

    const handleSave = async () => {
        await api.edition.save({ ...edition, schema: selected });
        history.push("management:edition_manage", { edition: edition.id as string })
    }

    return <Page>
        <Page.Header maxWidth="md">
            <EditionManagement.Breadcrumbs>
                <Typography color="textPrimary">{ t(title) }</Typography>
            </EditionManagement.Breadcrumbs>
            <Page.Title>{ t(title) }</Page.Title>
        </Page.Header>
        <Container maxWidth="md" className={ spacing.vertical }>
            <Async async={ fields }>
                { fields => <>
                    { fields.map(field => <div style={{ display: "flex", alignItems: "start" }}>
                        <Checkbox onClick={ handleCheckboxClick(field) } checked={ isSelected(field) }/>
                        <Card style={{ flex: "1 1 auto" }}>
                            <CardHeader subheader={ field.label.pl } />
                            <CardContent><FieldPreview field={ field }/></CardContent>
                        </Card>
                    </div>) }
                    <Actions>
                        <Button variant="contained" color="primary" onClick={ handleSave }>{ t("save") }</Button>
                    </Actions>
                </> }
            </Async>
        </Container>
    </Page>;
}
