import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Button, Card, Space, Table, Tag, Modal, Select, App, Input, Typography } from 'antd';
import { PlusOutlined, LockOutlined } from '@ant-design/icons';
import { getOAuthList, requestOAuth, getOpenTypeAll } from '../api';

const PORT_TYPE_MAP: Record<number, string> = {
  1: '巨量',
  2: '磁力',
  3: '巨量星图',
  4: '服务单',
  5: '腾讯',
};

// 格式化时间 2026-06-12T03:47:28.542988Z -> 2026-06-12 03:47:28
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

interface AuthorizationData {
  id: string;
  status: string;
  description: string;
  account_userid?: string;
  open_type?: number;
  account_id?: string;
}

const AuthorizationPage: React.FC = () => {
  const { message } = App.useApp();
  const [authorizations, setAuthorizations] = useState<AuthorizationData[]>([]);
  const [loading, setLoading] = useState(false);
  const [listLoading, setListLoading] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [selectedOpenType, setSelectedOpenType] = useState<number | undefined>(undefined);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [searchParams, setSearchParams] = useState({
    account_userid: '',
    open_type: undefined as number | undefined,
    account_id: '',
  });
  const [openTypeMap, setOpenTypeMap] = useState<Record<number, string>>({});
  const [openTypeOptions, setOpenTypeOptions] = useState<{ value: number; label: string }[]>([]);

  useEffect(() => {
    loadOAuthList();
    loadOpenTypeList();
  }, []);

  const loadOpenTypeList = async () => {
    try {
      const res = await getOpenTypeAll();
      const data = res.data || [];
      const map: Record<number, string> = {};
      const options: { value: number; label: string }[] = [];
      data.forEach(item => {
        map[item.openType] = item.typeName;
        options.push({ value: item.openType, label: item.typeName });
      });
      setOpenTypeMap(map);
      setOpenTypeOptions(options);
    } catch (error) {
      console.error('加载开户方式列表失败:', error);
    }
  };

  const loadOAuthList = async (page = 1, pageSize = 10, params = searchParams) => {
    setListLoading(true);
    try {
      const response = await getOAuthList({ 
        page, 
        page_size: pageSize,
        account_userid: params.account_userid || undefined,
        open_type: params.open_type,
        account_id: params.account_id || undefined,
      });
      if (response) {
        if (response.data) {
          setAuthorizations(response.data.data || response.data);
        }
        if (response.pagination) {
          setTotal(response.pagination.total || 0);
          setCurrentPage(response.pagination.page || 1);
          setPageSize(response.pagination.pageSize || 10);
        }
      } else {
        setAuthorizations(response || []);
      }
    } catch (error) {
      message.error('获取授权列表失败');
    } finally {
      setListLoading(false);
    }
  };

  const handleAuthorize = () => {
    setShowModal(true);
  };

  const handleConfirm = async () => {
    if (!selectedOpenType) {
      message.warning('请选择开户方式');
      return;
    }
    setLoading(true);
    try {
      const response = await requestOAuth({ open_type: selectedOpenType });
      if (response.authUrl) {
        window.open(response.authUrl, '_blank');
      } else {
        message.error('获取授权链接失败');
      }
    } catch (error) {
      message.error('请求授权失败');
    } finally {
      setLoading(false);
      setShowModal(false);
      setSelectedOpenType(undefined);
    }
  };
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '授权账户ID',
      dataIndex: 'accountId',
      key: 'accountId',
      width: 160,
    },
    {
      title: '授权账户名称',
      dataIndex: 'accountName',
      key: 'accountName',
    },
    {
      title: '授权账户角色',
      dataIndex: 'accountRole',
      key: 'accountRole',
      render: (role: string) => {
        const roleMap: Record<string, string> = {
          ADVERTISER: '客户',
          CUSTOMER_ADMIN: '普通版工作台-管理员',
          CUSTOMER_OPERATOR: '普通版工作台-协作者',
          AGENT: '代理商',
          CHILD_AGENT: '二级代理商',
          PLATFORM_ROLE_STAR: '星图账户',
          PLATFORM_ROLE_SHOP_ACCOUNT: '抖音店铺账户',
          PLATFORM_ROLE_QIANCHUAN_AGENT: '千川代理商',
          PLATFORM_ROLE_STAR_AGENT: '星图代理商',
          PLATFORM_ROLE_AWEME: '抖音号',
          PLATFORM_ROLE_STAR_MCN: '星图MCN机构',
          PLATFORM_ROLE_STAR_ISV: '星图服务商',
          AGENT_SYSTEM_ACCOUNT: '代理商系统账户',
          PLATFORM_ROLE_LOCAL_AGENT: '本地推代理商',
          PLATFORM_ROLE_YUNTU_BRAND_ISV_ADMIN: '云图品牌服务商管理员',
          PLATFORM_ROLE_LIFE: '抖音来客账户',
          PLATFORM_ROLE_ENTERPRISE_BP_ADMIN: '升级版工作台管理员',
          PLATFORM_ROLE_ENTERPRISE_BP_OPERATOR: '升级版工作台协作者',
        };
        return roleMap[role] || role;
      },
    },
    {
      title: '授权账户用户ID',
      dataIndex: 'accountUserid',
      key: 'accountUserid',
      render: (text: string) => <span style={{ color: text ? '#1e293b' : '#94a3b8' }}>{text || '-'}</span>,
    },
    {
      title: '授权账户用户名',
      dataIndex: 'accountUsername',
      key: 'accountUsername',
    },
    {
      title: '授权应用ID',
      dataIndex: 'appid',
      key: 'appid',
    },
    {
      title: '是否敏感物料授权',
      dataIndex: 'materialAuthStatus',
      key: 'materialAuthStatus',
      width: 100,
      render: (text: boolean) => (
        <Tag color={text ? 'green' : 'default'}>
          {text ? '是' : '否'}
        </Tag>
      ),
    },
    {
      title: '开户方式',
      dataIndex: 'openType',
      key: 'openType',
      render: (text: number) => <span style={{ color: '#1e293b' }}>{openTypeMap[text] || text}</span>,
    },
    {
      title: '平台端口',
      dataIndex: 'portType',
      key: 'portType',
      ellipsis: true,
      render: (text: number) => <span style={{ color: '#1e293b' }}>{PORT_TYPE_MAP[text] || text}</span>,
    },    
    {
      title: '用户id',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
      render: (text: string) => <span style={{ color: '#64748b' }}>{formatDateTime(text)}</span>,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 160,
      render: (text: string) => <span style={{ color: '#64748b' }}>{formatDateTime(text)}</span>,
    },
  ];

  const tableData = authorizations.map((item, index) => ({
    ...item,
    index: index + 1,
    key: item.id,
  }));

  return (
    <div style={{ minHeight: '94vh' }}>
      <Card variant="outlined" style={{ borderRadius: 12, border: '1px solid #f0f0f5' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Space>
            <LockOutlined style={{ fontSize: 18, color: '#6366f1' }} />
            <Typography.Text strong style={{ fontSize: 16 }}>授权管理</Typography.Text>
          </Space>
          <Button
            type="primary"
            size="medium"
            icon={<PlusOutlined />}
            onClick={handleAuthorize}
            loading={loading}
            style={{
              borderRadius: 8,
              fontSize: 14,
              fontWeight: 500,
            }}
          >
            点击授权
          </Button>
        </div>
        <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
          <Input
            placeholder="账号用户ID"
            value={searchParams.account_userid}
            onChange={(e) => setSearchParams(prev => ({ ...prev, account_userid: e.target.value }))}
            style={{ width: 180 }}
            onPressEnter={() => { setCurrentPage(1); loadOAuthList(1, pageSize); }}
          />
          <Select
            placeholder="开户方式"
            value={searchParams.open_type}
            onChange={(value) => setSearchParams(prev => ({ ...prev, open_type: value }))}
            style={{ width: 140 }}
            options={openTypeOptions}
          />
          <Input
            placeholder="账号ID"
            value={searchParams.account_id}
            onChange={(e) => setSearchParams(prev => ({ ...prev, account_id: e.target.value }))}
            style={{ width: 180 }}
            onPressEnter={() => { setCurrentPage(1); loadOAuthList(1, pageSize); }}
          />
          <Button
            type="primary"
            size="medium"
            onClick={() => { setCurrentPage(1); loadOAuthList(1, pageSize); }}
          >
            搜索
          </Button>
          <Button
            size="medium"
            onClick={() => {
              setSearchParams({ account_userid: '', open_type: undefined, account_id: '' });
              setCurrentPage(1);
              loadOAuthList(1, pageSize);
            }}
          >
            重置
          </Button>
        </div>
        <Table
          dataSource={tableData}
          columns={columns}
          loading={listLoading}
          rowKey="id"
          bordered={false}
          scroll={{ x: 'max-content' }}
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total,
            showSizeChanger: true,
            showTotal: (t) => `共 ${t} 条记录`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size);
              loadOAuthList(page, size);
            },
            size: 'small',
          }}
        />
      </Card>

      <Modal
        title="选择开户方式"
        open={showModal}
        onOk={handleConfirm}
        onCancel={() => {
          setShowModal(false);
          setSelectedOpenType(undefined);
        }}
        okText="确认授权"
        cancelText="取消"
        confirmLoading={loading}
      >
        <Select
          placeholder="请选择开户方式"
          value={selectedOpenType}
          onChange={(value) => setSelectedOpenType(value)}
          style={{ width: '100%' }}
          options={openTypeOptions}
        />
      </Modal>
    </div>
  );
};

export default AuthorizationPage;