import {
  createProjectIntroduction,
  getProjectIntroductionDetail,
  updateProjectIntroduction,
  uploadProjectIntroductionImage,
  uploadProjectIntroductionVideo,
} from './service';
import BraftEditorCom from '@/components/BraftEditor';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { history, useAccess } from '@umijs/max';
import { Button, Form, Image, Input, Radio, Select, Switch, Upload, message } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import './style.less';

const categoryOptions = [
  { label: '平台介绍', value: 'platform' },
  { label: '营销模式', value: 'mode' },
  { label: '营销动作', value: 'action' },
];

const contentTypeOptions = [
  { label: '图文', value: 1 },
  { label: '视频', value: 2 },
];

const ProjectIntroductionManagePage: React.FC = () => {
  const access = useAccess();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [uploadingCover, setUploadingCover] = useState(false);
  const [uploadingVideo, setUploadingVideo] = useState(false);
  const [coverImg, setCoverImg] = useState('');
  const pathname = history.location.pathname;
  const isCreate = pathname.endsWith('/create');
  const listPagePath = '/live/promotion/project-introduction';
  const recordId = useMemo(() => {
    if (isCreate) {
      return '';
    }
    const segments = pathname.split('/');
    return segments[segments.length - 2] || '';
  }, [isCreate, pathname]);
  const canAccess = isCreate ? access['live:project-introduction:add'] : access['live:project-introduction:edit'];
  const contentType = Form.useWatch('contentType', form) || 1;
  const isVideoType = contentType === 2;

  useEffect(() => {
    if (!canAccess) {
      history.replace('/Welcome');
      return;
    }
    const bootstrap = async () => {
      setLoading(true);
      try {
        if (isCreate) {
          setCoverImg('');
          form.setFieldsValue({
            title: '',
            category: undefined,
            contentType: 1,
            content: '',
            videoUrl: '',
            videoFileName: '',
            status: true,
          });
          return;
        }
        const res = await getProjectIntroductionDetail(recordId);
        const detail = res.data;
        setCoverImg(detail.coverImg || '');
        form.setFieldsValue({
          title: detail.title,
          coverImg: detail.coverImg,
          category: detail.category,
          contentType: detail.contentType || 1,
          content: detail.content || '',
          videoUrl: detail.videoUrl || '',
          videoFileName: detail.videoFileName || '',
          videoDescription: detail.videoDescription || '',
          status: detail.status === 1,
        });
      } finally {
        setLoading(false);
      }
    };
    bootstrap();
  }, [canAccess, form, isCreate, recordId]);

  const handleSubmit = async () => {
    const values = await form.validateFields();
    const payload = {
      title: values.title?.trim(),
      coverImg,
      category: values.category,
      contentType: values.contentType,
      content: values.contentType === 1 ? values.content : undefined,
      videoUrl: values.contentType === 2 ? values.videoUrl?.trim() : undefined,
      videoFileName: values.contentType === 2 ? values.videoFileName?.trim() : undefined,
      videoDescription: values.contentType === 2 ? values.videoDescription?.trim() : undefined,
      status: values.status ? 1 : 0,
    };
    setSubmitting(true);
    try {
      if (isCreate) {
        await createProjectIntroduction(payload);
        message.success('新增成功');
      } else {
        await updateProjectIntroduction(recordId, payload);
        message.success('保存成功');
      }
      history.replace(`${listPagePath}?refresh=${Date.now()}`);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="project-introduction-page">
      <div className="project-introduction-page__panel">
        <div className="project-introduction-page__title">{isCreate ? '添加项目介绍' : '编辑项目介绍'}</div>
        <Form form={form} layout="vertical" className="project-introduction-edit-form">
          <div className="project-introduction-edit-form__section-title">信息</div>
          <div className="project-introduction-edit-form__grid">
            <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入标题' }]}>
              <Input placeholder="请输入" maxLength={128} disabled={loading} />
            </Form.Item>
            <Form.Item label="类别" name="category" rules={[{ required: true, message: '请选择类别' }]}>
              <Select placeholder="请选择" options={categoryOptions} disabled={loading} />
            </Form.Item>
            <Form.Item label="封面图" className="project-introduction-edit-form__upload" required>
              <Form.Item name="coverImg" rules={[{ required: true, message: '请上传封面图' }]} hidden>
                <Input />
              </Form.Item>
              <Upload
                accept="image/*"
                showUploadList={false}
                customRequest={async (options) => {
                  setUploadingCover(true);
                  try {
                    const res = await uploadProjectIntroductionImage(options.file as File);
                    const url = res.data?.url;
                    if (!url) {
                      throw new Error('upload failed');
                    }
                    setCoverImg(url);
                    form.setFieldsValue({ coverImg: url });
                    options.onSuccess?.(res);
                  } catch (error) {
                    message.error('封面图上传失败');
                    options.onError?.(error as Error);
                  } finally {
                    setUploadingCover(false);
                  }
                }}
              >
                <div className="project-introduction-edit-form__cover-box">
                  {coverImg ? (
                    <Image src={coverImg} width={96} height={96} preview={false} />
                  ) : uploadingCover ? (
                    '上传中...'
                  ) : (
                    <PlusOutlined />
                  )}
                </div>
              </Upload>
            </Form.Item>
            <div className="project-introduction-edit-form__switch-group">
              <div className="project-introduction-edit-form__switch-item">
                <span className="project-introduction-edit-form__switch-label">是否启用</span>
                <Form.Item name="status" valuePropName="checked" rules={[{ required: true, message: '请选择是否启用' }]}>
                  <Switch />
                </Form.Item>
              </div>
            </div>
            <Form.Item label="内容类型" name="contentType" rules={[{ required: true, message: '请选择内容类型' }]}>
              <Radio.Group options={contentTypeOptions} disabled={loading} />
            </Form.Item>
            {isVideoType ? (
              <>
                <Form.Item
                  label="视频地址"
                  name="videoUrl"
                  extra="本地视频和视频地址必须填一个"
                  rules={[{ required: true, message: '请填写视频地址或上传本地视频' }]}
                >
                  <Input placeholder="请输入" disabled={loading} />
                </Form.Item>
                <Form.Item
                  label="视频介绍"
                  name="videoDescription"
                  rules={[{ required: true, message: '请输入视频介绍' }]}
                >
                  <Input.TextArea placeholder="请输入视频介绍" maxLength={255} rows={3} disabled={loading} />
                </Form.Item>
                <Form.Item label="本地视频" extra="本地视频和视频地址必须填一个">
                  <div className="project-introduction-edit-form__video-upload">
                    <Upload
                      accept="video/*"
                      showUploadList={false}
                      customRequest={async (options) => {
                        setUploadingVideo(true);
                        try {
                          const res = await uploadProjectIntroductionVideo(options.file as File);
                          const url = res.data?.url;
                          if (!url) {
                            throw new Error('upload failed');
                          }
                          form.setFieldsValue({
                            videoUrl: url,
                            videoFileName: res.data?.fileName || (options.file as File).name,
                          });
                          message.success('视频上传成功');
                          options.onSuccess?.(res);
                        } catch (error) {
                          message.error('视频上传失败');
                          options.onError?.(error as Error);
                        } finally {
                          setUploadingVideo(false);
                        }
                      }}
                    >
                      <Button icon={<UploadOutlined />} loading={uploadingVideo}>
                        上传
                      </Button>
                    </Upload>
                    <span>
                      {form.getFieldValue('videoFileName') ||
                        (form.getFieldValue('videoUrl') ? '已填写视频地址' : '未上传视频文件')}
                    </span>
                  </div>
                  <Form.Item name="videoFileName" hidden>
                    <Input />
                  </Form.Item>
                </Form.Item>
              </>
            ) : (
              <Form.Item
                label="内容详情"
                name="content"
                className="project-introduction-edit-form__editor-item"
                rules={[{ required: true, message: '请输入内容' }]}
              >
                <div className="project-introduction-edit-form__editor">
                  <BraftEditorCom
                    data={form.getFieldValue('content') || ''}
                    resultCallback={(html: string) => form.setFieldsValue({ content: html })}
                  />
                </div>
              </Form.Item>
            )}
          </div>
          <div className="project-introduction-edit-form__footer">
            <Button onClick={() => history.push(listPagePath)}>取消</Button>
            <Button type="primary" loading={submitting} onClick={handleSubmit}>
              保存
            </Button>
          </div>
        </Form>
      </div>
    </div>
  );
};

export default ProjectIntroductionManagePage;
