import React, { useState, useEffect } from 'react';
import { useIntl } from 'umi';
import { Table, Button, Modal, Form, Input, Space, message, Tag, TreeSelect } from 'antd';
import { PlusOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import {
  getLinkList,
  addLink,
  updateLink,
  deleteLink,
  enableLink,
  disableLink,
  getAllCategories,
  getLinkDetail,
} from '@/servers/api/friendLink';
import { LinkStatusMap } from '@/dicts/friendLinkDict';
import FileUpload from '@/components/FileUpload';
import styles from './friendLinkManage.less';

const FriendLinkManage: React.FC = () => {
  const intl = useIntl();
  const [loading, setLoading] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [currentId, setCurrentId] = useState<string>('');
  const [linkData, setLinkData] = useState<API.LinkType[]>([]);
  const [categoryData, setCategoryData] = useState<API.CategoryType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [form] = Form.useForm();
  const [categoryMap, setCategoryMap] = useState<Record<string, string>>({});

  // 获取友情链接列表
  const fetchLinkList = async (pageNo = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const res = await getLinkList({
        basePageRequest: {
          pageNo,
          pageSize,
        },
      });

      if (res.data && res.success) {
        setLinkData(res.data.records);
        setPagination({
          current: res.data.current,
          pageSize: res.data.size,
          total: res.data.total,
        });
      }
    } catch (error) {
      console.error('Failed to fetch link list', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取分类列表
  const fetchCategoryList = async () => {
    try {
      const res = await getAllCategories();
      if (res.data && res.success) {
        setCategoryData(res.data);
      }
    } catch (error) {
      console.error('Failed to fetch category list', error);
    }
  };

  // 首次加载时获取数据
  useEffect(() => {
    fetchCategoryList().then(() => {
      fetchLinkList();
    });
  }, []);

  // 处理分页变化
  const handleTableChange = (paginationParams: any) => {
    fetchLinkList(paginationParams.current, paginationParams.pageSize);
  };

  // 处理添加
  const handleAdd = () => {
    setIsEdit(false);
    setCurrentId('');
    form.resetFields();
    form.setFieldsValue({
      orderBy: 1,
    });
    setModalVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: API.LinkType) => {
    setIsEdit(true);
    setCurrentId(record.id);
    setModalVisible(true);

    // 清空表单
    form.resetFields();

    // 调用详情接口获取完整数据
    getLinkDetail(record.id)
      .then((res: API.Response<API.LinkType>) => {
        if (res.success && res.data) {
          const detail = res.data;
          console.log('Detail data:', detail);

          // 设置表单初始值，包括缩略图URL
          form.setFieldsValue({
            name: detail.name,
            nameEn: detail.nameEn,
            url: detail.url,
            orderBy: parseInt(detail.orderBy),
            classificationId: detail.classificationId,
            // 设置为URL字符串，组件会自动处理
            thumbnail: detail.thumbnail,
          });
        } else {
          message.error(intl.formatMessage({ id: 'friendLink.detail.failed' }));
        }
      })
      .catch((error: any) => {
        console.error('Failed to get link detail', error);
        message.error(intl.formatMessage({ id: 'friendLink.detail.failed' }));
      });
  };

  // 处理删除
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'friendLink.delete.confirm.title' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'friendLink.delete.confirm.content' }),
      okText: intl.formatMessage({ id: 'common.confirm' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'common.cancel' }),
      onOk: async () => {
        try {
          const res = await deleteLink(id);
          if (res.success) {
            message.success(intl.formatMessage({ id: 'friendLink.delete.success' }));
            fetchLinkList(pagination.current, pagination.pageSize);
          }
        } catch (error) {
          console.error('Failed to delete link', error);
        }
      },
    });
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning(intl.formatMessage({ id: 'friendLink.batchDelete.empty' }));
      return;
    }

    Modal.confirm({
      title: intl.formatMessage({ id: 'friendLink.batchDelete.confirm.title' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage(
        { id: 'friendLink.batchDelete.confirm.content' },
        { count: selectedRowKeys.length },
      ),
      okText: intl.formatMessage({ id: 'common.confirm' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'common.cancel' }),
      onOk: async () => {
        try {
          // 实际项目中应实现批量删除API，这里暂时使用循环单个删除
          const promises = selectedRowKeys.map((id) => deleteLink(id.toString()));
          const results = await Promise.all(promises);
          if (results.every((res) => res.success)) {
            message.success(intl.formatMessage({ id: 'friendLink.batchDelete.success' }));
            setSelectedRowKeys([]);
            fetchLinkList(pagination.current, pagination.pageSize);
          }
        } catch (error) {
          console.error('Failed to batch delete links', error);
        }
      },
    });
  };

  // 处理状态切换
  const handleToggleStatus = async (record: API.LinkType) => {
    // 添加确认对话框
    Modal.confirm({
      title: intl.formatMessage({
        id:
          record.status === LinkStatusMap.ENABLED
            ? 'friendLink.disable.confirm.title'
            : 'friendLink.enable.confirm.title',
      }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({
        id:
          record.status === LinkStatusMap.ENABLED
            ? 'friendLink.disable.confirm.content'
            : 'friendLink.enable.confirm.content',
      }),
      okText: intl.formatMessage({ id: 'common.confirm' }),
      cancelText: intl.formatMessage({ id: 'common.cancel' }),
      onOk: async () => {
        try {
          let res;
          if (record.status === LinkStatusMap.ENABLED) {
            // 当前启用，需要禁用
            res = await disableLink(record.id);
          } else {
            // 当前禁用，需要启用
            res = await enableLink(record.id);
          }

          if (res.success) {
            message.success(
              record.status === LinkStatusMap.ENABLED
                ? intl.formatMessage({ id: 'friendLink.disable.success' })
                : intl.formatMessage({ id: 'friendLink.enable.success' }),
            );
            fetchLinkList(pagination.current, pagination.pageSize);
          }
        } catch (error) {
          console.error('Failed to toggle status', error);
        }
      },
    });
  };

  // 处理表单提交
  const handleModalSubmit = () => {
    form.validateFields().then(async (values) => {
      console.log('Form values:', values);
      try {
        // 现在thumbnail字段已经直接是URL字符串，不需要额外处理
        const formData = {
          ...values,
        };

        console.log('Submitting form data:', formData);

        let res;
        if (isEdit) {
          // 编辑模式
          res = await updateLink({
            ...formData,
            id: currentId,
          });
        } else {
          // 新增模式
          res = await addLink(formData);
        }

        if (res.success) {
          message.success(
            isEdit
              ? intl.formatMessage({ id: 'friendLink.update.success' })
              : intl.formatMessage({ id: 'friendLink.add.success' }),
          );
          setModalVisible(false);
          fetchLinkList(pagination.current, pagination.pageSize);
        }
      } catch (error) {
        console.error('Failed to submit form', error);
      }
    });
  };

  // 表格列定义
  const columns = [
    {
      title: intl.formatMessage({ id: 'friendLink.name' }),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: intl.formatMessage({ id: 'friendLink.category' }),
      dataIndex: 'categoryName',
      key: 'categoryName',
    },
    {
      title: intl.formatMessage({ id: 'friendLink.url' }),
      dataIndex: 'url',
      key: 'url',
      render: (text: string) => (
        <a href={text} target="_blank" rel="noopener noreferrer">
          {text}
        </a>
      ),
    },
    {
      title: intl.formatMessage({ id: 'friendLink.thumbnail' }),
      dataIndex: 'thumbnail',
      key: 'thumbnail',
      render: (text: string) =>
        text ? <img src={text} alt="thumbnail" style={{ maxHeight: '30px' }} /> : '-',
    },
    {
      title: intl.formatMessage({ id: 'friendLink.sort' }),
      dataIndex: 'orderBy',
      key: 'orderBy',
    },
    {
      title: intl.formatMessage({ id: 'friendLink.status' }),
      dataIndex: 'status',
      key: 'status',
      render: (text: string) =>
        text === LinkStatusMap.ENABLED ? (
          <Tag color="green">{intl.formatMessage({ id: 'friendLink.enabled' })}</Tag>
        ) : (
          <Tag color="red">{intl.formatMessage({ id: 'friendLink.disabled' })}</Tag>
        ),
    },
    {
      title: intl.formatMessage({ id: 'friendLink.operation' }),
      key: 'operation',
      align: 'center' as const,
      render: (_: any, record: API.LinkType) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            {intl.formatMessage({ id: 'friendLink.edit' })}
          </Button>
          <Button type="link" onClick={() => handleToggleStatus(record)}>
            {record.status === LinkStatusMap.ENABLED
              ? intl.formatMessage({ id: 'friendLink.disable' })
              : intl.formatMessage({ id: 'friendLink.enable' })}
          </Button>
          <Button type="link" onClick={() => handleDelete(record.id)}>
            {intl.formatMessage({ id: 'friendLink.delete' })}
          </Button>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => setSelectedRowKeys(keys),
  };

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <div></div>
        <div className="right-buttons">
          <Button
            type="primary"
            ghost
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            {intl.formatMessage({ id: 'friendLink.add' })}
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            {intl.formatMessage({ id: 'friendLink.batchDelete' })}
          </Button>
          {selectedRowKeys.length > 0 && (
            <span className="selected-count">
              {intl.formatMessage({ id: 'friendLink.selectedCount' }, { count: selectedRowKeys.length })}
            </span>
          )}
        </div>
      </div>

      <div className="content-area">
        <Table
          rowKey="id"
          rowSelection={rowSelection}
          columns={columns}
          dataSource={linkData}
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </div>

      {/* 新增/编辑模态框 */}
      <Modal
        title={
          isEdit
            ? intl.formatMessage({ id: 'friendLink.edit' })
            : intl.formatMessage({ id: 'friendLink.add' })
        }
        visible={modalVisible}
        onOk={handleModalSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label={intl.formatMessage({ id: 'friendLink.name' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'friendLink.form.name.required' }),
              },
            ]}
          >
            <Input placeholder={intl.formatMessage({ id: 'friendLink.form.name.placeholder' })} />
          </Form.Item>

          <Form.Item
            name="nameEn"
            label={intl.formatMessage({ id: 'friendLink.nameEn' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'friendLink.form.nameEn.required' }),
              },
            ]}
          >
            <Input placeholder={intl.formatMessage({ id: 'friendLink.form.nameEn.placeholder' })} />
          </Form.Item>

          <Form.Item
            name="classificationId"
            label={intl.formatMessage({ id: 'friendLink.category' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'friendLink.form.category.required' }),
              },
            ]}
          >
            <TreeSelect
              placeholder={intl.formatMessage({ id: 'friendLink.form.category.placeholder' })}
              allowClear
              treeData={categoryData.map((item) => ({
                title: item.name,
                value: item.id,
                children: item.children?.map((child) => ({
                  title: child.name,
                  value: child.id,
                  children: child.children?.map((grandChild) => ({
                    title: grandChild.name,
                    value: grandChild.id,
                  })),
                })),
              }))}
            />
          </Form.Item>

          <Form.Item
            name="url"
            label={intl.formatMessage({ id: 'friendLink.url' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'friendLink.form.url.required' }),
              },
              { type: 'url', message: intl.formatMessage({ id: 'friendLink.form.url.invalid' }) },
            ]}
          >
            <Input placeholder={intl.formatMessage({ id: 'friendLink.form.url.placeholder' })} />
          </Form.Item>

          <Form.Item
            name="thumbnail"
            label={intl.formatMessage({ id: 'friendLink.thumbnail' })}
            getValueFromEvent={(e) => {
              return e[0].url;
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'friendLink.form.thumbnail.required' }),
              },
            ]}
          >
            <FileUpload
              maxCount={1}
              maxSize={2}
              allowedTypes={['jpg', 'png']}
              listType="picture"
              tip={intl.formatMessage(
                { id: 'component.fileUpload.fileTypeTip' },
                { types: 'JPG, PNG' },
              )}
              buttonText={intl.formatMessage({ id: 'friendLink.form.thumbnail.upload' })}
            />
          </Form.Item>

          <Form.Item
            name="orderBy"
            label={intl.formatMessage({ id: 'friendLink.sort' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'friendLink.form.sort.required' }),
              },
            ]}
          >
            <Input
              type="number"
              placeholder={intl.formatMessage({ id: 'friendLink.form.sort.placeholder' })}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default FriendLinkManage;
