import React, { useEffect, useState } from 'react';
import { Button, Table, Tag, Modal, Select, App, Input } from 'antd';
import { PlusOutlined, CheckCircleOutlined, ClockCircleOutlined, CiCircleOutlined } from '@ant-design/icons';
import { getOAuthList, juliang_callback, requestOAuth } from '../api';

const OPEN_TYPE_MAP: Record<number, string> = {
  1: '千川',
  2: '广告',
  3: '本地推',
  4: '星图',
  5: '快手代理商',
  6: '巨量星图',
  7: '巨量服务单',
  8: '腾讯服务单',
  9: '腾讯营销K2',
  10: '腾讯营销K3',
};

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

const statusConfig = {
  active: { label: '已授权', color: 'green', icon: CheckCircleOutlined },
  pending: { label: '待授权', color: 'gold', icon: ClockCircleOutlined },
  expired: { label: '已过期', color: 'red', icon: CiCircleOutlined },
  revoked: { label: '已撤销', color: 'gray', icon: CiCircleOutlined },
};

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: '',
  });

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

  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 handleCallback = async () => {
    const params = new URLSearchParams(window.location.search);
    const authCode = params.get('auth_code');
    const state = params.get('state');
    if (authCode && state) {
      try {
        await juliang_callback({ auth_code: authCode, state });
        message.success('授权成功');
        window.history.replaceState({}, document.title, window.location.pathname);
        loadOAuthList();
      } catch (error) {
        message.error('授权回调失败');
      }
    }
  };

  const renderStatus = (status: string) => {
    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.expired;
    const Icon = config.icon;
    return (
      <Tag color={config.color} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        <Icon size={14} />
        {config.label}
      </Tag>
    );
  };

  const handleAuthorize = () => {
    console.log('handleAuthorize');
    setShowModal(true);
  };

  const handleConfirm = async () => {
    if (!selectedOpenType) {
      message.warning('请选择开户方式');
      return;
    }
    setLoading(true);
    try {
      const response = await requestOAuth({ open_type: selectedOpenType });
      console.log(response);
      if (response.authUrl) {
        window.open(response.authUrl, '_blank');
      } else {
        message.error('获取授权链接失败');
      }
    } catch (error) {
      message.error('请求授权失败');
    } finally {
      setLoading(false);
      setShowModal(false);
      setSelectedOpenType(undefined);
    }
  };

  // account_id
  // : 
  // "1836691333531724"
  // account_name
  // : 
  // "BP-1836691333531724"
  // account_role
  // : 
  // "CUSTOMER_ADMIN"
  // account_userid
  // : 
  // null
  // account_username
  // : 
  // "a***3@minzhong.cn"
  // appid
  // : 
  // "1866261617455433"
  // created_at
  // : 
  // "2026-06-15T10:00:22.734565Z"
  // id
  // : 
  // "0019ecab9b8bc57d964"
  // material_auth_status
  // : 
  // true
  // open_type
  // : 
  // 2
  // port_type
  // : 
  // 1
  // updated_at
  // : 
  // "2026-06-17T06:41:33.012018Z"
  // user_id
  // : 
  // "0019e96d23e57a808e2"
  
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (text: number) => <span style={{ color: '#94a3b8' }}>{text}</span>,
    },
    {
      title: '授权ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
      render: (text: string) => (
        <span style={{ fontWeight: 500, color: '#1e293b' }}>{text}</span>
      ),
    },
    {
      title: '开户方式',
      dataIndex: 'open_type',
      key: 'open_type',
      width: 140,
      render: (text: number) => <span style={{ color: '#1e293b' }}>{OPEN_TYPE_MAP[text] || text}</span>,
    },
    {
      title: '授权状态',
      dataIndex: 'status',
      key: 'status',
      width: 140,
      render: (text: string) => renderStatus(text),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text: string) => <span style={{ color: '#64748b' }}>{text}</span>,
    },
  ];

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

  return (
    <div style={{ padding: 12, minHeight: '94vh', background: '#f8fafc', borderRadius: 12 }}>
      <div>
        <h1 style={{ lineHeight: '28px', fontSize: 24, fontWeight: 600, color: '#1e293b', marginBottom: 8, marginTop: 0 }}>
          授权管理
        </h1>
      </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={Object.entries(OPEN_TYPE_MAP).map(([key, value]) => ({
              value: Number(key),
              label: value,
            }))}
          />
          <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={{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size);
              loadOAuthList(page, size);
            },
          }}
          rowKey="id"
          bordered={false}
          style={{ padding: 16 }}
          scroll={{ x: 'max-content' }}
        />
      </div>

      <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={Object.entries(OPEN_TYPE_MAP).map(([key, value]) => ({
            value: Number(key),
            label: value,
          }))}
        />
      </Modal>
    </div>
  );
};

export default AuthorizationPage;