"use client";

import type { DoDetail as DoDetailType } from "@/app/api/do/actions";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import useUploadContext from "../UploadProvider/useUploadContext";
import { FormProvider, SubmitErrorHandler, SubmitHandler, useForm } from "react-hook-form";
import { useCallback, useState } from "react";
import { Button, Stack, Typography, Box, Alert } from "@mui/material";
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import StartIcon from "@mui/icons-material/Start";
import { releaseDo, startBatchReleaseAsyncSingle, assignPickOrderByStore, releaseAssignedPickOrderByStore } from "@/app/api/do/actions";
import {
  getWorkbenchBatchReleaseProgress,
  startWorkbenchBatchReleaseAsyncSingleV2,
} from "@/app/api/doworkbench/actions";
import Swal from "sweetalert2";
import DoInfoCard from "./DoInfoCard";
import DoLineTable from "./DoLineTable";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig"; //  Import the correct session type

type Props = {
    id?: number;
    defaultValues: Partial<DoDetailType> | undefined;
    workbenchRelease?: boolean;
}

const DoDetail: React.FC<Props> = ({
    defaultValues,
    id,
    workbenchRelease = true,
}) => {
    const { t } = useTranslation("do")
    const router = useRouter();
    const { setIsUploading } = useUploadContext();
    const [serverError, setServerError] = useState("");
    const [successMessage, setSuccessMessage] = useState("");
    const [isAssigning, setIsAssigning] = useState(false);
    const { data: session } = useSession() as { data: SessionWithTokens | null }; //  Use correct session type
    
    const currentUserId = session?.id ? parseInt(session.id) : undefined; //  Get user ID from session.id
    //console.log("🔍 DoSearch - session:", session);
//console.log("🔍 DoSearch - currentUserId:", currentUserId);
    const formProps = useForm<DoDetailType>({
        defaultValues: defaultValues
    })

    const handleBack = useCallback(() => {
        router.replace(`/do`)
    }, [router])

    const handleRelease = useCallback(async () => {
        try {
            setIsUploading(true)
            setServerError("")
            setSuccessMessage("")
            
            if (id) {
                //  Get current user ID from session
                //const currentUserId = session?.id ? parseInt(session.id) : undefined;
                
                //if (!currentUserId) {
                //    setServerError("User session not found. Please login again.");
                //    return;
                //}
                /*
                const response = await releaseDo({ 
                    id: id,
                    //userId: currentUserId //  Pass user ID from session
                })
                */
                const response = await startWorkbenchBatchReleaseAsyncSingleV2({
                    doId: id,
                    userId: currentUserId ?? 0
                })
                if (response?.code === "STARTED") {
                    setSuccessMessage(t("DO released successfully! Pick orders created."));
                    router.refresh();
                  } else if (response) {
                    setServerError(
                      response.message ??
                        response.code ??
                        t("An error has occurred. Please try again later."),
                    );
                  }
            }
        } catch (e) {
            setServerError(t("An error has occurred. Please try again later."));
            console.log(e);
        } finally {
            setIsUploading(false)
        }
    }, [id, formProps, t, setIsUploading, session]) //  Add session to dependencies

    //  UPDATE STORE-BASED ASSIGNMENT HANDLERS
    const handleAssignByStore = useCallback(async (storeId: string) => {
        try {
            setIsAssigning(true)
            setServerError("")
            setSuccessMessage("")
            
            //  Get current user ID from session
            const currentUserId = session?.id ? parseInt(session.id) : undefined;
            
            if (!currentUserId) {
                setServerError("User session not found. Please login again.");
                return;
            }
            
            const response = await assignPickOrderByStore({
                storeId: storeId,
                assignTo: currentUserId
            })
            
            if (response) {
                setSuccessMessage(`Pick orders assigned to ${storeId} successfully!`)
                console.log("Assignment response:", response)
            }

        } catch (e) {
            setServerError(t("Failed to assign pick orders. Please try again later."));
            console.log(e);
        } finally {
            setIsAssigning(false)
        }
    }, [t, session]) //  Add session to dependencies

    const handleReleaseByStore = useCallback(async (storeId: string) => {
        try {
            setIsAssigning(true)
            setServerError("")
            setSuccessMessage("")
            
            //  Get current user ID from session
            const currentUserId = session?.id ? parseInt(session.id) : undefined;
            
            if (!currentUserId) {
                setServerError("User session not found. Please login again.");
                return;
            }
            
            const response = await releaseAssignedPickOrderByStore({
                storeId: storeId,
                assignTo: currentUserId
            })
            
            if (response) {
                setSuccessMessage(`Pick orders released for ${storeId} successfully!`)
                console.log("Release response:", response)
            }

        } catch (e) {
            setServerError(t("Failed to release pick orders. Please try again later."));
            console.log(e);
        } finally {
            setIsAssigning(false)
        }
    }, [t, session]) //  Add session to dependencies

    const onSubmit = useCallback<SubmitHandler<DoDetailType>>(async (data, event) => {
        console.log(data)
    }, [t])

    const onSubmitError = useCallback<SubmitErrorHandler<DoDetailType>>((errors) => {
        console.log(errors)
    }, [t])

    return <>
        <FormProvider {...formProps}>
            <Stack
                spacing={2}
                component="form"
                onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
            >
                {serverError && (
                    <Alert severity="error" sx={{ mb: 2 }}>
                        {serverError}
                    </Alert>
                )}
                
                {successMessage && (
                    <Alert severity="success" sx={{ mb: 2 }}>
                        {successMessage}
                    </Alert>
                )}

             
                {formProps.watch("status")?.toLowerCase() === "pending" && (
                        <Stack direction="row" justifyContent="flex-start" gap={1}>
                            <Button
                                variant="outlined"
                                startIcon={<StartIcon />}
                                onClick={handleRelease}
                                disabled={isAssigning}
                            >
                                {t("Release")}
                            </Button>
                        </Stack>
                    )
                }
                {/*  ADD STORE-BASED ASSIGNMENT BUTTONS */}
                {/*
                {
                    formProps.watch("status")?.toLowerCase() === "released" && (
                        <Box sx={{ mb: 2 }}>
                            <Typography variant="h6" gutterBottom>
                                {t("Pick Order Assignment")}
                            </Typography>
                            <Stack direction="row" spacing={2}>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    onClick={() => handleAssignByStore("2/F")}
                                    disabled={isAssigning}
                                    sx={{ minWidth: 120 }}
                                >
                                    {t("Assign 2/F")}
                                </Button>
                                <Button
                                    variant="contained"
                                    color="secondary"
                                    onClick={() => handleAssignByStore("4/F")}
                                    disabled={isAssigning}
                                    sx={{ minWidth: 120 }}
                                >
                                    {t("Assign 4/F")}
                                </Button>
                            </Stack>
                            
                            <Stack direction="row" spacing={2} sx={{ mt: 1 }}>
                                <Button
                                    variant="outlined"
                                    color="primary"
                                    onClick={() => handleReleaseByStore("2/F")}
                                    disabled={isAssigning}
                                    sx={{ minWidth: 120 }}
                                >
                                    {t("Release 2/F")}
                                </Button>
                                <Button
                                    variant="outlined"
                                    color="secondary"
                                    onClick={() => handleReleaseByStore("4/F")}
                                    disabled={isAssigning}
                                    sx={{ minWidth: 120 }}
                                >
                                    {t("Release 4/F")}
                                </Button>
                            </Stack>
                        </Box>
                    )}
                */}
                <DoInfoCard />
                <DoLineTable />
                <Stack direction="row" justifyContent="flex-end" gap={1}>
                    <Button
                        variant="outlined"
                        startIcon={<ArrowBackIcon />}
                        onClick={handleBack}
                    >
                        {t("Back")}
                    </Button>
                </Stack>
            </Stack>
        </FormProvider>
    </>
}

export default DoDetail;