import React, { useEffect, useState } from 'react';
import { Form, Input, InputNumber, Select, Button, Card, Space, Upload, message, Checkbox, Tag, Alert } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { PlusOutlined } from '@ant-design/icons';
import { createRoom, updateRoom, getMerchantRoom } from '@/api/room';

const { TextArea } = Input;
const { Option } = Select;

const facilityOptions = [
  'WiFi', '空调', '热水', '电视', '冰箱', '洗衣机',
  '停车场', '电梯', '厨房', '阳台', '泳池', '健身房',
];

const RoomForm: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { id } = useParams();
  const [loading, setLoading] = useState(false);
  const [imageList, setImageList] = useState<any[]>([]);
  const [auditStatus, setAuditStatus] = useState<string>('');
  const [rejectReason, setRejectReason] = useState<string>('');
  useEffect(() => {
    if (id) {
      getMerchantRoom(Number(id)).then((res: any) => {
        const room = res.data;
        form.setFieldsValue({
          ...room,
          facilities: room.facilities || [],
        });
        if (room.images?.length) {
          setImageList(room.images.map((url: string, i: number) => ({ uid: String(i), url, status: 'done' })));
        }
        setAuditStatus(room.auditStatus || '');
        setRejectReason(room.auditRejectReason || '');
      });
    }
  }, [id]);

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const data = {
        ...values,
        images: imageList.map((f) => f.url || f.response?.url).filter(Boolean),
        coverImage: values.coverImage || imageList[0]?.url || '',
      };
      if (id) {
        await updateRoom(Number(id), data);
        message.success('更新成功');
      } else {
        await createRoom(data);
        message.success('创建成功');
      }
      navigate('/rooms');
    } catch (e: any) {
      message.error(e.message || '操作失败');
    } finally {
      setLoading(false);
    }
  };

  const handleUploadChange = ({ fileList }: any) => {
    setImageList(fileList);
  };

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>{id ? '编辑房源' : '添加房源'}</h2>
      {id && auditStatus && (
        <div style={{ marginBottom: 16 }}>
          <Space>
            <span>审核状态：</span>
            <Tag color={auditStatus === 'approved' ? 'green' : auditStatus === 'rejected' ? 'red' : 'orange'}>
              {auditStatus === 'approved' ? '已通过' : auditStatus === 'rejected' ? '已拒绝' : '审核中'}
            </Tag>
          </Space>
          {auditStatus === 'rejected' && rejectReason && (
            <Alert type="error" message={`拒绝原因：${rejectReason}`} style={{ marginTop: 8 }} showIcon />
          )}
        </div>
      )}
      <Card>
        <Form form={form} layout="vertical" onFinish={onFinish} style={{ maxWidth: 700 }}
          initialValues={{ type: 'hotel', cancelPolicy: 'flexible', maxGuests: 1, area: 0, facilities: [] }}
        >
          <Form.Item name="name" label="房源名称" rules={[{ required: true, message: '请输入房源名称' }]}>
            <Input placeholder="请输入房源名称" maxLength={100} />
          </Form.Item>
          <Space style={{ width: '100%' }} size="large">
            <Form.Item name="type" label="类型" rules={[{ required: true }]} style={{ width: 200 }}>
              <Select>
                <Option value="hotel">酒店</Option>
                <Option value="homestay">民宿</Option>
                <Option value="apartment">公寓</Option>
                <Option value="hostel">青旅</Option>
              </Select>
            </Form.Item>
            <Form.Item name="price" label="价格/晚" rules={[{ required: true }]} style={{ width: 200 }}>
              <InputNumber min={0} precision={2} style={{ width: '100%' }} addonAfter="元" />
            </Form.Item>
          </Space>
          <Space style={{ width: '100%' }} size="large">
            <Form.Item name="bedType" label="床型" style={{ width: 200 }}>
              <Input placeholder="如：大床/双床" />
            </Form.Item>
            <Form.Item name="area" label="面积(m²)" style={{ width: 200 }}>
              <InputNumber min={0} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="maxGuests" label="最多入住" style={{ width: 200 }}>
              <InputNumber min={1} style={{ width: '100%' }} addonAfter="人" />
            </Form.Item>
          </Space>
          <Form.Item name="cancelPolicy" label="取消政策" style={{ width: 200 }}>
            <Select>
              <Option value="free">免费取消</Option>
              <Option value="flexible">灵活取消</Option>
              <Option value="strict">严格取消</Option>
            </Select>
          </Form.Item>

          <Form.Item label="房源图片">
            <Upload
              listType="picture-card"
              fileList={imageList}
              onChange={handleUploadChange}
              beforeUpload={() => false}
              multiple
            >
              {imageList.length < 20 && (
                <div><PlusOutlined /><div style={{ marginTop: 8, fontSize: 12 }}>上传</div></div>
              )}
            </Upload>
            <div style={{ color: '#999', fontSize: 12 }}>第一张图将作为封面，最多20张</div>
          </Form.Item>

          <Form.Item name="facilities" label="设施服务">
            <Checkbox.Group options={facilityOptions} />
          </Form.Item>

          <Form.Item name="description" label="房源描述">
            <TextArea rows={4} placeholder="请描述房源特色" maxLength={1000} showCount />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>保存</Button>
              <Button onClick={() => navigate('/rooms')}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default RoomForm;
