"use client";

import { Box, Button, DialogActions, DialogContent, Tab, Tabs, useMediaQuery } from "@mui/material";
import React, { useState } from "react";
import { useTheme } from "@emotion/react";
import useRequest from "@/lib/hooks/useRequest";
import { object, string } from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import moment from "jalali-moment";
import { CREATE_AZMAYESH, UPDATE_AZMAYESH } from "@/core/utils/routes";
import StyledForm from "@/core/components/StyledForm";
import TravelExploreIcon from "@mui/icons-material/TravelExplore";
import TextSnippetIcon from "@mui/icons-material/TextSnippet";
import ExitToAppIcon from "@mui/icons-material/ExitToApp";
import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight";
import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft";
import BeenhereIcon from "@mui/icons-material/Beenhere";
import CandUMapBox from "./CandUMapBox";
import CandUCreateTimeLine from "./CandUTimeLine";
import CandUGeneralInfo from "./CandUGeneralInfo";

function TabPanel(props) {
    const { children, value, index } = props;

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

const validationSchema = object({
    azmayesh_type_id: string().required("نوع آزمایش را مشخص کنید!"),
    province_id: string().required("استان را وارد کنید!"),
    contract_subitem_id: string().required("کد یکتا پروژه را وارد کنید!"),
    project_name: string().required("عنوان پروژه را وارد کنید!"),
    employer: string().required("کارفرما را وارد کنید!"),
    consultant: string().required("مشاور را وارد کنید!"),
    contractor: string().required("پیمانکار را وارد کنید!"),
    applicant: string().required("متقاضی را وارد کنید!"),
    work_number: string().required("شماره کار را وارد کنید!"),
    request_number: string().required("شماره درخواست را وارد کنید!"),
    request_date: string().required("تاریخ درخواست را وارد کنید!"),
    report_date: string().required("تاریخ گزارش را وارد کنید!"),
});

const CandUAzmayesh = ({ setOpen, mutate, updateInfo, rowId }) => {
    const theme = useTheme();
    const requestServer = useRequest({ auth: true });
    const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
    const [tabState, setTabState] = useState(0);
    const [mapBoxData, setMapBoxData] = useState(updateInfo ? { lat: updateInfo.lat, lng: updateInfo.lng } : null);

    const handleClose = () => {
        setOpen(false);
    };

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

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

    const defaultValues = {
        azmayesh_type_id: updateInfo ? updateInfo.azmayesh_type_id : "",
        azmayesh_type_name: updateInfo ? updateInfo.azmayesh_type_name : "",
        province_id: updateInfo ? updateInfo.province_id : "",
        province_name: updateInfo ? updateInfo.province_name : "",
        contract_subitem_id: updateInfo ? updateInfo.contract_subitem_id : "",
        project_name: updateInfo ? updateInfo.project_name : "",
        employer: updateInfo ? updateInfo.employer : "",
        consultant: updateInfo ? updateInfo.consultant : "",
        contractor: updateInfo ? updateInfo.contractor : "",
        applicant: updateInfo ? updateInfo.applicant : "",
        work_number: updateInfo ? updateInfo.work_number : "",
        request_number: updateInfo ? updateInfo.request_number : "",
        request_date: updateInfo ? moment(updateInfo.request_date, "YYYY-MM-DD").toDate() : "",
        report_date: updateInfo ? moment(updateInfo.report_date, "YYYY-MM-DD").toDate() : "",
    };

    const {
        control,
        register,
        handleSubmit,
        setValue,
        formState: { isSubmitting, errors, touchedFields },
    } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "onBlur" });

    const onSubmit = async (data) => {
        const formData = new FormData();
        formData.append("lat", mapBoxData.lat);
        formData.append("lng", mapBoxData.lng);
        formData.append("azmayesh_type_id", data.azmayesh_type_id);
        formData.append("azmayesh_type_name", data.azmayesh_type_name);
        formData.append("province_id", data.province_id);
        formData.append("province_name", data.province_name);
        formData.append("contract_subitem_id", data.contract_subitem_id);
        formData.append("project_name", data.project_name);
        formData.append("employer", data.employer);
        formData.append("consultant", data.consultant);
        formData.append("contractor", data.contractor);
        formData.append("applicant", data.applicant);
        formData.append("work_number", data.work_number);
        formData.append("request_number", data.request_number);
        formData.append("request_date", moment(new Date(data.request_date)).format("YYYY-MM-DD"));
        formData.append("report_date", moment(new Date(data.report_date)).format("YYYY-MM-DD"));

        try {
            const url = updateInfo ? `${UPDATE_AZMAYESH}/${rowId}` : CREATE_AZMAYESH;
            await requestServer(url, "post", {
                data: formData,
            });
            mutate();
            handleClose();
        } catch (error) {}
    };

    return (
        <StyledForm onSubmit={handleSubmit(onSubmit)}>
            <Tabs
                allowScrollButtonsMobile
                value={tabState}
                onChange={handleChangeTab}
                variant={`${isMobile ? "scrollable" : "fullWidth"}`}
                sx={{
                    display: "flex",
                    justifyContent: "space-around",
                    width: "100%",
                    backgroundColor: "#efefef",
                }}
            >
                <Tab icon={<TravelExploreIcon />} label="انتخاب محل آزمایش"></Tab>
                <Tab disabled={!mapBoxData} icon={<TextSnippetIcon />} label="مشخصات آزمایش"></Tab>
            </Tabs>
            <DialogContent dividers sx={{ display: "flex" }}>
                <Box sx={{ flex: 1 }}>
                    <TabPanel value={tabState} index={0}>
                        <CandUMapBox mapBoxData={mapBoxData} setMapBoxData={setMapBoxData} />
                    </TabPanel>
                    <TabPanel value={tabState} index={1}>
                        <CandUGeneralInfo control={control} register={register} setValue={setValue} errors={errors} />
                    </TabPanel>
                </Box>
                {!isMobile && (
                    <Box sx={{ display: "flex", alignItems: "center" }}>
                        <CandUCreateTimeLine tabState={tabState} />
                    </Box>
                )}
            </DialogContent>
            <DialogActions sx={{ alignItems: "center", justifyContent: "center" }}>
                <Button
                    onClick={handlePrev}
                    variant="outlined"
                    color="error"
                    size="large"
                    startIcon={tabState === 0 ? <ExitToAppIcon /> : <KeyboardDoubleArrowRightIcon />}
                >
                    {tabState === 0 ? "بستن" : "مرحله قبل"}
                </Button>
                {tabState === 0 ? (
                    <Button
                        onClick={(event) => {
                            event.preventDefault();
                            setTabState(tabState + 1);
                        }}
                        variant="contained"
                        size="large"
                        disabled={!mapBoxData}
                        endIcon={<KeyboardDoubleArrowLeftIcon />}
                    >
                        مرحله بعد
                    </Button>
                ) : (
                    <Button
                        variant="contained"
                        size="large"
                        disabled={isSubmitting}
                        type={"submit"}
                        endIcon={<BeenhereIcon />}
                    >
                        {updateInfo
                            ? isSubmitting
                                ? "در حال ویرایش آزمایش"
                                : "ویرایش آزمایش"
                            : isSubmitting
                              ? "در حال ثبت آزمایش"
                              : "ثبت آزمایش"}
                    </Button>
                )}
            </DialogActions>
        </StyledForm>
    );
};
export default CandUAzmayesh;
