import React, { useEffect, useState } from 'react';
import { Button, Table, Tag, Modal, Select, App, Input, Pagination, 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: '腾讯',
};

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}`;
};

// 安全拼接URL，避免双斜杠
const buildUrl = (path: string): string => {
  const baseUrl = import.meta.env.VITE_API_BASE || "http://localhost:8000";
  // 如果已经是完整URL（以http://或https://开头），直接返回
  if (path.startsWith('http://') || path.startsWith('https://')) {
    return path;
  }
  // 移除路径开头的斜杠（如果有）
  const cleanPath = path.startsWith('/') ? path.slice(1) : path;
  // 移除baseUrl结尾的斜杠（如果有）
  const cleanBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
  return `${cleanBase}/${cleanPath}`;
};

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 }[]>([]);
  const [openTypeList, setOpenTypeList] = useState<any[]>([]);

  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);
      setOpenTypeList(data);
    } 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' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <LockOutlined style={{ color: '#6366f1', fontSize: 16 }} />
        <Typography.Text strong style={{ fontSize: 16 }}>授权管理</Typography.Text>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 12 }}>
          <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>
        <Button
          type="primary"
          size="medium"
          icon={<PlusOutlined />}
          onClick={handleAuthorize}
          loading={loading}
          style={{
            borderRadius: 8,
            fontSize: 14,
            fontWeight: 500,
          }}
        >
          点击授权
        </Button>
      </div>

      <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
        <Table
          dataSource={tableData}
          columns={columns}
          loading={listLoading}
          pagination={false}
          rowKey="id"
          bordered={false}
          scroll={{ x: 'max-content' }}
        />
        <div style={{ padding: '16px', textAlign: 'right' }}>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={total}
            showSizeChanger
            showTotal={(total) => `共 ${total} 条记录`}
            onChange={(page, size) => {
              setCurrentPage(page);
              setPageSize(size);
              loadOAuthList(page, size);
            }}
            size="small"
          />
        </div>
      </div>

      <Modal
        title="选择开户方式"
        open={showModal}
        onOk={handleConfirm}
        onCancel={() => {
          setShowModal(false);
          setSelectedOpenType(undefined);
        }}
        okText="确认授权"
        cancelText="取消"
        confirmLoading={loading}
        width={700}
      >
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', maxHeight: 420, overflowY: 'auto' }}>
          {openTypeList.map((item) => (
            <div
              key={item.id}
              onClick={() => setSelectedOpenType(item.openType)}
              style={{
                width: 'calc(33.33% - 12px)',
                cursor: 'pointer',
                borderRadius: 12,
                border: `2px solid ${selectedOpenType === item.openType ? '#6366f1' : '#e2e8f0'}`,
                padding: 16,
                transition: 'all 0.3s ease',
                background: selectedOpenType === item.openType ? '#f0f1ff' : '#fff',
              }}
            >
              <div style={{ width: '100%', height: 120, marginBottom: 12, borderRadius: 8, overflow: 'hidden' }}>
                {item.thumb ? (
                  <img
                    src={buildUrl(item.thumb)}
                    alt={item.typeName}
                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                  />
                ) : (
                  <div style={{ width: '100%', height: '100%', background: '#f1f5f9', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Typography.Text type="secondary">暂无图片</Typography.Text>
                  </div>
                )}
              </div>
              <Typography.Text strong style={{ fontSize: 14, color: '#1e293b' }}>{item.typeName}</Typography.Text>
              <p style={{ fontSize: 12, color: '#64748b', marginTop: 8, marginBottom: 0, lineHeight: 1.5 }}>
                {item.description}
              </p>
            </div>
          ))}
        </div>
      </Modal>
    </div>
  );
};

export default AuthorizationPage;