import React, { useState, useMemo } from "react";
import { Button, Form, Select } from "antd";
import { Inertia } from "@inertiajs/inertia";
import { useTranslation } from "react-i18next";
import { InertiaLink, usePage } from "@inertiajs/inertia-react";
import { getParsedQueryString } from "../../../../../Utils/getParsedQueryString";
import clsx from "clsx";
import Layout from "../../../../../Layout/Index";
import InputSearch from "../../../../../Components/Common/InputSearch";
import BackButton from "./../../../../../Components/Common/BackButton";
import DatatableComponent from "./../../../../../Components/Common/DatatableComponent";
import ExportDropdown from "./../../../../../Components/Common/ExportDropdown";
import StudentSemesterFilter from "./../../../../../Components/Common/StudentSemesterFilter";
import FilterListIcon from "@material-ui/icons/FilterList";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ClearFilterButton from "./../../../../../Components/Common/ClearFilterButton";

const Details = ({ students = [] }) => {
    const [isFilterMenuVisible, setIsFilterMenuVisible] = useState(false);
    const { t } = useTranslation();
    const { accountId, assetsAccountsCategories = [] } = usePage().props;
    const columns = [
        {
            name: "S.no",
            selector: (row, index) => index + 1,
            width: "100px",
        },
        {
            name: "College",
            selector: (row) => row.college,
        },
        {
            name: "Student ID",
            selector: (row) => row.username,
        },
        {
            name: t("Student Name"),
            selector: (row) => (
                <InertiaLink
                    href={`/accounting/assets/${accountId}/category/${assetsAccountsCategories?.id}/${row.college}/student/${row.id
                        }`}
                >
                    <u className="color-secondary cursor-pointer fw-500">{row.full_name}</u>
                </InertiaLink>
            ),
            width: "700px",
        },
        {
            name: t("Current Semester"),
            selector: (row) => <p className={"mb-0"}>{row.semester}</p>,
            width: "166px",
        },
        {
            name: t("Debit"),
            selector: (row) => <p className={"mb-0"}>{row.student_total_debit_amount} SAR</p>,

        },
        {
            name: t("Credit"),
            selector: (row) => <p className={"mb-0"}>{row.student_total_credit_amount} SAR</p>,

        },
    ];

    const handleCancelFilter = () => setIsFilterMenuVisible(false);

    /**
     * @description Toggle the filter menu
     */
    const toggleFilterMenu = () => {
        return setIsFilterMenuVisible(!isFilterMenuVisible);
    };

    const total_debit = students.reduce(
        (total, student) => total + student.student_total_debit_amount,
        0
    );
    const total_credit = students.reduce(
        (total, student) => total + student.student_total_credit_amount,
        0
    );

    const balance = total_debit - total_credit;

    return (
        <Layout currentPage={12}>
            <div className="account-details-wrapper ml-20">
                <BackButton url={route("accounting.asset.show", [accountId])} />

                <div className="account-details-wrapper__header">
                    <div className="d-flex justify-content-between mb-30">
                        <div>
                            <h2 className="f-18 fw-600 mb-0">{t("Students")}</h2>
                            <p className="f-12 fw-300 color-silver mb-0">
                                {t("Account code")}: {assetsAccountsCategories.code}
                            </p>
                        </div>
                        <p className="f-12 fw-300 color-silver">{t("Asset account")}</p>
                    </div>

                    <div className="d-flex justify-content-between align-items-center">
                        <div className="d-flex align-items center">
                            <div>
                                <h3 className="f-12 fw-300 color-silver mb-0">{t("Balance")}</h3>
                                <p className="f-16 mb-0">{balance.toFixed(2)} SAR</p>
                            </div>
                            <div className="vertical-divider" />

                            <div>
                                <h3 className="f-12 fw-300 color-silver mb-0">
                                    {t("Amount debit")}
                                </h3>
                                <p className="f-16 mb-0">{total_debit.toFixed(2)} SAR</p>
                            </div>
                            <div className="vertical-divider" />

                            <div>
                                <h3 className="f-12 fw-300 color-silver mb-0">
                                    {t("Amount credit")}
                                </h3>
                                <p className="f-16 mb-0">{total_credit.toFixed(2)} SAR</p>
                            </div>
                        </div>
                    </div>
                </div>

                {
                    // content
                }
                <div className="primary-card">
                    <div className="primary-table">
                        <div className="primary-table-header">
                            <h2 className="f-16 fw-500 mb-0 mr-18">{t("Showing all records")}</h2>

                            <div className="d-flex align-items-center ml-1">
                                <ClearFilterButton />
                                <Button
                                    onClick={toggleFilterMenu}
                                    className={clsx("button-default btn-filter", {
                                        "btn-filter-active": isFilterMenuVisible,
                                    })}
                                >
                                    {t("Filter")}
                                    <FilterListIcon className="btn-filter-icon" />
                                </Button>
                                {isFilterMenuVisible && (
                                    <FilterMenu handleCancel={handleCancelFilter} />
                                )}
                                <InertiaLink
                                    href={route("accounting.asset.students-custom-report.index", [accountId, assetsAccountsCategories?.id])}
                                >
                                    <Button className="button-default mr-16">
                                        {t("Custom Report")}
                                    </Button>
                                </InertiaLink>
                                <ExportDropdown />

                                {/* search bar here */}
                                <InputSearch searchOnFocusOut={true} isPreserve={false} />
                            </div>
                        </div>
                        {/* data table  */}
                        <DatatableComponent columns={columns} data={students} />
                    </div>
                </div>
            </div>
        </Layout>
    );
};

export default Details;

const FilterMenu = ({ handleCancel }) => {
    const { colleges = [] } = usePage().props;

    /**
     * @description Handle the filter menu submit
     * @param {object} values
     */
    const { t } = useTranslation();
    const onFinish = (values) => {
        Inertia.get("", values, {
            preserveScroll: true,
            preserveState: false,
            onSuccess: () => {
                handleCancel();
            },
        });
    };
    const initialValues = useMemo(() => {
        return Object.keys(getParsedQueryString()).length > 0 ? getParsedQueryString() : {};
    }, []);
    return (
        <div className="table-filter-menu" style={{ zIndex: 2 }}>
            <Form
                scrollToFirstError
                layout="vertical"
                initialValues={initialValues}
                onFinish={onFinish}
            >
                <div className="row">
                    <div className="col-6">
                        <Form.Item label={t("College")} name="college">
                            <Select
                                suffixIcon={<ExpandMoreIcon />}
                                className="primary-select select-icon-sm w-100"
                            >
                                <Option value={"all"}>{t("All")}</Option>
                                {colleges.map((college) => (
                                    <Option value={college} key={college}>
                                        {college}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </div>
                    <div className="col-6">
                        <StudentSemesterFilter />
                    </div>
                </div>

                {/* menu actions */}
                <div className="d-flex justify-content-end mt-20">
                    <Button onClick={handleCancel} className="button-default-bordered mr-15">
                        {t("Cancel")}
                    </Button>
                    <Button htmlType="submit" className="button-primary">
                        {t("Apply")}
                    </Button>
                </div>
            </Form>
        </div>
    );
};
