import StyledForm from "@/core/components/StyledForm";
import {
    GET_CITIES_LIST,
    GET_PROVINCES_LIST,
    GET_STATIONS_LIST,
    UPDATE_MACHINE_STATUS_AND_LOCATION,
} from "@/core/utils/routes";
import useRequest from "@/lib/hooks/useRequest";
import { yupResolver } from "@hookform/resolvers/yup";
import { Beenhere, ExitToApp } from "@mui/icons-material";
import {
    Button,
    CircularProgress,
    DialogActions,
    DialogContent,
    DialogTitle,
    FormControl,
    InputLabel,
    MenuItem,
    Select,
    Stack,
} from "@mui/material";
import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog";
import { useEffect, useState } from "react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { number, object } from "yup";

const statusOptions = [
    { value: 1, label: "آماده" },
    { value: 2, label: "رزرو" },
    { value: 3, label: "در ماموریت" },
    { value: 4, label: "خارج از رده" },
    { value: 5, label: "در تعمیر" },
    { value: 6, label: "فروخته شده" },
    { value: 7, label: "نیاز به تعمیر" },
];

const validationSchema = object({
    status: number().required("انتخاب وضعیت الزامی است"),
    province_id: number().required("انتخاب استان الزامی است"),
    city_id: number().required("انتخاب شهر الزامی است"),
    station_id: number().required("انتخاب راهداری الزامی است"),
});

const EditFormContent = ({ row, rowId, mutate, setOpen }) => {
    const requestServer = useRequest();

    const [provinces, setProvinces] = useState([]);
    const [cities, setCities] = useState([]);
    const [stations, setStations] = useState([]);

    const [loadingProvinces, setLoadingProvinces] = useState(false);
    const [loadingCities, setLoadingCities] = useState(false);
    const [loadingStations, setLoadingStations] = useState(false);

    const {
        control,
        handleSubmit,
        setValue,
        formState: { isSubmitting },
    } = useForm({
        defaultValues: {
            status: row.original.status,
            province_id: row.original.province_id,
            city_id: row.original.city_id,
            station_id: row.original.station_id,
        },
        resolver: yupResolver(validationSchema),
        mode: "all",
    });

    const provinceId = useWatch({
        control,
        name: "province_id",
    });

    const cityId = useWatch({
        control,
        name: "city_id",
    });

    const loadProvinces = async () => {
        try {
            setLoadingProvinces(true);
            const response = await requestServer(GET_PROVINCES_LIST, "get");
            setProvinces(response.data?.data || []);
        } finally {
            setLoadingProvinces(false);
        }
    };

    const loadCities = async (provinceId) => {
        if (!provinceId) return;

        try {
            setLoadingCities(true);
            const response = await requestServer(`${GET_CITIES_LIST}?province_id=${provinceId}`, "get");
            setCities(response.data?.data || []);
        } finally {
            setLoadingCities(false);
        }
    };

    const loadStations = async (cityId) => {
        if (!cityId) return;

        try {
            setLoadingStations(true);
            const response = await requestServer(`${GET_STATIONS_LIST}/search_by_city?city_id=${cityId}`, "get");
            setStations(response.data?.data || []);
        } finally {
            setLoadingStations(false);
        }
    };

    useEffect(() => {
        loadProvinces();
    }, []);

    /**
     * Initial edit mode loading
     */
    useEffect(() => {
        if (row.original.province_id) {
            loadCities(row.original.province_id);
        }

        if (row.original.city_id) {
            loadStations(row.original.city_id);
        }
    }, []);

    useEffect(() => {
        if (!provinceId) return;

        loadCities(provinceId);

        if (provinceId !== row.original.province_id) {
            setValue("city_id", "");
            setValue("station_id", "");
            setStations([]);
        }
    }, [provinceId]);

    useEffect(() => {
        if (!cityId) return;

        loadStations(cityId);

        if (cityId !== row.original.city_id) {
            setValue("station_id", "");
        }
    }, [cityId]);

    const onSubmit = async (data) => {
        const formData = new FormData();

        formData.append("status", String(data.status));
        formData.append("province_id", String(data.province_id));
        formData.append("city_id", String(data.city_id));
        formData.append("station_id", String(data.station_id));

        try {
            await requestServer(`${UPDATE_MACHINE_STATUS_AND_LOCATION}/${rowId}`, "post", {
                data: formData,
            });

            mutate();
            setOpen(false);
        } catch (error) {}
    };

    return (
        <>
            <DialogHeader>
                <DialogTitle>ویرایش ماشین</DialogTitle>
            </DialogHeader>

            <DialogContent dividers>
                <StyledForm id="updateMachineForm" onSubmit={handleSubmit(onSubmit)}>
                    <Stack spacing={3}>
                        <Controller
                            name="province_id"
                            control={control}
                            render={({ field, fieldState: { error } }) => (
                                <FormControl fullWidth size="small" error={!!error}>
                                    <InputLabel>استان</InputLabel>

                                    <Select {...field} label="استان" disabled={loadingProvinces}>
                                        {provinces.map((province) => (
                                            <MenuItem key={province.id} value={province.id}>
                                                {province.name_fa}
                                            </MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>
                            )}
                        />

                        <Controller
                            name="city_id"
                            control={control}
                            render={({ field, fieldState: { error } }) => (
                                <FormControl fullWidth size="small" error={!!error}>
                                    <InputLabel>شهر</InputLabel>

                                    <Select {...field} label="شهر" disabled={!provinceId || loadingCities}>
                                        {cities.map((city) => (
                                            <MenuItem key={city.id} value={city.id}>
                                                {city.name_fa}
                                            </MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>
                            )}
                        />

                        <Controller
                            name="station_id"
                            control={control}
                            render={({ field, fieldState: { error } }) => (
                                <FormControl fullWidth size="small" error={!!error}>
                                    <InputLabel>راهداری</InputLabel>

                                    <Select {...field} label="راهداری" disabled={!cityId || loadingStations}>
                                        {stations.map((station) => (
                                            <MenuItem key={station.id} value={station.id}>
                                                {station.name}
                                            </MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>
                            )}
                        />
                        <Controller
                            name="status"
                            control={control}
                            render={({ field, fieldState: { error } }) => (
                                <FormControl fullWidth size="small" error={!!error}>
                                    <InputLabel>وضعیت</InputLabel>

                                    <Select {...field} label="وضعیت">
                                        {statusOptions.map((item) => (
                                            <MenuItem key={item.value} value={item.value}>
                                                {item.label}
                                            </MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>
                            )}
                        />

                        {(loadingCities || loadingStations) && (
                            <Stack direction="row" justifyContent="center">
                                <CircularProgress size={24} />
                            </Stack>
                        )}
                    </Stack>
                </StyledForm>
            </DialogContent>

            <DialogActions>
                <Button onClick={() => setOpen(false)} variant="outlined" color="secondary" startIcon={<ExitToApp />}>
                    بستن
                </Button>

                <Button
                    variant="contained"
                    disabled={isSubmitting}
                    type="submit"
                    form="updateMachineForm"
                    endIcon={<Beenhere />}
                >
                    {isSubmitting ? "در حال ویرایش" : "ویرایش ماشین"}
                </Button>
            </DialogActions>
        </>
    );
};

export default EditFormContent;
