import { useEffect, useState } from 'react';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import {
    Divider,
    Typography,
    Button,
    Steps,
    Form,
    Row,
    Col,
    Card,
    Spin,
    Modal,
    ConfigProvider,
    Table,
    Tag,
    Space,
} from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { getBrandById, updateBrand } from '../../../api/master-brand';
import { getFileUrl } from '../../../api/file-uploads';
import BrandForm from './component/BrandForm';
import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import SolutionForm from './component/SolutionForm';
import ErrorCodeListModal from './component/ErrorCodeListModal';
import FormActions from './component/FormActions';
import { useErrorCodeLogic } from './hooks/errorCode';
import { useSolutionLogic } from './hooks/solution';
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 EditBrandDevice = () => {
    const navigate = useNavigate();
    const { id } = useParams();
    const location = useLocation();
    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(true);
    const [formData, setFormData] = useState(defaultData);
    const [errorCodes, setErrorCodes] = useState([]);
    const [errorCodeIcon, setErrorCodeIcon] = useState(null);
    const [solutionForm] = Form.useForm();

    const { errorCodeFields, addErrorCode, removeErrorCode, editErrorCode } = useErrorCodeLogic(
        errorCodeForm,
        fileList
    );

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

    useEffect(() => {
        const fetchBrandData = async () => {
            const token = localStorage.getItem('token');
            if (!token) {
                navigate('/signin');
                return;
            }

            const savedPhase =
                location.state?.phase || localStorage.getItem(`brand_device_edit_${id}_last_phase`);
            if (savedPhase) {
                setCurrentStep(parseInt(savedPhase));
                localStorage.removeItem(`brand_device_edit_${id}_last_phase`);
            }

            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' }}>
                            Edit Brand Device
                        </span>
                    ),
                },
            ]);

            try {
                setLoading(true);
                const response = await getBrandById(id);

                if (response && response.statusCode === 200) {
                    const brandData = response.data;
                    const newFormData = {
                        brand_name: brandData.brand_name,
                        brand_type: brandData.brand_type,
                        brand_model: brandData.brand_model,
                        brand_manufacture: brandData.brand_manufacture,
                        is_active: brandData.is_active,
                        brand_code: brandData.brand_code,
                    };

                    const existingErrorCodes = brandData.error_code
                        ? brandData.error_code.map((ec, index) => ({
                              key: `existing-${ec.error_code_id}`,
                              error_code_id: ec.error_code_id,
                              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 || '',
                              status: ec.is_active,
                              solution: ec.solution || [],
                              errorCodeIcon: ec.path_icon
                                  ? {
                                        name: 'icon',
                                        uploadPath: ec.path_icon,
                                        url: (() => {
                                            const pathParts = ec.path_icon.split('/');
                                            const folder = pathParts[0];
                                            const filename = pathParts.slice(1).join('/');
                                            return getFileUrl(folder, filename);
                                        })(),
                                        type_solution: 'image',
                                    }
                                  : null,
                          }))
                        : [];

                    setFormData(newFormData);
                    brandForm.setFieldsValue(newFormData);
                    setErrorCodes(existingErrorCodes);
                } else {
                    NotifAlert({
                        icon: 'error',
                        title: 'Error',
                        message: response?.message || 'Failed to fetch brand device data',
                    });
                }
            } catch (error) {
                NotifAlert({
                    icon: 'error',
                    title: 'Error',
                    message: error.message || 'Failed to fetch brand device data',
                });
            } finally {
                setLoading(false);
            }
        };

        fetchBrandData();
    }, [id, setBreadcrumbItems, navigate, brandForm, location]);

    const handleCancel = () => {
        localStorage.removeItem(`brand_device_edit_${id}_temp_data`);
        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 {
            // Get current solution data from forms
            const currentSolutionData = getSolutionData();

            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: errorCodes.map((ec) => {
                    // If editing current error code, get latest data from forms
                    if (ec.key === editingErrorCodeKey) {
                        return {
                            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.errorCodeIcon?.uploadPath || ec.path_icon || '',
                            is_active: ec.status !== undefined ? ec.status : true,
                            solution: currentSolutionData.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,
                            })),
                        };
                    }

                    // Return existing data for other error codes
                    return {
                        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.errorCodeIcon?.uploadPath || 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,
                        })),
                    };
                }),
            };

            const response = await updateBrand(id, finalFormData);

            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                localStorage.removeItem(`brand_device_edit_${id}_temp_data`);
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: response.message || 'Brand Device dan Error Codes berhasil diupdate.',
                });
                navigate('/master/brand-device');
            } else {
                NotifAlert({
                    icon: 'error',
                    title: 'Gagal',
                    message: response?.message || 'Gagal mengupdate Brand Device',
                });
            }
        } catch (error) {
            NotifAlert({
                icon: 'error',
                title: 'Gagal',
                message: error.message || 'Gagal mengupdate 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,
        });
        setErrorCodeIcon(record.errorCodeIcon || null);
        setIsErrorCodeFormReadOnly(true);
        setEditingErrorCodeKey(record.key);

        // Load solutions to solution form
        if (record.solution && record.solution.length > 0) {
            setSolutionsForExistingRecord(record.solution, solutionForm);
        } else {
            resetSolutionFields();
        }
    };

    const handleEditErrorCode = (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,
        });
        setErrorCodeIcon(record.errorCodeIcon || null);
        setIsErrorCodeFormReadOnly(false);
        setEditingErrorCodeKey(record.key);

        // Load solutions to solution form
        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' });
        }
    };

    const handleAddErrorCode = async () => {
        try {
            // Validate error code form
            const errorCodeValues = await errorCodeForm.validateFields();

            // Get solution data from solution form
            const solutionData = getSolutionData();

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

            // Create complete error code object
            const newErrorCode = {
                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: errorCodeIcon?.uploadPath || '',
                status: errorCodeValues.status === undefined ? true : errorCodeValues.status,
                solution: solutionData,
                errorCodeIcon: errorCodeIcon,
                key: editingErrorCodeKey || `temp-${Date.now()}`,
            };

            let updatedErrorCodes;
            if (editingErrorCodeKey) {
                // Update existing error code
                updatedErrorCodes = errorCodes.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 {
                // Add new error code
                updatedErrorCodes = [...errorCodes, newErrorCode];
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: 'Error code berhasil ditambahkan!',
                });
            }

            setErrorCodes(updatedErrorCodes);

            // Delay form reset to prevent data loss
            setTimeout(() => {
                resetErrorCodeForm();
            }, 100);
        } catch (error) {
            NotifAlert({
                icon: 'warning',
                title: 'Perhatian',
                message: 'Harap isi semua kolom wajib (error code + minimal 1 solution)!',
            });
        }
    };

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

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

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

    const handleErrorCodeIconUpload = (iconData) => {
        setErrorCodeIcon(iconData);
    };

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

    const handleFileView = (pathSolution, fileType) => {
        localStorage.setItem(`brand_device_edit_${id}_last_phase`, currentStep.toString());

        const tempData = {
            errorCodes: errorCodes,
            fileList: fileList,
            solutionFields: solutionFields,
            solutionTypes: solutionTypes,
            solutionStatuses: solutionStatuses,
            editingErrorCodeKey: editingErrorCodeKey,
            isErrorCodeFormReadOnly: isErrorCodeFormReadOnly,
            solutionsToDelete: Array.from(solutionsToDelete),
            currentSolutionData: window.currentSolutionData || {},
        };
        localStorage.setItem(`brand_device_edit_${id}_temp_data`, JSON.stringify(tempData));

        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/edit/${id}/files/${folder}/${encodedFileName}`;
        navigate(navigationPath);
    };

    const handleSolutionFileUpload = (file) => {
        setFileList((prevList) => [...prevList, file]);
    };

    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={true}
                />
            );
        }

        if (currentStep === 1) {
            return (
                <>
                    <Row gutter={24}>
                        <Col span={6}>
                            <Card
                                title={
                                    <Title level={5} style={{ margin: 0 }}>
                                        {isErrorCodeFormReadOnly
                                            ? editingErrorCodeKey
                                                ? 'View Error Code'
                                                : 'Error Code Form'
                                            : editingErrorCodeKey
                                            ? 'Edit Error Code'
                                            : 'Error Code'}
                                    </Title>
                                }
                                size="small"
                            >
                                <Form
                                    form={errorCodeForm}
                                    layout="vertical"
                                    initialValues={{
                                        status: true,
                                    }}
                                >
                                    <ErrorCodeSimpleForm
                                        errorCodeForm={errorCodeForm}
                                        isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
                                        errorCodeIcon={errorCodeIcon}
                                        onErrorCodeIconUpload={handleErrorCodeIconUpload}
                                        onErrorCodeIconRemove={handleErrorCodeIconRemove}
                                        onAddErrorCode={handleAddErrorCode}
                                    />
                                </Form>
                            </Card>
                        </Col>
                        <Col span={8}>
                            <Card
                                title={
                                    <Title level={5} style={{ margin: 0 }}>
                                        Solutions
                                    </Title>
                                }
                                size="small"
                            >
                                <Form
                                    form={solutionForm}
                                    layout="vertical"
                                    initialValues={{
                                        solution_status_0: true,
                                        solution_type_0: 'text',
                                    }}
                                >
                                    <SolutionForm
                                        solutionForm={solutionForm}
                                        solutionFields={solutionFields}
                                        solutionTypes={solutionTypes}
                                        solutionStatuses={solutionStatuses}
                                        onAddSolutionField={handleAddSolutionField}
                                        onRemoveSolutionField={handleRemoveSolutionField}
                                        onSolutionTypeChange={handleSolutionTypeChange}
                                        onSolutionStatusChange={handleSolutionStatusChange}
                                        isReadOnly={isErrorCodeFormReadOnly}
                                        onFileUpload={handleSolutionFileUpload}
                                        onFileView={handleFileView}
                                    />
                                </Form>
                            </Card>
                        </Col>
                        <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' }}>
                Edit Brand Device
            </Title>
            <Steps current={currentStep} style={{ marginBottom: 24 }}>
                <Step title="Brand Device Details" />
                <Step title="Error Codes & Solutions" />
            </Steps>
            <div style={{ position: 'relative' }}>
                {loading && (
                    <div
                        style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            backgroundColor: 'rgba(255, 255, 255, 0.6)',
                            backdropFilter: 'blur(0.8px)',
                            filter: 'blur(0.5px)',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            zIndex: 10,
                            borderRadius: '8px',
                        }}
                    >
                        <Spin size="large" />
                    </div>
                )}
                <div
                    style={{
                        filter: loading ? 'blur(0.5px)' : 'none',
                        transition: 'filter 0.3s ease',
                    }}
                >
                    {renderStepContent()}
                </div>
            </div>
            <Divider />
            <FormActions
                currentStep={currentStep}
                onPreviousStep={() => setCurrentStep(currentStep - 1)}
                onNextStep={handleNextStep}
                onSave={handleFinish}
                onCancel={handleCancel}
                confirmLoading={confirmLoading}
                isEditMode={true}
            />
        </Card>
    );
};

export default EditBrandDevice;
