import React, { useEffect } from 'react';
import { Form, Input, Button, Switch, Radio, Upload, Typography } from 'antd';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { uploadFile, getFolderFromFileType } from '../../../../api/file-uploads';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';

const { Text } = Typography;

const SolutionField = ({
    fieldId,
    index,
    solutionStatus,
    isReadOnly,
    fileList,
    onRemove,
    onSolutionTypeChange,
    onSolutionStatusChange,
    onFileUpload,
    currentSolutionData,
    onFileView,
    errorCodeForm,
}) => {
    useEffect(() => {
        if (currentSolutionData && errorCodeForm) {
            if (currentSolutionData.solution_name) {
                errorCodeForm.setFieldValue(
                    `solution_name_${fieldId}`,
                    currentSolutionData.solution_name
                );
            }

            if (currentSolutionData.type_solution === 'text' && currentSolutionData.text_solution) {
                errorCodeForm.setFieldValue(
                    `text_solution_${fieldId}`,
                    currentSolutionData.text_solution
                );
            }

            if (currentSolutionData.type_solution) {
                const formValue =
                    currentSolutionData.type_solution === 'image' ||
                    currentSolutionData.type_solution === 'pdf'
                        ? 'file'
                        : currentSolutionData.type_solution;
                errorCodeForm.setFieldValue(`solution_type_${fieldId}`, formValue);
            }

            // Only set status if it's not already set to prevent overwriting user changes
            const currentStatus = errorCodeForm.getFieldValue(`solution_status_${fieldId}`);
            if (currentSolutionData.is_active !== undefined && currentStatus === undefined) {
                errorCodeForm.setFieldValue(
                    `solution_status_${fieldId}`,
                    currentSolutionData.is_active
                );
            }
        }
    }, [currentSolutionData, fieldId, errorCodeForm]);

    const handleBeforeUpload = async (file) => {
        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 Upload.LIST_IGNORE;
        }

        try {
            // Upload file immediately to get path
            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 = fieldId;
                file.type_solution = fileType;
                onFileUpload(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.`,
            });
        }

        return false;
    };

    return (
        <div
            data-solution-id={fieldId}
            style={{
                marginBottom: 24,
                padding: 16,
                border: '1px solid #d9d9d9',
                borderRadius: 8,
                transition: 'all 0.3s ease',
            }}
        >
            <div
                style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: 12,
                }}
            >
                <Text strong>Solution {index + 1}</Text>
                <Button
                    type="text"
                    danger
                    size="small"
                    icon={<DeleteOutlined />}
                    onClick={() => onRemove(fieldId)}
                    disabled={isReadOnly}
                    style={{ borderColor: '#ff4d4f' }}
                />
            </div>

            <Form.Item name={`solution_name_${fieldId}`} label="Solution Name">
                <Input placeholder="Enter solution name" disabled={isReadOnly} />
            </Form.Item>

            <Form.Item label="Status">
                <Form.Item
                    shouldUpdate={(prevValues, currentValues) =>
                        prevValues[`solution_status_${fieldId}`] !==
                        currentValues[`solution_status_${fieldId}`]
                    }
                    noStyle
                >
                    {({ getFieldValue, setFieldValue }) => {
                        const currentStatus = getFieldValue(`solution_status_${fieldId}`);
                        return (
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <Switch
                                    checked={currentStatus === true}
                                    onChange={(checked) => {
                                        setFieldValue(`solution_status_${fieldId}`, checked);
                                    }}
                                    disabled={isReadOnly}
                                    style={{
                                        backgroundColor: solutionStatus ? '#23A55A' : '#bfbfbf',
                                    }}
                                />
                                <Text style={{ marginLeft: 8 }}>
                                    {currentStatus === true ? 'Active' : 'Non Active'}
                                </Text>
                            </div>
                        );
                    }}
                </Form.Item>
            </Form.Item>

            <Form.Item label="Solution Type">
                <Form.Item name={`solution_type_${fieldId}`} noStyle>
                    <Radio.Group
                        onChange={(e) => {
                            onSolutionTypeChange(fieldId, e.target.value);
                        }}
                        disabled={isReadOnly}
                    >
                        <Radio value="text">Text Solution</Radio>
                        <Radio value="file">File Upload</Radio>
                    </Radio.Group>
                </Form.Item>
            </Form.Item>

            <Form.Item
                shouldUpdate={(prevValues, currentValues) =>
                    prevValues[`solution_type_${fieldId}`] !==
                    currentValues[`solution_type_${fieldId}`]
                }
                noStyle
            >
                {({ getFieldValue }) => {
                    const currentType = getFieldValue(`solution_type_${fieldId}`) || 'text';
                    const displayType =
                        currentType === 'file' && currentSolutionData
                            ? currentSolutionData.type_solution === 'image'
                                ? 'image'
                                : currentSolutionData.type_solution === 'pdf'
                                ? 'pdf'
                                : 'file'
                            : currentType;

                    return displayType === 'text' ? (
                        <Form.Item name={`text_solution_${fieldId}`} label="Text Solution">
                            <Input.TextArea
                                placeholder="Enter text solution"
                                disabled={isReadOnly}
                                rows={4}
                            />
                        </Form.Item>
                    ) : (
                        <>
                            {/* Show existing file info for both preview and edit mode */}
                            {currentSolutionData &&
                                currentSolutionData.type_solution !== 'text' &&
                                currentSolutionData.path_solution && (
                                    <Form.Item label="Current Document">
                                        {(() => {
                                            const solution = currentSolutionData;
                                            const fileName =
                                                solution.file_upload_name ||
                                                solution.path_solution?.split('/')[1] ||
                                                'File';
                                            const fileType = solution.type_solution;

                                            if (fileType !== 'text' && solution.path_solution) {
                                                return (
                                                    <div
                                                        style={{
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            gap: '8px',
                                                            marginBottom: '8px',
                                                        }}
                                                    >
                                                        <Text>
                                                            {fileType === 'image'
                                                                ? '[Image]'
                                                                : '[Document]'}{' '}
                                                            {fileName}
                                                        </Text>
                                                        <Button
                                                            type="link"
                                                            size="small"
                                                            onClick={() =>
                                                                onFileView(
                                                                    solution.path_solution,
                                                                    solution.type_solution
                                                                )
                                                            }
                                                            style={{
                                                                padding: 0,
                                                                height: 'auto',
                                                                fontSize: '12px',
                                                            }}
                                                        >
                                                            View Document
                                                        </Button>
                                                    </div>
                                                );
                                            }
                                            return null;
                                        })()}
                                    </Form.Item>
                                )}

                            <Form.Item label="Upload File">
                                <Upload
                                    multiple={true}
                                    accept=".pdf,.jpg,.jpeg,.png,.gif"
                                    disabled={isReadOnly}
                                    fileList={[
                                        ...fileList.filter((file) => file.solutionId === fieldId),
                                        // Add existing file to fileList if it exists
                                        ...(currentSolutionData &&
                                        currentSolutionData.type_solution !== 'text' &&
                                        currentSolutionData.path_solution
                                            ? [
                                                  {
                                                      uid: `existing-${fieldId}`,
                                                      name:
                                                          currentSolutionData.file_upload_name ||
                                                          currentSolutionData.path_solution?.split(
                                                              '/'
                                                          )[1] ||
                                                          'File',
                                                      status: 'done',
                                                      url: null, // We'll use the path_solution for viewing
                                                      solutionId: fieldId,
                                                      type_solution:
                                                          currentSolutionData.type_solution,
                                                      uploadPath: currentSolutionData.path_solution,
                                                      existingFile: true,
                                                  },
                                              ]
                                            : []),
                                    ]}
                                    onRemove={(file) => {}}
                                    beforeUpload={handleBeforeUpload}
                                >
                                    <Button icon={<UploadOutlined />} disabled={isReadOnly}>
                                        Click to Upload (File or Image)
                                    </Button>
                                </Upload>
                            </Form.Item>
                        </>
                    );
                }}
            </Form.Item>
        </div>
    );
};

export default SolutionField;
