import { Form, Input, Switch, Upload, Button, Typography, message, ConfigProvider } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '../../../../api/file-uploads';

const { Text } = Typography;

const ErrorCodeSimpleForm = ({
    errorCodeForm,
    isErrorCodeFormReadOnly = false,
    errorCodeIcon,
    onErrorCodeIconUpload,
    onErrorCodeIconRemove,
    onAddErrorCode,
}) => {
    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) {
                onErrorCodeIconUpload({
                    name: file.name,
                    uploadPath: iconPath,
                    fileExtension,
                    isImage: isImageFile,
                    size: file.size,
                });
                message.success(`${file.name} uploaded successfully!`);
            } else {
                message.error(`Failed to upload ${file.name}`);
            }
        } catch (error) {
            console.error('Error uploading icon:', error);
            message.error(`Failed to upload ${file.name}`);
        }
    };

    const handleIconRemove = () => {
        onErrorCodeIconRemove();
    };

    return (
        <>
            {/* Status Switch */}
            <Form.Item label="Status" name="status">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Form.Item name="status" valuePropName="checked" noStyle>
                        <Switch
                            disabled={isErrorCodeFormReadOnly}
                            style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }}
                        />
                    </Form.Item>
                    <Text style={{ marginLeft: 8 }}>{statusValue ? 'Active' : 'Inactive'}</Text>
                </div>
            </Form.Item>

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

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

            {/* Error Description */}
            <Form.Item label="Description" name="error_code_description">
                <Input.TextArea
                    placeholder="Enter error description"
                    rows={3}
                    disabled={isErrorCodeFormReadOnly}
                />
            </Form.Item>

            {/* Color and Icon in same row */}
            <Form.Item label="Color & Icon">
                <Input.Group compact>
                    <Form.Item name="error_code_color" noStyle>
                        <input
                            type="color"
                            disabled={isErrorCodeFormReadOnly}
                            style={{
                                width: '30%',
                                height: '40px',
                                border: '1px solid #d9d9d9',
                                borderRadius: 4,
                            }}
                            defaultValue="#000000"
                        />
                    </Form.Item>

                    <Form.Item noStyle style={{ width: '70%', paddingLeft: 8 }}>
                        {!isErrorCodeFormReadOnly ? (
                            <Upload
                                beforeUpload={handleIconUpload}
                                showUploadList={false}
                                accept="image/*"
                                style={{ width: '100%' }}
                            >
                                <Button icon={<UploadOutlined />} style={{ width: '100%' }}>
                                    Upload Icon
                                </Button>
                            </Upload>
                        ) : (
                            <div
                                style={{
                                    padding: '8px 12px',
                                    border: '1px solid #d9d9d9',
                                    borderRadius: 4,
                                }}
                            >
                                <Text type="secondary">No upload allowed</Text>
                            </div>
                        )}
                    </Form.Item>
                </Input.Group>

                {errorCodeIcon && (
                    <div style={{ marginTop: 8 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <img
                                src={errorCodeIcon.uploadPath}
                                alt="Error Code Icon"
                                style={{
                                    width: 50,
                                    height: 50,
                                    objectFit: 'cover',
                                    border: '1px solid #d9d9d9',
                                    borderRadius: 4,
                                }}
                            />
                            <div>
                                <Text style={{ fontSize: 12 }}>{errorCodeIcon.name}</Text>
                                <br />
                                <Text type="secondary" style={{ fontSize: 10 }}>
                                    Size: {(errorCodeIcon.size / 1024).toFixed(1)} KB
                                </Text>
                            </div>
                            {!isErrorCodeFormReadOnly && (
                                <Button type="text" danger size="small" onClick={handleIconRemove}>
                                    Remove
                                </Button>
                            )}
                        </div>
                    </div>
                )}
            </Form.Item>

            {/* Add Error Code Button */}
            {!isErrorCodeFormReadOnly && (
                <Form.Item>
                    <ConfigProvider
                        theme={{
                            token: { colorBgContainer: '#23a55ade' },
                            components: {
                                Button: {
                                    defaultBg: '#23a55a',
                                    defaultColor: '#FFFFFF',
                                    defaultBorderColor: '#23a55a',
                                    defaultHoverBg: '#209652',
                                    defaultHoverColor: '#FFFFFF',
                                    defaultHoverBorderColor: '#23a55a',
                                },
                            },
                        }}
                    >
                        <Button
                            htmlType="button"
                            onClick={() => {
                                // Call parent function to add error code
                                onAddErrorCode();
                            }}
                            style={{ width: '100%' }}
                        >
                            Simpan Error Code
                        </Button>
                    </ConfigProvider>
                </Form.Item>
            )}
        </>
    );
};

export default ErrorCodeSimpleForm;
