import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
import FileCopyIcon from "@mui/icons-material/FileCopy";
import ExitToAppIcon from "@mui/icons-material/ExitToApp";
import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight";
import BeenhereIcon from "@mui/icons-material/Beenhere";
import StyledForm from "@/core/components/StyledForm";
import React, { useState } from "react";
import SearchItemInfo from "./SearchItemInfo";
import moment from "jalali-moment";
import GetItemInfo from "./RowActions/GetItemInfo";

function TabPanel(props) {
    const { children, value, index } = props;
    return (
        <div role="tabpanel" hidden={value !== index}>
            {value === index && <Box>{children}</Box>}
        </div>
    );
}

const defaultValues = {
    start_date: moment(new Date()).format("YYYY-MM-DD"),
    end_date: moment(new Date()).format("YYYY-MM-DD"),
    item_id: "",
    road_patrol_id: "",
};

const defaultFilter = [
    { value: `${defaultValues.item_id}`, datatype: "text", id: "item_id", fn: "equals" },
    { value: `${defaultValues.road_patrol_id}`, datatype: "text", id: "road_patrol_id", fn: "equals" },
    { value: `${defaultValues.start_date}`, datatype: "date", id: "roadPatrol.start_time", fn: "equals" },
    { value: `${defaultValues.end_date}`, datatype: "date", id: "roadPatrol.end_time", fn: "equals" },
];

const GashtCreateContent = ({ mutate, setOpen, tabState, setTabState }) => {
    const [itemInfo, setItemInfo] = useState(null);
    const [submitCompleteForm, setSubmitCompleteForm] = useState(false);
    const [specialFilter, setSpecialFilter] = useState(defaultFilter);

    const validationSchema = yup
        .object()
        .shape({
            start_date: yup.string().nullable(),
            end_date: yup.string().nullable(),
            item_id: yup.string().nullable(),
            road_patrol_id: yup.string().nullable(),
        })
        .test("at-least-one", "وارد کردن مقدار ضروریست!!!", (values) => {
            return (!!values.start_date && !!values.end_date) || !!values.item_id || !!values.road_patrol_id;
        });

    const handleChangeTab = (event, newValue) => {
        setTabState(newValue);
    };
    const handleClose = () => {
        setOpen(false);
    };

    const handlePrev = () => {
        if (tabState === 0) {
            handleClose();
        } else {
            setTabState(tabState - 1);
        }
    };

    const {
        control,
        getValues,
        watch,
        register,
        handleSubmit,
        setValue,
        formState: { errors, isSubmitting },
    } = useForm({
        defaultValues,
        resolver: yupResolver(validationSchema),
        mode: "onBlur",
    });
    const onSearchSubmit = async (data) => {
        setSpecialFilter([
            { value: `${data.item_id}`, datatype: "text", id: "item_id", fn: "equals" },
            { value: `${data.road_patrol_id}`, datatype: "text", id: "road_patrol_id", fn: "equals" },
            { value: `${data.start_date}`, datatype: "date", id: "roadPatrol.start_time", fn: "equals" },
            { value: `${data.end_date}`, datatype: "date", id: "roadPatrol.end_time", fn: "equals" },
        ]);
    };
    return (
        <>
            <Tabs
                allowScrollButtonsMobile
                value={tabState}
                onChange={handleChangeTab}
                variant="fullWidth"
                sx={{
                    display: "flex",
                    justifyContent: "center",
                    width: "100%",
                    backgroundColor: "#efefef",
                }}
            >
                <Tab icon={<InsertDriveFileIcon />} label="انتخاب مورد مشاهده شده" />
                <Tab disabled={tabState === 0} icon={<FileCopyIcon />} label="اطلاعات مورد اقدام شده" />
            </Tabs>
            <DialogContent dividers sx={{ overflowY: "auto", maxHeight: "70vh" }}>
                <Box sx={{ flex: 1 }}>
                    <TabPanel value={tabState} index={0}>
                        <StyledForm onSubmit={handleSubmit(onSearchSubmit)}>
                            <SearchItemInfo
                                isSubmitting={isSubmitting}
                                specialFilter={specialFilter}
                                watch={watch}
                                errors={errors}
                                setValue={setValue}
                                register={register}
                                setTabState={setTabState}
                                setItemInfo={setItemInfo}
                            />
                        </StyledForm>
                    </TabPanel>
                    <TabPanel value={tabState} index={1}>
                        <GetItemInfo
                            mutate={mutate}
                            setOpen={setOpen}
                            setSubmitCompleteForm={setSubmitCompleteForm}
                            itemInfo={itemInfo}
                        />
                    </TabPanel>
                </Box>
            </DialogContent>
            <DialogActions sx={{ alignItems: "center", justifyContent: "center" }}>
                <Button
                    onClick={handlePrev}
                    variant="outlined"
                    color="secondary"
                    size="large"
                    startIcon={tabState === 0 ? <ExitToAppIcon /> : <KeyboardDoubleArrowRightIcon />}
                >
                    {tabState === 0 ? "بستن" : "مرحله قبل"}
                </Button>
                {tabState === 1 && (
                    <Button
                        form={"CompleteItemForm"}
                        type={"submit"}
                        variant="contained"
                        color="primary"
                        size="large"
                        disabled={submitCompleteForm}
                        endIcon={<BeenhereIcon />}
                    >
                        {submitCompleteForm ? "درحال ثبت فعالیت..." : "ثبت فعالیت"}
                    </Button>
                )}
            </DialogActions>
        </>
    );
};
export default GashtCreateContent;
