import { useState } from 'react';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';

export const useBrandDeviceLogic = (isEditMode = false, brandId = null) => {
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [currentStep, setCurrentStep] = useState(0);
    const [loading, setLoading] = useState(false);
    const [errorCodes, setErrorCodes] = useState([]);
    const [pendingErrorCodes, setPendingErrorCodes] = useState([]);
    const [editingErrorCodeKey, setEditingErrorCodeKey] = useState(null);
    const [isErrorCodeFormReadOnly, setIsErrorCodeFormReadOnly] = useState(false);

    const handleCancel = () => {
    };

    const handleNextStep = async (validateForm, setFormData, currentFormData) => {
        try {
            const validatedFormData = await validateForm();

            setFormData({
                brand_name: validatedFormData.brand_name,
                brand_type: validatedFormData.brand_type || '',
                brand_model: validatedFormData.brand_model || '',
                brand_manufacture: validatedFormData.brand_manufacture || '',
                is_active: validatedFormData.is_active,
            });

            setCurrentStep(1);
        } catch (error) {
            NotifAlert({
                icon: 'warning',
                title: 'Perhatian',
                message: 'Harap isi semua kolom wajib untuk brand device!',
            });
            return false;
        }
    };

    const handleFinish = async (
        formData,
        selectedSparepartIds,
        apiCall,
        successMessage,
        navigatePath
    ) => {
        setConfirmLoading(true);
        try {
            const transformedErrorCodes = pendingErrorCodes.length > 0 ? pendingErrorCodes.map(ec => ({
                error_code: ec.error_code,
                error_code_name: ec.error_code_name,
                error_code_description: ec.error_code_description || '',
                error_code_color: ec.error_code_color || '#000000',
                path_icon: ec.path_icon || '',
                is_active: ec.status !== undefined ? ec.status : true,
                solution: (ec.solution || []).map(sol => ({
                    solution_name: sol.solution_name,
                    type_solution: sol.type_solution,
                    text_solution: sol.text_solution || '',
                    path_solution: sol.path_solution || '',
                    is_active: sol.is_active
                }))
            })) : (isEditMode ? errorCodes.map(ec => ({
                error_code: ec.error_code,
                error_code_name: ec.error_code_name,
                error_code_description: ec.error_code_description || '',
                error_code_color: ec.error_code_color || '#000000',
                path_icon: ec.path_icon || '',
                is_active: ec.status !== undefined ? ec.status : true,
                solution: (ec.solution || []).map(sol => ({
                    solution_name: sol.solution_name,
                    type_solution: sol.type_solution,
                    text_solution: sol.text_solution || '',
                    path_solution: sol.path_solution || '',
                    is_active: sol.is_active
                }))
            })) : []);

            const brandData = {
                brand_name: formData.brand_name,
                brand_type: formData.brand_type || '',
                brand_model: formData.brand_model || '',
                brand_manufacture: formData.brand_manufacture || '',
                is_active: formData.is_active,
                spareparts: selectedSparepartIds,
                error_code: transformedErrorCodes,
            };

            const response = await apiCall(brandId, brandData);

            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: response.message || successMessage,
                });
                navigate(navigatePath);
            } else {
                NotifAlert({
                    icon: 'error',
                    title: 'Gagal',
                    message: response?.message || 'Gagal menyimpan data.',
                });
            }
        } catch (error) {
            NotifAlert({
                icon: 'error',
                title: 'Gagal',
                message: error.message || 'Gagal menyimpan data. Silakan coba lagi.',
            });
        } finally {
            setConfirmLoading(false);
        }
    };

    const handleAddErrorCode = async (
        validateErrorCodeForm,
        getSolutionData,
        resetErrorCodeForm
    ) => {
        try {
            const errorCodeValues = await validateErrorCodeForm();
            const solutionData = getSolutionData();

            if (solutionData.length === 0) {
                NotifAlert({
                    icon: 'warning',
                    title: 'Perhatian',
                    message: 'Setiap error code harus memiliki minimal 1 solution!',
                });
                return false;
            }

            const newErrorCode = {
                key: editingErrorCodeKey || `temp-${Date.now()}`,
                error_code: errorCodeValues.error_code,
                error_code_name: errorCodeValues.error_code_name,
                error_code_description: errorCodeValues.error_code_description,
                error_code_color: errorCodeValues.error_code_color || '#000000',
                path_icon: errorCodeValues.path_icon || '',
                is_active: errorCodeValues.status === undefined ? true : errorCodeValues.status,
                solution: solutionData,
            };

            let updatedPendingErrorCodes;
            if (editingErrorCodeKey) {
                updatedPendingErrorCodes = pendingErrorCodes.map((item) => {
                    if (item.key === editingErrorCodeKey) {
                        return {
                            ...item,
                            ...newErrorCode,
                            error_code_id: item.error_code_id || newErrorCode.error_code_id,
                        };
                    }
                    return item;
                });
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: 'Error code berhasil diupdate!',
                });
            } else {
                updatedPendingErrorCodes = [...pendingErrorCodes, newErrorCode];
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: 'Error code berhasil ditambahkan!',
                });
            }

            setPendingErrorCodes(updatedPendingErrorCodes);
            setErrorCodes(updatedPendingErrorCodes);

            setTimeout(() => {
                resetErrorCodeForm();
            }, 100);
            return true;
        } catch (error) {
            NotifAlert({
                icon: 'warning',
                title: 'Perhatian',
                message: 'Harap isi semua kolom wajib (error code + minimal 1 solution)!',
            });
            return false;
        }
    };

    const handleDeleteErrorCode = (key) => {
        if (errorCodes.length <= 1) {
            NotifAlert({
                icon: 'warning',
                title: 'Perhatian',
                message: 'Setiap brand harus memiliki minimal 1 error code!',
            });
            return false;
        }

        const updatedErrorCodes = errorCodes.filter((item) => item.key !== key);
        setErrorCodes(updatedErrorCodes);
        NotifOk({
            icon: 'success',
            title: 'Berhasil',
            message: 'Error code berhasil dihapus!',
        });
        return true;
    };

    const handleCreateNewErrorCode = (resetErrorCodeForm, resetSolutionFields) => {
        resetErrorCodeForm();
        resetSolutionFields();
        setIsErrorCodeFormReadOnly(false);
        setEditingErrorCodeKey(null);
    };

    const handlePreviewErrorCode = (
        record,
        setErrorCodeIcon,
        setIsErrorCodeFormReadOnly,
        setEditingErrorCodeKey,
        setSolutionsForExistingRecord,
        resetSolutionFields,
        solutionForm
    ) => {
        errorCodeForm.setFieldsValue({
            error_code: record.error_code,
            error_code_name: record.error_code_name,
            error_code_description: record.error_code_description,
            error_code_color: record.error_code_color,
            status: record.status,
        });
        setErrorCodeIcon(record.errorCodeIcon || null);
        setIsErrorCodeFormReadOnly(true);
        setEditingErrorCodeKey(record.key);

        if (record.solution && record.solution.length > 0) {
            setSolutionsForExistingRecord(record.solution, solutionForm);
        } else {
            resetSolutionFields();
        }
    };

    const handleEditErrorCode = (
        record,
        setErrorCodeIcon,
        setIsErrorCodeFormReadOnly,
        setEditingErrorCodeKey,
        setSolutionsForExistingRecord,
        resetSolutionFields,
        solutionForm
    ) => {
        errorCodeForm.setFieldsValue({
            error_code: record.error_code,
            error_code_name: record.error_code_name,
            error_code_description: record.error_code_description,
            error_code_color: record.error_code_color,
            status: record.status,
        });
        setErrorCodeIcon(record.errorCodeIcon || null);
        setIsErrorCodeFormReadOnly(false);
        setEditingErrorCodeKey(record.key);

        if (record.solution && record.solution.length > 0) {
            setSolutionsForExistingRecord(record.solution, solutionForm);
        }

        const formElement = document.querySelector('.ant-form');
        if (formElement) {
            formElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    };

    return {
        // State
        confirmLoading,
        setConfirmLoading,
        currentStep,
        setCurrentStep,
        loading,
        setLoading,
        errorCodes,
        setErrorCodes,
        pendingErrorCodes,
        setPendingErrorCodes,
        editingErrorCodeKey,
        setEditingErrorCodeKey,
        isErrorCodeFormReadOnly,
        setIsErrorCodeFormReadOnly,

        // Handlers
        handleCancel,
        handleNextStep,
        handleFinish,
        handleAddErrorCode,
        handleDeleteErrorCode,
        handleCreateNewErrorCode,
        handlePreviewErrorCode,
        handleEditErrorCode,
    };
};