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

const { Text } = Typography;
const { TextArea } = Input;

const SolutionFieldNew = ({
    fieldKey,
    fieldName,
    index,
    solutionType,
    solutionStatus,
    isReadOnly = false,
    canRemove = true,
    onTypeChange,
    onStatusChange,
    onRemove,
    onFileUpload,
    onFileView,
    fileList = []
}) => {
    const [currentStatus, setCurrentStatus] = useState(solutionStatus ?? true);

    // Watch form values
    const getFieldValue = () => {
        try {
            const form = document.querySelector(`[data-field="${fieldName}"]`)?.form;
            if (form) {
                const formData = new FormData(form);
                return formData.get(`${fieldName}.status`) === 'on';
            }
            return currentStatus;
        } catch {
            return currentStatus;
        }
    };

    useEffect(() => {
        setCurrentStatus(solutionStatus ?? true);
    }, [solutionStatus]);
    const handleFileUpload = 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) {
                // Store the file info with the solution field
                file.uploadPath = actualPath;
                file.solutionId = fieldKey;
                file.type_solution = fileType;
                onFileUpload(file);
                NotifAlert({
                    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 renderSolutionContent = () => {
        if (solutionType === 'text') {
            return (
                <Form.Item
                    name={[fieldName, 'text']}
                    rules={[{ required: true, message: 'Text solution wajib diisi!' }]}
                >
                    <TextArea
                        placeholder="Enter solution text"
                        rows={3}
                        disabled={isReadOnly}
                    />
                </Form.Item>
            );
        }

        if (solutionType === 'file') {
            const currentFiles = fileList.filter(file => file.solutionId === fieldKey);

            return (
                <div>
                    <Form.Item
                        name={[fieldName, 'file']}
                        rules={[{ required: true, message: 'File solution wajib diupload!' }]}
                    >
                        <Upload
                            beforeUpload={handleFileUpload}
                            showUploadList={false}
                            accept=".pdf,.jpg,.jpeg,.png,.gif"
                            disabled={isReadOnly}
                        >
                            <Button
                                icon={<UploadOutlined />}
                                disabled={isReadOnly}
                                style={{ width: '100%' }}
                            >
                                Upload File (PDF/Image)
                            </Button>
                        </Upload>
                    </Form.Item>

                    {currentFiles.length > 0 && (
                        <div style={{ marginTop: 8 }}>
                            {currentFiles.map((file, index) => (
                                <div key={index} style={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'center',
                                    padding: '4px 8px',
                                    border: '1px solid #d9d9d9',
                                    borderRadius: 4,
                                    marginBottom: 4
                                }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                        <Text style={{ fontSize: 12 }}>{file.name}</Text>
                                        <Text type="secondary" style={{ fontSize: 10 }}>
                                            ({(file.size / 1024).toFixed(1)} KB)
                                        </Text>
                                    </div>
                                    <Button
                                        type="text"
                                        size="small"
                                        icon={<EyeOutlined />}
                                        onClick={() => onFileView(file.uploadPath, file.type_solution)}
                                    />
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            );
        }

        return null;
    };

    return (
        <div style={{
            border: '1px solid #d9d9d9',
            borderRadius: 8,
            padding: 16,
            marginBottom: 16,
            backgroundColor: isReadOnly ? '#f5f5f5' : 'white'
        }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <Text strong>Solution #{index + 1}</Text>
                <Space>
                    <Form.Item
                        name={[fieldName, 'name']}
                        rules={[{ required: true, message: 'Solution name wajib diisi!' }]}
                        style={{ margin: 0, width: 200 }}
                    >
                        <Input
                            placeholder="Solution name"
                            disabled={isReadOnly}
                        />
                    </Form.Item>

                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                        <Form.Item name={[fieldName, 'status']} valuePropName="checked" noStyle>
                            <Switch
                                disabled={isReadOnly}
                                onChange={(checked) => {
                                    onStatusChange(fieldKey, checked);
                                    setCurrentStatus(checked);
                                }}
                                style={{
                                    backgroundColor: currentStatus ? '#23A55A' : '#bfbfbf'
                                }}
                            />
                        </Form.Item>
                        <Text style={{ fontSize: 12, color: '#666' }}>
                            {currentStatus ? 'Active' : 'Inactive'}
                        </Text>
                    </div>

                    {canRemove && !isReadOnly && (
                        <Button
                            type="text"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={onRemove}
                        />
                    )}
                </Space>
            </div>

            <Form.Item
                name={[fieldName, 'type']}
                rules={[{ required: true, message: 'Solution type wajib diisi!' }]}
            >
                <Radio.Group
                    onChange={(e) => onTypeChange(fieldKey, e.target.value)}
                    disabled={isReadOnly}
                >
                    <Radio value="text">Text Solution</Radio>
                    <Radio value="file">File Solution</Radio>
                </Radio.Group>
            </Form.Item>

            {renderSolutionContent()}
        </div>
    );
};

export default SolutionFieldNew;