import { Modal, Form, Input, Select, Radio, Alert, Divider } from 'antd';
import { Comment, Library, Reader, Book } from './types';
import React, { useState, useEffect } from 'react';
import { api } from '@nice/client';

const { TextArea } = Input;

interface CommentModalProps {
    open: boolean;
    loading?: boolean;
    editingRecord?: Comment;
    onOk: (values: any) => void;
    onCancel: () => void;
}

export const CommentModal: React.FC<CommentModalProps> = ({
    open,
    loading,
    editingRecord,
    onOk,
    onCancel,
}) => {
    const [form] = Form.useForm();
    const [commentType, setCommentType] = useState<'book' | 'library'>('book');
    const [selectedLibraryId, setSelectedLibraryId] = useState<string>('');
    const [selectedReaderId, setSelectedReaderId] = useState<string>('');
console.log(editingRecord);

    // 查询所有图书馆
    const { data: libraryList } = api.library.findMany.useQuery({
        where: { deletedAt: null },
    });

    // 查询所有读者
    const { data: readerList } = api.reader.findMany.useQuery({
        where: {
            deletedAt: null,
        },
    });

    // 根据选择的图书馆筛选图书
    const { data: bookList } = api.book.findMany.useQuery({
        where: {
            deletedAt: null,
            libraryId: selectedLibraryId || undefined
        },
        include: { library: true }
    }, {
        enabled: !!selectedLibraryId && commentType === 'book'
    });

    // 初始化表单数据
    useEffect(() => {
        if (editingRecord && open) {
            // 判断评论类型
            const type = editingRecord.bookId ? 'book' : 'library';
            setCommentType(type);
            setSelectedLibraryId(type === 'book' ? editingRecord.book?.libraryId : editingRecord.libraryId);
            setSelectedReaderId(editingRecord.readerId);

            form.setFieldsValue({
                content: editingRecord.content,
                readerId: editingRecord.readerId,
                commentType: type,
                libraryId: type === 'library' ? editingRecord.libraryId : undefined,
                bookId: type === 'book' ? editingRecord.bookId : undefined,
            });
        } else if (!editingRecord && open) {
            form.resetFields();
            setCommentType('book');
            setSelectedLibraryId('');
            setSelectedReaderId('');
        }
    }, [editingRecord, open, form]);

    // 处理评论类型变化
    const handleCommentTypeChange = (e: any) => {
        const type = e.target.value;
        setCommentType(type);
        // 清空相关字段
        if (type === 'book') {
            form.setFieldsValue({ libraryId: undefined });
        } else {
            form.setFieldsValue({ bookId: undefined });
        }
    };

    // 处理图书馆选择变化
    const handleLibraryChange = (value: string) => {
        setSelectedLibraryId(value);
        // 如果是图书评论，清空图书选择
        if (commentType === 'book') {
            form.setFieldsValue({ bookId: undefined });
        }
    };

    return (
        <Modal
            title={editingRecord ? '编辑评论' : '添加评论'}
            open={open}
            onOk={() => form.submit()}
            onCancel={onCancel}
            confirmLoading={loading}
            width={600}
        >
            <Form
                form={form}
                layout="vertical"
                onFinish={(values) => {
                    // 根据评论类型处理数据
                    const formData = {
                        ...values,
                        libraryId: values.commentType === 'library' ? values.libraryId : null,
                        bookId: values.commentType === 'book' ? values.bookId : null,
                    };
                    onOk(formData);
                }}
            >
                <Form.Item
                    name="readerId"
                    label="评论人"
                    rules={[{ required: true, message: '请选择评论人' }]}
                >
                    <Select
                        placeholder="请选择评论人"
                        showSearch
                        optionFilterProp="children"
                    >
                        {readerList?.map(reader => (
                            <Select.Option key={reader.id} value={reader.id}>
                                {reader.name} ({reader.username})
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>

                <Divider>评论对象</Divider>

                <Form.Item
                    name="commentType"
                    label="评论类型"
                    rules={[{ required: true, message: '请选择评论类型' }]}
                    initialValue="book"
                >
                    <Radio.Group onChange={handleCommentTypeChange}>
                        <Radio value="book">图书评论</Radio>
                        <Radio value="library">图书馆评论</Radio>
                    </Radio.Group>
                </Form.Item>

                {commentType === 'book' ? (
                    <>
                        <Form.Item
                            name="libraryId"
                            label="图书所属图书馆"
                            rules={[{ required: true, message: '请选择图书馆' }]}
                        >
                            <Select
                                placeholder="请选择图书馆"
                                onChange={handleLibraryChange}
                            >
                                {libraryList?.map(library => (
                                    <Select.Option key={library.id} value={library.id}>
                                        {library.name}
                                    </Select.Option>
                                ))}
                            </Select>
                        </Form.Item>

                        {!selectedLibraryId && (
                            <Alert
                                message="请先选择图书馆"
                                type="info"
                                showIcon
                                style={{ marginBottom: 16 }}
                            />
                        )}

                        <Form.Item
                            name="bookId"
                            label="评论图书"
                            rules={[{ required: true, message: '请选择图书' }]}
                        >
                            <Select
                                placeholder="请选择图书"
                                disabled={!selectedLibraryId}
                                showSearch
                                optionFilterProp="children"
                            >
                                {bookList?.map(book => (
                                    <Select.Option key={book.id} value={book.id}>
                                        {book.bookName} (ISBN: {book.isbn})
                                    </Select.Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </>
                ) : (
                    <Form.Item
                        name="libraryId"
                        label="评论图书馆"
                        rules={[{ required: true, message: '请选择图书馆' }]}
                    >
                        <Select
                            placeholder="请选择图书馆"
                            onChange={handleLibraryChange}
                        >
                            {libraryList?.map(library => (
                                <Select.Option key={library.id} value={library.id}>
                                    {library.name}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                )}

                <Divider>评论内容</Divider>

                <Form.Item
                    name="content"
                    label="评论内容"
                    rules={[{ required: true, message: '请输入评论内容' }]}
                >
                    <TextArea
                        rows={4}
                        placeholder="请输入您的评论内容..."
                        showCount
                        maxLength={500}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
};