import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Divider,
    Typography,
    Button,
    Steps,
    Form,
    Row,
    Col,
    Card,
    ConfigProvider,
    Table,
    Tag,
    Space,
} 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 ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import ErrorCodeListModal from './component/ErrorCodeListModal';
import FormActions from './component/FormActions';
import SolutionForm from './component/SolutionForm';
import { useSolutionLogic } from './hooks/solution';
import { uploadFile, getFolderFromFileType } from '../../../api/file-uploads';
import { EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';

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 [solutionForm] = 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 [errorCodeIcon, setErrorCodeIcon] = useState(null);

    const {
        solutionFields,
        solutionTypes,
        solutionStatuses,
        solutionsToDelete,
        firstSolutionValid,
        handleAddSolutionField,
        handleRemoveSolutionField,
        handleSolutionTypeChange,
        handleSolutionStatusChange,
        resetSolutionFields,
        checkFirstSolutionValid,
        getSolutionData,
        setSolutionsForExistingRecord,
    } = useSolutionLogic(solutionForm);

    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 {
            // Validation: Ensure at least one error code
            if (errorCodes.length === 0) {
                NotifAlert({
                    icon: 'warning',
                    title: 'Perhatian',
                    message: 'Setidaknya tambahkan 1 error code!',
                });
                setConfirmLoading(false);
                return;
            }

            const transformedErrorCodes = 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 !== false,
                })),
                // Note: Sparepart data is collected but not sent to backend yet
                // sparepart: (ec.sparepart || []).map((sp) => ({
                //     type: sp.type || 'required',
                //     name: sp.name || '',
                //     quantity: sp.quantity || 1,
                //     is_active: sp.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,
            };

            console.log('Final form data:', finalFormData); // Debug log

            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) {
            console.error('Finish Error:', 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,
            error_code_color: record.error_code_color,
            status: record.status,
        });
        setFileList(record.fileList || []);
        setErrorCodeIcon(record.errorCodeIcon || null);
        setIsErrorCodeFormReadOnly(true);
        setEditingErrorCodeKey(null);

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

    const handleEditErrorCode = (record) => {
        // Prevent infinite loop
        if (editingErrorCodeKey === record.key) {
            return;
        }

        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 || '#000000',
            status: record.status !== false,
        });
        setFileList(record.fileList || []);
        setErrorCodeIcon(record.errorCodeIcon || null);
        setIsErrorCodeFormReadOnly(false);
        setEditingErrorCodeKey(record.key);

        if (record.solution && record.solution.length > 0) {
            // Reset solution fields first
            resetSolutionFields();
            // Then load new solutions
            setTimeout(() => {
                setSolutionsForExistingRecord(record.solution, solutionForm);
            }, 0);
        } else {
            resetSolutionFields();
        }
    };

    const handleAddErrorCode = async () => {
        try {
            const formValues = errorCodeForm.getFieldsValue();

            // Validation
            if (!formValues.error_code || !formValues.error_code_name) {
                NotifAlert({
                    icon: 'warning',
                    title: 'Perhatian',
                    message: 'Error code dan error name wajib diisi!',
                });
                return;
            }

            // Validate at least 1 solution
            const solutions = getSolutionData();

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

            const newErrorCode = {
                key: Date.now(),
                error_code: formValues.error_code,
                error_code_name: formValues.error_code_name || '',
                error_code_description: formValues.error_code_description || '',
                error_code_color: formValues.error_code_color || '#000000',
                path_icon: errorCodeIcon?.uploadPath || '',
                status: formValues.status !== false,
                errorCodeIcon: errorCodeIcon,
                solution: solutions,
            };

            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!',
                });
            }

            // Reset all forms
            resetErrorCodeForm();
            resetSolutionFields();
        } catch (error) {
            console.error('Error adding error code:', error);
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: 'Gagal menambahkan error code',
            });
        }
    };

    const resetErrorCodeForm = () => {
        errorCodeForm.resetFields();
        errorCodeForm.setFieldsValue({
            status: true,
            solution_status_0: true,
            solution_type_0: 'text',
        });
        setFileList([]);
        setErrorCodeIcon(null);
        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 handleErrorCodeIconUpload = (iconData) => {
        setErrorCodeIcon(iconData);
    };

    const handleErrorCodeIconRemove = () => {
        setErrorCodeIcon(null);
    };

    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={16} style={{ marginBottom: 24 }}>
                        {/* Error Code Form Column */}
                        <Col span={6}>
                            <Card size="small" title="Error Code">
                                <Form
                                    form={errorCodeForm}
                                    layout="vertical"
                                    initialValues={{
                                        status: true,
                                    }}
                                >
                                    <ErrorCodeSimpleForm
                                        errorCodeForm={errorCodeForm}
                                        isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
                                        errorCodeIcon={errorCodeIcon}
                                        onErrorCodeIconUpload={handleErrorCodeIconUpload}
                                        onErrorCodeIconRemove={handleErrorCodeIconRemove}
                                        onAddErrorCode={handleAddErrorCode}
                                    />
                                </Form>
                            </Card>
                        </Col>

                        {/* Solution Form Column */}
                        <Col span={8}>
                            <Card size="small" title="Solutions">
                                <Form
                                    form={solutionForm}
                                    layout="vertical"
                                    initialValues={{
                                        solution_status_0: true,
                                        solution_type_0: 'text',
                                    }}
                                    onValuesChange={checkFirstSolutionValid}
                                >
                                    <SolutionForm
                                        solutionForm={solutionForm}
                                        solutionFields={solutionFields}
                                        solutionTypes={solutionTypes}
                                        solutionStatuses={solutionStatuses}
                                        fileList={fileList}
                                        solutionsToDelete={solutionsToDelete}
                                        firstSolutionValid={firstSolutionValid}
                                        onAddSolutionField={handleAddSolutionField}
                                        onRemoveSolutionField={handleRemoveSolutionField}
                                        onSolutionTypeChange={handleSolutionTypeChange}
                                        onSolutionStatusChange={handleSolutionStatusChange}
                                        onSolutionFileUpload={handleSolutionFileUpload}
                                        onFileView={handleFileView}
                                        isReadOnly={isErrorCodeFormReadOnly}
                                    />
                                </Form>
                            </Card>
                        </Col>

                        {/* Error Codes Table Column */}
                        <Col span={10}>
                            <Card size="small" title={`Error Codes (${errorCodes.length})`}>
                                <Table
                                    dataSource={errorCodes}
                                    columns={[
                                        {
                                            title: 'Error Code',
                                            dataIndex: 'error_code',
                                            key: 'error_code',
                                            width: '25%',
                                        },
                                        {
                                            title: 'Sol',
                                            key: 'Sol',
                                            width: '10%',
                                            align: 'center',
                                            render: (_, record) => {
                                                const solutionCount = record.solution
                                                    ? record.solution.length
                                                    : 0;
                                                return (
                                                    <Tag
                                                        color={solutionCount > 0 ? 'green' : 'red'}
                                                    >
                                                        {solutionCount} Sol
                                                    </Tag>
                                                );
                                            },
                                        },
                                        {
                                            title: 'Status',
                                            dataIndex: 'status',
                                            key: 'status',
                                            width: '20%',
                                            align: 'center',
                                            render: (_, { status }) => (
                                                <Tag color={status ? 'green' : 'red'}>
                                                    {status ? 'Active' : 'Inactive'}
                                                </Tag>
                                            ),
                                        },
                                        {
                                            title: 'Action',
                                            key: 'action',
                                            align: 'center',
                                            width: '15%',
                                            render: (_, record) => (
                                                <Space>
                                                    <Button
                                                        type="text"
                                                        style={{ borderColor: '#1890ff' }}
                                                        size="small"
                                                        icon={
                                                            <EyeOutlined
                                                                style={{ color: '#1890ff' }}
                                                            />
                                                        }
                                                        onClick={() =>
                                                            handlePreviewErrorCode(record)
                                                        }
                                                    />
                                                    <Button
                                                        type="text"
                                                        style={{ borderColor: '#faad14' }}
                                                        size="small"
                                                        icon={
                                                            <EditOutlined
                                                                style={{ color: '#faad14' }}
                                                            />
                                                        }
                                                        onClick={() => handleEditErrorCode(record)}
                                                    />
                                                    <Button
                                                        type="text"
                                                        danger
                                                        style={{ borderColor: 'red' }}
                                                        size="small"
                                                        icon={<DeleteOutlined />}
                                                        onClick={() =>
                                                            handleDeleteErrorCode(record.key)
                                                        }
                                                    />
                                                </Space>
                                            ),
                                        },
                                    ]}
                                    rowKey="key"
                                    pagination={{
                                        pageSize: 10,
                                        showSizeChanger: false,
                                        hideOnSinglePage: true,
                                    }}
                                    size="small"
                                    scroll={{ y: 300 }}
                                />
                            </Card>
                        </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 & Solutions" />
            </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;
