import React, { useState, useEffect } from 'react';
import { Card, Descriptions, Form, Input, Button, message, Tag, Space, Modal, Radio, Tabs, Image, Alert } from 'antd';
import {
  ShopOutlined,
  PhoneOutlined,
  EnvironmentOutlined,
  EditOutlined,
  PictureOutlined,
  IdcardOutlined,
  BankOutlined,
} from '@ant-design/icons';
import { getMerchantInfo, updateMerchantProfile } from '@/api/auth';

const { TabPane } = Tabs;

const statusMap: Record<string, { color: string; text: string }> = {
  pending: { color: 'gold', text: '审核中' },
  approved: { color: 'green', text: '营业中' },
  rejected: { color: 'red', text: '已拒绝' },
  frozen: { color: 'default', text: '已冻结' },
};

const Settings: React.FC = () => {
  const [merchant, setMerchant] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchMerchant();
  }, []);

  async function fetchMerchant() {
    try {
      const res: any = await getMerchantInfo();
      setMerchant(res.data);
    } catch {
      message.error('获取店铺信息失败');
    }
  }

  function openEdit() {
    form.setFieldsValue({
      shopName: merchant?.shopName,
      phone: merchant?.phone,
      province: merchant?.province,
      city: merchant?.city,
      district: merchant?.district,
      address: merchant?.address,
      description: merchant?.description,
      logo: merchant?.logo,
      coverImage: merchant?.coverImage,
      licenseNo: merchant?.licenseNo,
      legalPerson: merchant?.legalPerson,
      businessLicense: merchant?.businessLicense,
    });
    setEditOpen(true);
  }

  async function handleUpdate() {
    const values = await form.validateFields();
    setLoading(true);
    try {
      await updateMerchantProfile(values);
      message.success('保存成功，修改后需重新审核');
      setEditOpen(false);
      fetchMerchant();
    } catch (e: any) {
      message.error(e.message || '保存失败');
    } finally {
      setLoading(false);
    }
  }

  if (!merchant) {
    return <div style={{ textAlign: 'center', padding: 80, color: '#999' }}>加载中...</div>;
  }

  const status = statusMap[merchant.status] || { color: 'default', text: merchant.status };
  const hotelImagesArray = merchant.hotelImages ? merchant.hotelImages.split(',').filter(Boolean) : [];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h2 style={{ margin: 0 }}>店铺设置</h2>
        {(merchant.status === 'approved' || merchant.status === 'rejected') && (
          <Button type="primary" icon={<EditOutlined />} onClick={openEdit}>
            修改店铺信息
          </Button>
        )}
      </div>

      {/* 店铺状态 */}
      <Card style={{ marginBottom: 24 }}>
        <Descriptions column={1}>
          <Descriptions.Item label="店铺名称">
            <Space>
              <ShopOutlined />
              {merchant.shopName}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="店铺状态">
            <Tag color={status.color}>{status.text}</Tag>
          </Descriptions.Item>
          {merchant.status === 'rejected' && merchant.rejectReason && (
            <Descriptions.Item label="拒绝原因">
              <span style={{ color: '#ff4d4f' }}>{merchant.rejectReason}</span>
            </Descriptions.Item>
          )}
          {merchant.status === 'pending' && (
            <Descriptions.Item>
              <span style={{ color: '#faad14' }}>店铺信息审核中，暂不可修改</span>
            </Descriptions.Item>
          )}
          {merchant.status === 'frozen' && (
            <Descriptions.Item>
              <span style={{ color: '#999' }}>店铺已被冻结，请联系平台客服</span>
            </Descriptions.Item>
          )}
          <Descriptions.Item label="店铺评分">{merchant.rating} 分（{merchant.reviewCount} 条评价）</Descriptions.Item>
        </Descriptions>
      </Card>

      {/* 基本信息 */}
      <Card title={<><ShopOutlined /> 基本信息</>} style={{ marginBottom: 24 }}>
        <Descriptions column={2}>
          <Descriptions.Item label="店铺Logo" span={2}>
            {merchant.logo ? (
              <Image src={merchant.logo} width={80} height={80} style={{ objectFit: 'cover', borderRadius: 8 }} />
            ) : (
              <span style={{ color: '#999' }}>未上传</span>
            )}
          </Descriptions.Item>
          <Descriptions.Item label="店铺封面" span={2}>
            {merchant.coverImage ? (
              <Image src={merchant.coverImage} width={200} height={120} style={{ objectFit: 'cover', borderRadius: 8 }} />
            ) : (
              <span style={{ color: '#999' }}>未上传</span>
            )}
          </Descriptions.Item>
          <Descriptions.Item label="联系电话">
            <Space><PhoneOutlined />{merchant.phone}</Space>
          </Descriptions.Item>
          <Descriptions.Item label="法人姓名">{merchant.legalPerson || '-'}</Descriptions.Item>
          <Descriptions.Item label="所在地区">
            <Space><EnvironmentOutlined />{merchant.province} {merchant.city} {merchant.district}</Space>
          </Descriptions.Item>
          <Descriptions.Item label="详细地址">{merchant.address || '-'}</Descriptions.Item>
          <Descriptions.Item label="营业执照编号">{merchant.licenseNo || '-'}</Descriptions.Item>
          <Descriptions.Item label="保证金">¥{merchant.deposit}</Descriptions.Item>
          <Descriptions.Item label="店铺描述" span={2}>{merchant.description || '-'}</Descriptions.Item>
        </Descriptions>
      </Card>

      {/* 店铺照片 */}
      {hotelImagesArray.length > 0 && (
        <Card title={<><PictureOutlined /> 店铺照片</>} style={{ marginBottom: 24 }}>
          <Image.PreviewGroup>
            <Space wrap>
              {hotelImagesArray.map((img: string, index: number) => (
                <Image key={index} src={img} width={120} height={120} style={{ objectFit: 'cover', borderRadius: 8 }} />
              ))}
            </Space>
          </Image.PreviewGroup>
        </Card>
      )}

      {/* 资质信息 */}
      <Card title={<><IdcardOutlined /> 资质信息</>} style={{ marginBottom: 24 }}>
        <Descriptions column={2}>
          <Descriptions.Item label="签约类型">
            {merchant.contractType === 'personal' ? '个人签约' : '公司/法人签约'}
          </Descriptions.Item>
          <Descriptions.Item label="门店营业执照">
            {merchant.storeLicense ? (
              <Image src={merchant.storeLicense} width={100} />
            ) : (
              <span style={{ color: '#999' }}>未上传</span>
            )}
          </Descriptions.Item>
          {merchant.contractType === 'personal' ? (
            <>
              <Descriptions.Item label="身份证正面">
                {merchant.idCardFront ? (
                  <Image src={merchant.idCardFront} width={100} />
                ) : (
                  <span style={{ color: '#999' }}>未上传</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="身份证反面">
                {merchant.idCardBack ? (
                  <Image src={merchant.idCardBack} width={100} />
                ) : (
                  <span style={{ color: '#999' }}>未上传</span>
                )}
              </Descriptions.Item>
            </>
          ) : (
            <>
              <Descriptions.Item label="营业执照">
                {merchant.businessLicense ? (
                  <Image src={merchant.businessLicense} width={100} />
                ) : (
                  <span style={{ color: '#999' }}>未上传</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="法人身份证正面">
                {merchant.legalIdCardFront ? (
                  <Image src={merchant.legalIdCardFront} width={100} />
                ) : (
                  <span style={{ color: '#999' }}>未上传</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="法人身份证反面">
                {merchant.legalIdCardBack ? (
                  <Image src={merchant.legalIdCardBack} width={100} />
                ) : (
                  <span style={{ color: '#999' }}>未上传</span>
                )}
              </Descriptions.Item>
            </>
          )}
        </Descriptions>
      </Card>

      {/* 银行信息 */}
      <Card title={<><BankOutlined /> 银行信息</>} style={{ marginBottom: 24 }}>
        <Descriptions column={2}>
          <Descriptions.Item label="账户类型">
            {merchant.accountType === 'company' ? '对公账户' : '对私账户'}
          </Descriptions.Item>
          <Descriptions.Item label="开户银行">{merchant.bankName || '-'}</Descriptions.Item>
          <Descriptions.Item label="银行账号">{merchant.bankAccount || '-'}</Descriptions.Item>
          <Descriptions.Item label="账户名">{merchant.accountName || '-'}</Descriptions.Item>
          {merchant.accountType === 'personal' && (
            <Descriptions.Item label="支行信息">{merchant.bankBranch || '-'}</Descriptions.Item>
          )}
          {merchant.accountType === 'company' && merchant.bankLicense && (
            <Descriptions.Item label="开户营业执照">
              <Image src={merchant.bankLicense} width={100} />
            </Descriptions.Item>
          )}
          {merchant.accountType === 'personal' && (
            <>
              <Descriptions.Item label="开户人身份证正面">
                {merchant.accountIdCardFront ? (
                  <Image src={merchant.accountIdCardFront} width={100} />
                ) : (
                  <span style={{ color: '#999' }}>未上传</span>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="开户人身份证反面">
                {merchant.accountIdCardBack ? (
                  <Image src={merchant.accountIdCardBack} width={100} />
                ) : (
                  <span style={{ color: '#999' }}>未上传</span>
                )}
              </Descriptions.Item>
            </>
          )}
        </Descriptions>
      </Card>

      {/* 编辑弹窗 */}
      <Modal
        title="修改店铺信息"
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        onOk={handleUpdate}
        confirmLoading={loading}
        width={720}
        style={{ top: 20 }}
      >
        <Alert
          message="提示"
          description="修改店铺信息后将重新进入审核状态。图片字段请输入图片URL地址。"
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
        <Form form={form} layout="vertical">
          <Tabs defaultActiveKey="basic">
            <TabPane tab="基本信息" key="basic">
              <Form.Item name="shopName" label="店铺名称" rules={[{ required: true, message: '请输入店铺名称' }]}>
                <Input maxLength={100} placeholder="请输入店铺名称" />
              </Form.Item>
              <Form.Item name="phone" label="联系电话" rules={[{ required: true, message: '请输入联系电话' }]}>
                <Input maxLength={20} placeholder="请输入联系电话" />
              </Form.Item>
              <Form.Item name="logo" label="店铺Logo">
                <Input placeholder="请输入Logo图片URL" maxLength={500} />
              </Form.Item>
              <Form.Item name="coverImage" label="店铺封面">
                <Input placeholder="请输入封面图片URL" maxLength={500} />
              </Form.Item>
              <Form.Item name="province" label="省份">
                <Input maxLength={50} placeholder="请输入省份" />
              </Form.Item>
              <Form.Item name="city" label="城市">
                <Input maxLength={50} placeholder="请输入城市" />
              </Form.Item>
              <Form.Item name="district" label="区县">
                <Input maxLength={50} placeholder="请输入区县" />
              </Form.Item>
              <Form.Item name="address" label="详细地址">
                <Input maxLength={255} placeholder="请输入详细地址" />
              </Form.Item>
              <Form.Item name="description" label="店铺描述">
                <Input.TextArea rows={3} maxLength={500} showCount placeholder="请输入店铺描述" />
              </Form.Item>
            </TabPane>
            <TabPane tab="资质信息" key="qualification">
              <Form.Item name="licenseNo" label="营业执照编号">
                <Input maxLength={50} placeholder="请输入营业执照编号" />
              </Form.Item>
              <Form.Item name="legalPerson" label="法人姓名">
                <Input maxLength={50} placeholder="请输入法人姓名" />
              </Form.Item>
              <Form.Item name="businessLicense" label="营业执照图片">
                <Input placeholder="请输入营业执照图片URL" maxLength={500} />
              </Form.Item>
              <Alert
                message="注意"
                description="签约类型、门店营业执照、身份证等资质信息创建后不可修改，如需修改请联系平台客服。"
                type="info"
                showIcon
                style={{ marginTop: 16 }}
              />
            </TabPane>
          </Tabs>
        </Form>
      </Modal>
    </div>
  );
};

export default Settings;
