import { CardContainer } from "@components/CardContainer";
import { IconApp } from "@components/IconApp";
import { InputApp } from "@components/InputApp";
import { useForm } from "@hooks/useForm";
import {
    clearReport,
    startShowBreakdownByPeriod,
} from "@redux/slices/operators/BreakdownByPeriod";
import { startShow } from "@redux/slices/users/PaymentScreen";
import { Empty } from "antd";
import React, { useEffect, useMemo } from "react";
import { Button, Col, Row, Tab, Tabs } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import { BreakdownByPeriodAdvancedTuition } from "./BreakdownByPeriodAdvancedTuition";
import { BreakdownByPeriodBudget } from "./BreakdownByPeriodBudget";
import { BreakdownByPeriodConcentrated } from "./BreakdownByPeriodConcentrated";
import { BreakdownByPeriodIncomeByDay } from "./BreakdownByPeriodIncomeByDay";
import { BreakdownByPeriodDebts } from "./BreakdownByPeriodDebts";
import { BreakdownByPeriodGeneral } from "./BreakdownByPeriodGeneral";

const defaultValues = {
    start_date: "",
    end_date: "",
    errors: {},
};

const LOCAL_STORAGE_NAME = "breakdownByPeriodFilters";

export default function BreakdownByPeriodScreen() {
    const dispatch = useDispatch();

    const { report } = useSelector((state) => state.breakdownByPeriod);

    const { values, handleInputChange, setFormValues } = useForm(defaultValues);
    const { start_date, end_date, errors } = values;

    const canStartSearch = useMemo(() => {
        return !!start_date && !!end_date;
    }, [start_date, end_date]);

    const advancedTuitionData = useMemo(() => {
        return (
            report?.advanced_tuition || report?.debts?.advanced_tuition || null
        );
    }, [report?.advanced_tuition, report?.debts?.advanced_tuition]);

    const hasReport = useMemo(() => {
        return Boolean(
            report?.concentrated?.rows?.length ||
            report?.debts?.rows?.length ||
            advancedTuitionData?.rows?.length,
        );
    }, [
        report?.concentrated?.rows?.length,
        report?.debts?.rows?.length,
        advancedTuitionData?.rows?.length,
    ]);

    useEffect(() => {
        const localStorageData = JSON.parse(
            localStorage.getItem(LOCAL_STORAGE_NAME),
        );

        if (!localStorageData) {
            return;
        }

        setFormValues({
            start_date:
                localStorageData?.start_date ?? defaultValues.start_date,
            end_date: localStorageData?.end_date ?? defaultValues.end_date,
        });
    }, []);

    useEffect(() => {
        localStorage.setItem(
            LOCAL_STORAGE_NAME,
            JSON.stringify({
                start_date,
                end_date,
            }),
        );
    }, [start_date, end_date]);

    const handleSearch = () => {
        dispatch(
            startShowBreakdownByPeriod({
                start_date,
                end_date,
            }),
        );
    };

    const handleClear = () => {
        dispatch(clearReport());
    };

    const handleExportExcel = () => {
        dispatch(
            startShow({
                from: start_date,
                to: end_date,
                is_export: 1,
                concepts: true,
            }),
        );
    };

    return (
        <CardContainer title="Desglose por periodo">
            <div
                className="rounded-3 border shadow-sm p-3 mb-3"
                style={{
                    background:
                        "linear-gradient(180deg, #f8f9fb 0%, #f2f4f8 100%)",
                    borderColor: "#d7dee8",
                }}
            >
                <Row className="g-2 align-items-center">
                    <Col xs={12} lg={3}>
                        <h5 className="m-0 fw-bold text-dark-blue-1">
                            Desglose por periodo
                        </h5>
                    </Col>

                    <Col xs={12} sm={6} lg={2}>

                        <InputApp
                            type="date"
                            title="Desde"
                            name="start_date"
                            value={start_date}
                            onChange={handleInputChange}
                            errorText={
                                errors.start_date && errors.start_date[0]
                            }
                        />
                    </Col>

                    <Col xs={12} sm={6} lg={2}>
                        <InputApp
                            type="date"
                            title="Hasta"
                            name="end_date"
                            value={end_date}
                            onChange={handleInputChange}
                            errorText={errors.end_date && errors.end_date[0]}
                        />
                    </Col>

                    <Col xs={12} lg={5}>
                        <div className="d-flex flex-wrap gap-2 justify-content-lg-end mt-0 mt-lg-4">
                            <Button
                                className="btn-app-green-with-hover"
                                onClick={handleExportExcel}
                            >
                                <IconApp iconClassName="fas fa-chart-simple me-2" />
                                Excel desglose
                            </Button>

                            <Button
                                onClick={handleSearch} disabled={!canStartSearch}
                            >
                                Buscar
                                <IconApp iconClassName="fas fa-search ms-2" />
                            </Button>

                            <Button variant="secondary" onClick={handleClear}>
                                Limpiar
                            </Button>
                        </div>
                    </Col>
                </Row>
            </div>

            {!hasReport ? (
                <div className="pt-3">
                    <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        className="text-size-15"
                        description="Seleccione una fecha de inicio y una fecha de fin para habilitar la búsqueda."
                    />
                </div>
            ) : (
                <div className="mt-4">
                    <div className="px-2 px-md-3">
                        <Tabs
                            defaultActiveKey="general"
                            id="breakdown-by-period-tabs"
                            className="custom-tabs-2 nav-fill mb-3"
                        >
                            <Tab
                                eventKey="general"
                                title={<h6 className="m-0">General</h6>}
                            >
                                <BreakdownByPeriodGeneral
                                    concentratedData={
                                        report?.concentrated || null
                                    }
                                    debtsData={report?.debts || null}
                                    advancedTuitionData={
                                        advancedTuitionData || null
                                    }
                                />
                            </Tab>

                            <Tab
                                eventKey="ingresos"
                                title={<h6 className="m-0">Ingresos</h6>}
                            >
                                <div className="mt-3">
                                    {report?.concentrated?.rows?.length ? (
                                        <>
                                            <BreakdownByPeriodConcentrated
                                                sectionData={report.concentrated}
                                                paymentsByCycleData={
                                                    report.payments_by_cycle
                                                }
                                            />
                                            {report?.income_by_day?.rows
                                                ?.length ? (
                                                <BreakdownByPeriodIncomeByDay
                                                    sectionData={
                                                        report.income_by_day
                                                    }
                                                />
                                            ) : null}
                                        </>
                                    ) : (
                                        <Empty
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                            className="text-size-15 mt-3"
                                            description="No hay datos de ingresos para el periodo seleccionado."
                                        />
                                    )}
                                </div>
                            </Tab>

                            <Tab
                                eventKey="presupuesto"
                                title={<h6 className="m-0">Presupuesto</h6>}
                            >
                                <div className="mt-3">
                                    {report?.budget?.length ? (
                                        <BreakdownByPeriodBudget
                                            sectionData={report.budget}
                                        />
                                    ) : (
                                        <Empty
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                            className="text-size-15 mt-3"
                                            description="No hay datos de presupuesto para el periodo seleccionado."
                                        />
                                    )}
                                </div>
                            </Tab>

                            <Tab
                                eventKey="adelantados"
                                title={
                                    <h6 className="m-0">Pagos adelantados</h6>
                                }
                            >
                                <div className="mt-3">
                                    {advancedTuitionData?.rows?.length ? (
                                        <BreakdownByPeriodAdvancedTuition
                                            sectionData={advancedTuitionData}
                                        />
                                    ) : (
                                        <Empty
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                            className="text-size-15 mt-3"
                                            description="No hay datos de pagos adelantados para el periodo seleccionado."
                                        />
                                    )}
                                </div>
                            </Tab>

                            <Tab
                                eventKey="adeudos"
                                title={<h6 className="m-0">Adeudos</h6>}
                            >
                                <div className="mt-3">
                                    {report?.debts?.rows?.length ? (
                                        <BreakdownByPeriodDebts
                                            sectionData={report.debts}
                                        />
                                    ) : (
                                        <Empty
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                            className="text-size-15 mt-3"
                                            description="No hay datos de adeudos para el periodo seleccionado."
                                        />
                                    )}
                                </div>
                            </Tab>
                        </Tabs>
                    </div>
                </div>
            )}
        </CardContainer>
    );
}
