import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Divider, Typography, Button, Steps, Form, Row, Col, Card } from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { createBrand } from '../../../api/master-brand';
import BrandForm from './component/BrandForm';
import ErrorCodeForm from './component/ErrorCodeForm';
import ErrorCodeTable from './component/ListErrorCode';
import FormActions from './component/FormActions';
import { useErrorCodeLogic } from './hooks/errorCode';
import { uploadFile, getFolderFromFileType } from '../../../api/file-uploads';

const { Title } = Typography;
const { Step } = Steps;

const defaultData = {
    brand_name: '',
    brand_type: '',
    brand_model: '',
    brand_manufacture: '',
    is_active: true,
    brand_code: '',
};

const AddBrandDevice = () => {
    const navigate = useNavigate();
    const { setBreadcrumbItems } = useBreadcrumb();
    const [brandForm] = Form.useForm();
    const [errorCodeForm] = Form.useForm();
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [currentStep, setCurrentStep] = useState(0);
    const [fileList, setFileList] = useState([]);
    const [isErrorCodeFormReadOnly, setIsErrorCodeFormReadOnly] = useState(false);
    const [editingErrorCodeKey, setEditingErrorCodeKey] = useState(null);
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState(defaultData);
    const [errorCodes, setErrorCodes] = useState([]);

    const {
        solutionFields,
        solutionTypes,
        solutionStatuses,
        firstSolutionValid,
        solutionsToDelete,
        handleAddSolutionField,
        handleRemoveSolutionField,
        handleSolutionTypeChange,
        handleSolutionStatusChange,
        resetSolutionFields,
        checkFirstSolutionValid,
        setSolutionsForExistingRecord
    } = useErrorCodeLogic(errorCodeForm, fileList);

    useEffect(() => {
        setBreadcrumbItems([
            { title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}>• Master</span> },
            {
                title: <span style={{ fontSize: '14px', fontWeight: 'bold', cursor: 'pointer' }} onClick={() => navigate('/master/brand-device')}>Brand Device</span>
            },
            { title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}>Tambah Brand Device</span> }
        ]);
    }, [setBreadcrumbItems, navigate]);

    const handleCancel = () => {
        navigate('/master/brand-device');
    };

    const handleNextStep = async () => {
        try {
            await brandForm.validateFields();
            setCurrentStep(1);
        } catch (error) {
            NotifAlert({ icon: 'warning', title: 'Perhatian', message: 'Harap isi semua kolom wajib untuk brand device!' });
        }
    };

    const handleFinish = async () => {
        setConfirmLoading(true);
        try {
            const transformedErrorCodes = errorCodes.map(ec => ({
                error_code: ec.error_code,
                error_code_name: ec.error_code_name || '',
                error_code_description: ec.error_code_description || '',
                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 !== false
                }))
            }));

            const finalFormData = {
                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,
                error_code: transformedErrorCodes.length > 0 ? transformedErrorCodes : [
                    {
                        error_code: "DEFAULT",
                        error_code_name: "Default Error Code",
                        error_code_description: "Default error description",
                        is_active: true,
                        solution: [
                            {
                                solution_name: "Default Solution",
                                type_solution: "text",
                                text_solution: "Default solution text",
                                path_solution: "",
                                is_active: true
                            }
                        ]
                    }
                ]
            };

            const response = await createBrand(finalFormData);

            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: response.message || 'Brand Device berhasil ditambahkan.',
                });
                navigate('/master/brand-device');
            } else {
                NotifAlert({
                    icon: 'error',
                    title: 'Gagal',
                    message: response?.message || 'Gagal menambahkan Brand Device',
                });
            }
        } catch (error) {
            NotifAlert({
                icon: "error",
                title: "Gagal",
                message: error.message || "Gagal menyimpan data. Silakan coba lagi.",
            });
        } finally {
            setConfirmLoading(false);
        }
    };

    const handlePreviewErrorCode = (record) => {
        errorCodeForm.setFieldsValue({
            error_code: record.error_code,
            error_code_name: record.error_code_name,
            error_code_description: record.error_code_description,
            status: record.status,
        });
        setFileList(record.fileList || []);
        setIsErrorCodeFormReadOnly(true);
        setEditingErrorCodeKey(null);

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

    const handleEditErrorCode = (record) => {
        errorCodeForm.setFieldsValue({
            error_code: record.error_code,
            error_code_name: record.error_code_name,
            error_code_description: record.error_code_description,
            status: record.status,
        });
        setFileList(record.fileList || []);
        setIsErrorCodeFormReadOnly(false);
        setEditingErrorCodeKey(record.key);

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

    const handleAddErrorCode = async (newErrorCode) => {
        if (editingErrorCodeKey) {
            const updatedCodes = errorCodes.map(item => item.key === editingErrorCodeKey ? newErrorCode : item);
            setErrorCodes(updatedCodes);
            NotifOk({
                icon: 'success',
                title: 'Berhasil',
                message: 'Error code berhasil diupdate!'
            });
        } else {
            const updatedCodes = [...errorCodes, newErrorCode];
            setErrorCodes(updatedCodes);
            NotifOk({
                icon: 'success',
                title: 'Berhasil',
                message: 'Error code berhasil ditambahkan!'
            });
        }

        resetErrorCodeForm();
    };

    const resetErrorCodeForm = () => {
        errorCodeForm.resetFields();
        errorCodeForm.setFieldsValue({
            status: true,
            solution_status_0: true,
            solution_type_0: 'text'
        });
        setFileList([]);
        resetSolutionFields();
        setIsErrorCodeFormReadOnly(false);
        setEditingErrorCodeKey(null);
    };

    const handleCreateNewErrorCode = () => {
        resetErrorCodeForm();
    };

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

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

    const handleFileView = (pathSolution, fileType) => {
        const filePath = pathSolution || '';
        if (!filePath) return;

        const parts = filePath.split('/');
        if (parts.length < 2) return;

        const [folder, filename] = parts;
        const encodedFileName = encodeURIComponent(filename);
        const navigationPath = `/master/brand-device/view/temp/files/${folder}/${encodedFileName}`;
        navigate(navigationPath);
    };

    const handleSolutionFileUpload = async (file) => {
        try {
            const isAllowedType = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif'].includes(file.type);
            if (!isAllowedType) {
                NotifAlert({
                    icon: 'error',
                    title: 'Error',
                    message: `${file.name} bukan file PDF atau gambar yang diizinkan.`
                });
                return;
            }

            const fileExtension = file.name.split('.').pop().toLowerCase();
            const isImage = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(fileExtension);
            const fileType = isImage ? 'image' : 'pdf';
            const folder = getFolderFromFileType(fileType);

            const uploadResponse = await uploadFile(file, folder);
            const actualPath = uploadResponse.data?.path_solution || '';

            if (actualPath) {
                file.uploadPath = actualPath;
                file.solution_name = file.name;
                file.solutionId = solutionFields[0];
                file.type_solution = fileType;
                setFileList(prevList => [...prevList, file]);
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `${file.name} berhasil diupload!`
                });
            } else {
                NotifAlert({
                    icon: 'error',
                    title: 'Gagal',
                    message: `Gagal mengupload ${file.name}`
                });
            }
        } catch (error) {
            console.error('Error uploading file:', error);
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: `Gagal mengupload ${file.name}. Silakan coba lagi.`
            });
        }
    };

    const handleFileRemove = (file) => {
        const newFileList = fileList.filter(item => item.uid !== file.uid);
        setFileList(newFileList);
    };

    const renderStepContent = () => {
        if (currentStep === 0) {
            return (
                <BrandForm
                    form={brandForm}
                    formData={formData}
                    onValuesChange={(changedValues, allValues) => setFormData(prev => ({...prev, ...allValues}))}
                    isEdit={false}
                />
            );
        }

        if (currentStep === 1) {
            return (
                <Row gutter={24}>
                    <Col span={12}>
                        <Title level={5} style={{ marginBottom: 16 }}>
                            {isErrorCodeFormReadOnly
                                ? 'View Error Code'
                                : (editingErrorCodeKey ? 'Edit Error Code' : 'Tambah Error Code')
                            }
                        </Title>
                        <Form
                            form={errorCodeForm}
                            layout="vertical"
                            initialValues={{ status: true, solution_status_0: true, solution_type_0: 'text' }}
                            onValuesChange={checkFirstSolutionValid}
                        >
                            <ErrorCodeForm
                                errorCodeForm={errorCodeForm}
                                isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
                                editingErrorCodeKey={editingErrorCodeKey}
                                solutionFields={solutionFields}
                                solutionTypes={solutionTypes}
                                solutionStatuses={solutionStatuses}
                                fileList={fileList}
                                solutionsToDelete={solutionsToDelete}
                                firstSolutionValid={firstSolutionValid}
                                onAddErrorCode={handleAddErrorCode}
                                onAddSolutionField={handleAddSolutionField}
                                onRemoveSolutionField={handleRemoveSolutionField}
                                onSolutionTypeChange={handleSolutionTypeChange}
                                onSolutionStatusChange={handleSolutionStatusChange}
                                onSolutionFileUpload={handleSolutionFileUpload}
                                onFileView={handleFileView}
                                onCreateNewErrorCode={handleCreateNewErrorCode}
                                onResetForm={resetErrorCodeForm}
                                errorCodes={errorCodes}
                            />
                        </Form>
                    </Col>
                    <Col span={12}>
                        <ErrorCodeTable
                            errorCodes={errorCodes}
                            loading={loading}
                            onPreview={handlePreviewErrorCode}
                            onEdit={handleEditErrorCode}
                            onDelete={handleDeleteErrorCode}
                            onFileView={handleFileView}
                        />
                    </Col>
                </Row>
            );
        }
        return null;
    };

    return (
        <Card>
            <Title level={4} style={{ margin: '0 0 24px 0' }}>Tambah Brand Device</Title>
            <Steps current={currentStep} style={{ marginBottom: 24 }}>
                <Step title="Brand Device Details" />
                <Step title="Error Codes" />
            </Steps>
            <div style={{ marginTop: 24 }}>
                {renderStepContent()}
            </div>
            <Divider />
            <FormActions
                currentStep={currentStep}
                onPreviousStep={() => setCurrentStep(currentStep - 1)}
                onNextStep={handleNextStep}
                onSave={handleFinish}
                onCancel={handleCancel}
                confirmLoading={confirmLoading}
                isEditMode={false}
            />
        </Card>
    );
};

export default AddBrandDevice;