import { Form, Divider, Button, Switch, Input, ConfigProvider, Typography, Upload, message } from 'antd';
import { PlusOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import { NotifAlert } from '../../../../components/Global/ToastNotif';
import SolutionField from './SolutionField';
import { uploadFile, getFileUrl } from '../../../../api/file-uploads';

const { Text } = Typography;

const ErrorCodeForm = ({
    errorCodeForm,
    isErrorCodeFormReadOnly,
    editingErrorCodeKey,
    solutionFields,
    solutionTypes,
    solutionStatuses,
    fileList,
    solutionsToDelete,
    firstSolutionValid,
    onAddErrorCode,
    onAddSolutionField,
    onRemoveSolutionField,
    onSolutionTypeChange,
    onSolutionStatusChange,
    onSolutionFileUpload,
    onFileView,
    onCreateNewErrorCode,
    onResetForm,
    errorCodes,
    errorCodeIcon,
    onErrorCodeIconUpload,
    onErrorCodeIconRemove
}) => {
    const statusValue = Form.useWatch('status', errorCodeForm);

    const handleIconUpload = async (file) => {
        // Check if file is an image
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
            message.error('You can only upload image files!');
            return Upload.LIST_IGNORE;
        }

        // Check file size (max 2MB)
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must be smaller than 2MB!');
            return Upload.LIST_IGNORE;
        }

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

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

            if (iconPath) {
                // Extract folder and filename from the path
                const pathParts = iconPath.split('/');
                const folder = pathParts[0];
                const filename = pathParts.slice(1).join('/');

                onErrorCodeIconUpload({
                    name: file.name,
                    uploadPath: iconPath,
                    url: getFileUrl(folder, filename), // Use the same endpoint as file uploads
                    type_solution: fileType,
                    solutionId: 'icon'
                });
                message.success(`${file.name} uploaded successfully!`);
            } else {
                message.error('Failed to upload icon');
            }
        } catch (error) {
            console.error('Error uploading icon:', error);
            message.error('Failed to upload icon');
        }

        return false; // Prevent default upload behavior
    };

    const handleRemoveIcon = () => {
        onErrorCodeIconRemove();
        message.success('Icon removed');
    };

    const handleAddErrorCode = async () => {
        try {
            const values = await errorCodeForm.validateFields();

            const solutions = [];

            solutionFields.forEach((fieldId) => {
                if (solutionsToDelete && solutionsToDelete.has(fieldId)) {
                    return;
                }

                const solutionName = values[`solution_name_${fieldId}`];
                const textSolution = values[`text_solution_${fieldId}`];
                const filesForSolution = fileList.filter(file => file.solutionId === fieldId);
                const solutionType = values[`solution_type_${fieldId}`] || solutionTypes[fieldId];

                if (solutionType === 'text') {
                    if (textSolution && textSolution.trim()) {
                        const solutionData = {
                            solution_name: solutionName || `Solution ${fieldId}`,
                            type_solution: 'text',
                            text_solution: textSolution.trim(),
                            path_solution: '',
                            is_active: solutionStatuses[fieldId] !== false
                        };

                        if (window.currentSolutionData && window.currentSolutionData[fieldId]) {
                            solutionData.brand_code_solution_id = window.currentSolutionData[fieldId].brand_code_solution_id;
                        }

                        solutions.push(solutionData);
                    }
                } else if (solutionType === 'file') {
                    filesForSolution.forEach((file) => {
                        const solutionData = {
                            solution_name: solutionName || file.solution_name || file.name || `Solution ${fieldId}`,
                            type_solution: file.type_solution || (file.type.startsWith('image/') ? 'image' : 'pdf'),
                            text_solution: '',
                            path_solution: file.uploadPath,
                            is_active: solutionStatuses[fieldId] !== false
                        };

                        if (window.currentSolutionData && window.currentSolutionData[fieldId]) {
                            solutionData.brand_code_solution_id = window.currentSolutionData[fieldId].brand_code_solution_id;
                        }

                        solutions.push(solutionData);
                    });
                }
            });

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

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

            onAddErrorCode(newErrorCode);

        } catch (error) {
            NotifAlert({ icon: 'warning', title: 'Perhatian', message: 'Harap isi semua kolom wajib (error code + minimal 1 solution)!' });
        }
    };

    const handleResetForm = () => {
        errorCodeForm.resetFields();
        errorCodeForm.setFieldsValue({
            status: true,
            solution_status_0: true,
            solution_type_0: 'text'
        });
        onResetForm();
    };

    return (
        <>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                <Form.Item label="Status" style={{ margin: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <Form.Item name="status" valuePropName="checked" noStyle>
                            <Switch
                                style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }}
                                disabled={isErrorCodeFormReadOnly}
                            />
                        </Form.Item>
                        <Text style={{ marginLeft: 8 }}>{statusValue ? 'Running' : 'Offline'}</Text>
                    </div>
                </Form.Item>
                {!isErrorCodeFormReadOnly && (
                    <ConfigProvider
                        theme={{
                            components: {
                                Button: {
                                    defaultBg: '#23a55a',
                                    defaultColor: '#FFFFFF',
                                    defaultBorderColor: '#23a55a',
                                    defaultHoverBg: '#209652',
                                    defaultHoverColor: '#FFFFFF',
                                    defaultHoverBorderColor: '#23a55a',
                                },
                            },
                        }}
                    >
                        <Button
                            icon={<PlusOutlined />}
                            onClick={handleAddErrorCode}
                        >
                            {editingErrorCodeKey ? 'Update Error Code' : 'Tambah Error Code'}
                        </Button>
                    </ConfigProvider>
                )}
            </div>

            <Form.Item name="error_code" label="Error Code" rules={[{ required: true, message: 'Error Code wajib diisi' }]}>
                <Input disabled={isErrorCodeFormReadOnly} />
            </Form.Item>

            <Form.Item name="error_code_name" label="Error Code Name" rules={[{ required: true, message: 'Error Code Name wajib diisi' }]}>
                <Input disabled={isErrorCodeFormReadOnly} />
            </Form.Item>

            <Form.Item name="error_code_color" label="Error Code Color">
                <Input
                    type="color"
                    disabled={isErrorCodeFormReadOnly}
                    style={{ width: 100, height: 40 }}
                />
            </Form.Item>

            <Form.Item label="Error Code Icon">
                <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    {errorCodeIcon ? (
                        <>
                            <img
                                src={errorCodeIcon.url}
                                alt="Error Code Icon"
                                style={{
                                    width: 64,
                                    height: 64,
                                    objectFit: 'cover',
                                    border: '1px solid #d9d9d9',
                                    borderRadius: 4
                                }}
                            />
                            <div>
                                <div style={{ fontSize: 12, color: '#666', marginBottom: 4 }}>
                                    {errorCodeIcon.name}
                                </div>
                                {!isErrorCodeFormReadOnly && (
                                    <Button
                                        size="small"
                                        danger
                                        icon={<DeleteOutlined />}
                                        onClick={handleRemoveIcon}
                                    >
                                        Remove
                                    </Button>
                                )}
                            </div>
                        </>
                    ) : (
                        <Upload
                            accept="image/*"
                            beforeUpload={handleIconUpload}
                            showUploadList={false}
                            disabled={isErrorCodeFormReadOnly}
                        >
                            <Button
                                icon={<UploadOutlined />}
                                disabled={isErrorCodeFormReadOnly}
                            >
                                Upload Icon
                            </Button>
                        </Upload>
                    )}
                </div>
                <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
                    Upload an icon image (max 2MB, JPG/PNG/GIF)
                </div>
            </Form.Item>

            <Form.Item name="error_code_description" label="Error Code Description" rules={[{ required: true, message: 'Error Code Description wajib diisi' }]}>
                <Input.TextArea disabled={isErrorCodeFormReadOnly} />
            </Form.Item>

            <Divider>Solutions</Divider>

            {solutionFields.map((fieldId, index) => (
                <SolutionField
                    key={fieldId}
                    fieldId={fieldId}
                    index={index}
                    solutionType={solutionTypes[fieldId]}
                    solutionStatus={solutionStatuses[fieldId]}
                    isReadOnly={isErrorCodeFormReadOnly}
                    fileList={fileList.filter(file => file.solutionId === fieldId)}
                    onRemove={() => onRemoveSolutionField(fieldId)}
                    onSolutionTypeChange={(type) => onSolutionTypeChange(fieldId, type)}
                    onSolutionStatusChange={(status) => onSolutionStatusChange(fieldId, status)}
                    onFileUpload={onSolutionFileUpload}
                    currentSolutionData={window.currentSolutionData?.[fieldId] || null}
                    onFileView={onFileView}
                    errorCodeForm={errorCodeForm}
                />
            ))}

            {!isErrorCodeFormReadOnly && (
                <Form.Item style={{ textAlign: 'center' }}>
                    <Button
                        icon={<PlusOutlined />}
                        onClick={onAddSolutionField}
                        style={{ width: '100%' }}
                    >
                        Add More Solution
                    </Button>
                </Form.Item>
            )}

            {!isErrorCodeFormReadOnly && editingErrorCodeKey && (
                <Form.Item style={{ textAlign: 'right', marginTop: 16 }}>
                    <Button onClick={handleResetForm}>
                        Kembali
                    </Button>
                </Form.Item>
            )}

            {isErrorCodeFormReadOnly && editingErrorCodeKey && (
                <Form.Item style={{ textAlign: 'right', marginTop: 16 }}>
                    <Button onClick={handleResetForm}>
                        Kembali
                    </Button>
                </Form.Item>
            )}
        </>
    );
};

export default ErrorCodeForm;