import { useEffect, useState } from 'react'
import { Button, Flex, Modal, Form, Divider, Select, Radio, Input, message, ColorPicker, Space, Tooltip } from 'antd'
import { useCreateLargeScreen, useUpdateLargeScreen, useViewLargeScreen } from '../query'
import SelectChart from '@/components/chart/SelectChart'
import AppUpload from '@/components/AppUpload'
import {
  BoldOutlined,
  ItalicOutlined,
  AlignLeftOutlined,
  AlignCenterOutlined,
  AlignRightOutlined,
} from '@ant-design/icons'

interface Chart {
  id: string
  type: string
  config: any
}

interface Props {
  id?: string
  setOpen: (open: boolean) => void
}

const ModalContent = ({ setOpen, id = '' }: Props) => {
  const [form] = Form.useForm()
  const [selectedCharts, setSelectedCharts] = useState<Chart[]>([])
  const { data } = useViewLargeScreen(id)

  // Add form field watchers
  const titleStyle = Form.useWatch('titleStyle', form)

  useEffect(() => {
    if (id && data) {
      try {
        const parsedContent = JSON.parse(data.content)
        form.setFieldsValue({ ...parsedContent.form })
        setSelectedCharts(parsedContent.charts)
      } catch (e) {
        console.error('解析数据失败:', e)
      }
    }
  }, [id, data, form])

  const { mutate: mutateCreate } = useCreateLargeScreen()
  const { mutate: mutateUpdate } = useUpdateLargeScreen()

  // 预览
  const handlePreview = () => {
    form.validateFields().then((values) => {
      const ids = selectedCharts.map((item) => item.id)
      if (!ids.length) {
        message.warning('请至少选择一个图表')
        return
      }

      const params = {
        ...values,
        component_ids: ids.join(','),
        content: JSON.stringify({ form: values, charts: selectedCharts }),
      }

      // 先保存，然后在新窗口打开预览
      mutateUpdate(
        { id, ...params },
        {
          onSuccess: () => {
            window.open(`/data/screen/view/${id}`, '_blank')
          },
        }
      )
    })
  }

  // 保存
  const handleSubmit = () => {
    form.validateFields().then((values) => {
      const ids = selectedCharts.map((item) => item.id)
      if (!ids.length) {
        message.warning('请至少选择一个图表')
        return
      }

      const params = {
        ...values,
        component_ids: ids.join(','),
        content: JSON.stringify({ form: values, charts: selectedCharts }),
      }

      if (id) {
        mutateUpdate(
          { id, ...params },
          {
            onSuccess: () => setOpen(false),
          }
        )
      } else {
        mutateCreate(params, {
          onSuccess: () => setOpen(false),
        })
      }
    })
  }

  return (
    <>
      <Form
        form={form}
        preserve={false}
        initialValues={{
          size: '1920*1080',
          bg: 'default',
          layout: 'auto',
          titleStyle: {
            fontSize: 24,
            color: '#000000',
            bold: false,
            italic: false,
            align: 'center',
          },
        }}>
        <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
          <Input placeholder="请输入名称" />
        </Form.Item>
        <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入标题' }]}>
          <Space>
            <Form.Item name="title" noStyle>
              <Input placeholder="请输入标题" />
            </Form.Item>
            <Form.Item name={['titleStyle', 'fontSize']} noStyle>
              <Select
                options={[
                  { label: '16px', value: 16 },
                  { label: '18px', value: 18 },
                  { label: '20px', value: 20 },
                  { label: '24px', value: 24 },
                  { label: '28px', value: 28 },
                  { label: '32px', value: 32 },
                  { label: '36px', value: 36 },
                  { label: '40px', value: 40 },
                ]}
                style={{ width: 120 }}
              />
            </Form.Item>
            <Form.Item name={['titleStyle', 'color']} noStyle getValueFromEvent={(e) => e.toHexString()}>
              <ColorPicker />
            </Form.Item>
            <Form.Item name={['titleStyle', 'bold']} noStyle>
              <Tooltip title="加粗">
                <Button
                  type={titleStyle?.bold ? 'primary' : 'default'}
                  icon={<BoldOutlined />}
                  onClick={() => form.setFieldValue(['titleStyle', 'bold'], !titleStyle?.bold)}
                />
              </Tooltip>
            </Form.Item>
            <Form.Item name={['titleStyle', 'italic']} noStyle>
              <Tooltip title="斜体">
                <Button
                  type={titleStyle?.italic ? 'primary' : 'default'}
                  icon={<ItalicOutlined />}
                  onClick={() => form.setFieldValue(['titleStyle', 'italic'], !titleStyle?.italic)}
                />
              </Tooltip>
            </Form.Item>
            <Form.Item name={['titleStyle', 'align']} noStyle>
              <Space>
                <Tooltip title="左对齐">
                  <Button
                    type={titleStyle?.align === 'left' ? 'primary' : 'default'}
                    icon={<AlignLeftOutlined />}
                    onClick={() => form.setFieldValue(['titleStyle', 'align'], 'left')}
                  />
                </Tooltip>
                <Tooltip title="居中">
                  <Button
                    type={titleStyle?.align === 'center' ? 'primary' : 'default'}
                    icon={<AlignCenterOutlined />}
                    onClick={() => form.setFieldValue(['titleStyle', 'align'], 'center')}
                  />
                </Tooltip>
                <Tooltip title="右对齐">
                  <Button
                    type={titleStyle?.align === 'right' ? 'primary' : 'default'}
                    icon={<AlignRightOutlined />}
                    onClick={() => form.setFieldValue(['titleStyle', 'align'], 'right')}
                  />
                </Tooltip>
              </Space>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item label="大小" name="size" rules={[{ required: true, message: '请选择大小' }]}>
          <Select
            options={[
              { label: '1920*1080', value: '1920*1080' },
              { label: '1024*768', value: '1024*768' },
            ]}
            placeholder="请选择大小"
          />
        </Form.Item>
        <Form.Item label="背景" name="bg" rules={[{ required: true, message: '请选择背景' }]}>
          <Radio.Group
            options={[
              { label: '默认', value: 'default' },
              { label: '纯色', value: 'color' },
              { label: '图片', value: 'image' },
            ]}
          />
        </Form.Item>
        <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.bg !== currentValues.bg}>
          {({ getFieldValue }) => {
            const bgType = getFieldValue('bg')
            if (bgType === 'color') {
              return (
                <Form.Item label="背景颜色" name="bgColor" getValueFromEvent={(e) => e.toHexString()}>
                  <ColorPicker />
                </Form.Item>
              )
            }
            if (bgType === 'image') {
              return (
                <Form.Item label="背景图片" name="bgImage">
                  <AppUpload accept="image/*" />
                </Form.Item>
              )
            }
            return null
          }}
        </Form.Item>
        <Divider />
        <SelectChart value={selectedCharts} onChange={setSelectedCharts} />
        <Form.Item label="组件布局方式" name="layout" rules={[{ required: true, message: '请选择布局方式' }]}>
          <Radio.Group options={[{ label: '自动布局', value: 'auto' }]} />
        </Form.Item>
      </Form>
      <Flex justify="center" gap={20}>
        <Button autoInsertSpace onClick={() => setOpen(false)}>
          取消
        </Button>
        {id && (
          <Button type="primary" onClick={handlePreview}>
            预览
          </Button>
        )}
        <Button type="primary" autoInsertSpace onClick={handleSubmit}>
          保存
        </Button>
      </Flex>
    </>
  )
}

export default function ButtonModal({ id = '' }) {
  const [open, setOpen] = useState(false)
  const title = id ? '编辑' : '新建'
  return (
    <>
      <Button color="primary" variant={id ? 'text' : 'solid'} onClick={() => setOpen(true)}>
        {title}
      </Button>
      <Modal title={title} open={open} footer={null} destroyOnClose width={1000} onCancel={() => setOpen(false)}>
        <ModalContent setOpen={(open) => setOpen(open)} id={id} />
      </Modal>
    </>
  )
}
