import { useEffect, useState, useMemo, useCallback } from 'react';
import {
  Table, Button, Modal, Input, Select, message, Popconfirm, Typography, Tag, Space,
  Row, Col, Card, Statistic,
} from 'antd';
import type { TableProps } from 'antd';
import { ImportOutlined, DeleteOutlined, TagOutlined, FilterOutlined } from '@ant-design/icons';
import { accountApi, userApi, type AccountItem, type UserInfo } from '../api/modules';
import { usePermissions } from '../hooks/usePermissions';
import { formatTime } from '../utils/time';
import { getErrorMessage } from '../utils/error';

const { TextArea } = Input;
const { Text } = Typography;

const TAG_COLORS = [
  'blue', 'green', 'cyan', 'geekblue', 'purple', 'orange', 'magenta', 'volcano',
];

export default function AccountsPage() {
  const [accounts, setAccounts] = useState<AccountItem[]>([]);
  const [users, setUsers] = useState<UserInfo[]>([]);
  const [tags, setTags] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [importText, setImportText] = useState('');
  const [importing, setImporting] = useState(false);
  const [tagFilter, setTagFilter] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [batchTagInput, setBatchTagInput] = useState('');
  const [batchTagVisible, setBatchTagVisible] = useState(false);
  const [pageSize, setPageSize] = useState(() => {
    const v = localStorage.getItem('account_page_size');
    return v ? Number(v) || 20 : 20;
  });
  const [currentPage, setCurrentPage] = useState(1);
  const { can } = usePermissions();

  const canViewFull = can('account:view_full');
  const canImport = can('account:import');
  const canAssign = can('account:assign');
  const canDelete = can('account:delete');

  const loadAccounts = useCallback(async () => {
    setLoading(true);
    try {
      const params: { tag?: string } = {};
      if (tagFilter) params.tag = tagFilter;
      const data = await accountApi.list(params);
      setAccounts(data);
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    } finally {
      setLoading(false);
    }
  }, [tagFilter]);

  const loadUsers = useCallback(async () => {
    try {
      const data = await userApi.list();
      setUsers(data.filter((u) => u.role === 'support'));
    } catch {
      // 忽略客服列表加载失败，账号列表仍可继续使用。
    }
  }, []);

  const loadTags = useCallback(async () => {
    try {
      const data = await accountApi.listTags();
      setTags(data);
    } catch {
      // 忽略标签加载失败，页面会退化为无标签筛选。
    }
  }, []);

  useEffect(() => {
    loadAccounts();
    if (canAssign) loadUsers();
    loadTags();
  }, [loadAccounts, canAssign, loadUsers, loadTags]);

  const tagColorMap = useMemo(() => {
    const map: Record<string, string> = {};
    tags.forEach((t, i) => {
      map[t] = TAG_COLORS[i % TAG_COLORS.length];
    });
    return map;
  }, [tags]);

  const handleImport = async () => {
    if (!importText.trim()) {
      message.warning('请输入账号数据');
      return;
    }
    setImporting(true);
    try {
      const result = await accountApi.import(importText);
      message.success(result.message);
      setImportOpen(false);
      setImportText('');
      loadAccounts();
      loadTags();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    } finally {
      setImporting(false);
    }
  };

  const handleAssign = async (accountId: number, assignedTo: number | null) => {
    try {
      await accountApi.assign(accountId, assignedTo);
      message.success('已分配');
      loadAccounts();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    }
  };

  const handleSetTag = async (accountId: number, tag: string) => {
    try {
      await accountApi.setTag(accountId, tag);
      message.success('标签已更新');
      loadAccounts();
      loadTags();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    }
  };

  const handleBatchTag = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择账号');
      return;
    }
    try {
      await accountApi.batchTag(selectedRowKeys as number[], batchTagInput);
      message.success(`已为 ${selectedRowKeys.length} 个账号设置标签`);
      setBatchTagVisible(false);
      setBatchTagInput('');
      setSelectedRowKeys([]);
      loadAccounts();
      loadTags();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await accountApi.delete(id);
      message.success('已删除');
      setSelectedRowKeys((prev) => prev.filter((k) => k !== id));
      loadAccounts();
      loadTags();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    }
  };

  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择账号');
      return;
    }
    try {
      const result = await accountApi.batchDelete(selectedRowKeys as number[]);
      message.success(result.message);
      setSelectedRowKeys([]);
      loadAccounts();
      loadTags();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    }
  };

  const columns: TableProps<AccountItem>['columns'] = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '用户名', dataIndex: 'username' },
    {
      title: '标签',
      dataIndex: 'tag',
      width: 120,
      render: (tag: string, record: AccountItem) => {
        if (!tag) {
          if (canImport) {
            return (
              <Input
                size="small"
                placeholder="输入标签"
                style={{ width: 90 }}
                onPressEnter={(e) => {
                  const val = (e.target as HTMLInputElement).value.trim();
                  if (val) handleSetTag(record.id, val);
                }}
                onBlur={(e) => {
                  const val = e.target.value.trim();
                  if (val) handleSetTag(record.id, val);
                }}
              />
            );
          }
          return <Text type="secondary">-</Text>;
        }
        if (canImport) {
          return (
            <Tag
              color={tagColorMap[tag]}
              closable
              onClose={(e) => {
                e.preventDefault();
                handleSetTag(record.id, '');
              }}
            >
              {tag}
            </Tag>
          );
        }
        return <Tag color={tagColorMap[tag]}>{tag}</Tag>;
      },
    },
    {
      title: '上传时间',
      dataIndex: 'created_at',
      width: 180,
      render: (val: string | null) => val ? formatTime(val) : <Text type="secondary">-</Text>,
    },
  ];

  // 只有管理员可看完整字段（密码、邮箱等）
  if (canViewFull) {
    columns.push(
      { title: '密码', dataIndex: 'password', width: 120 },
      { title: '邮箱', dataIndex: 'email' },
      { title: '邮箱密码', dataIndex: 'email_password', width: 120 },
    );
  }

  columns.push({
    title: '分配给',
    dataIndex: 'assigned_username',
    render: (_: unknown, record: AccountItem) => {
      if (canAssign) {
        return (
          <Select
            style={{ width: 140 }}
            allowClear
            placeholder="未分配"
            value={record.assigned_to}
            onChange={(val) => handleAssign(record.id, val ?? null)}
            options={users.map((u) => ({ value: u.id, label: u.username }))}
          />
        );
      }
      return record.assigned_username || <Text type="secondary">未分配</Text>;
    },
  });

  if (canDelete) {
    columns.push({
      title: '操作',
      width: 80,
      render: (_: unknown, record: AccountItem) => (
        <Popconfirm title="确认删除？" onConfirm={() => handleDelete(record.id)}>
          <Button danger size="small" icon={<DeleteOutlined />}>删除</Button>
        </Popconfirm>
      ),
    });
  }

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h2>账号管理</h2>
        <Space>
          <Select
            allowClear
            placeholder="按标签筛选"
            style={{ width: 150 }}
            value={tagFilter || undefined}
            onChange={(val) => setTagFilter(val || '')}
            options={tags.map((t) => ({ value: t, label: t }))}
            prefix={<FilterOutlined />}
          />
          {canImport && (
            <>
              <Button
                disabled={selectedRowKeys.length === 0}
                icon={<TagOutlined />}
                onClick={() => {
                  setBatchTagInput('');
                  setBatchTagVisible(true);
                }}
              >
                批量打标签
              </Button>
              {canDelete && (
                <Popconfirm
                  title={`确认删除选中的 ${selectedRowKeys.length} 个账号？`}
                  description="将同时删除关联的登录任务"
                  onConfirm={handleBatchDelete}
                  okText="删除"
                  okButtonProps={{ danger: true }}
                  cancelText="取消"
                >
                  <Button
                    danger
                    disabled={selectedRowKeys.length === 0}
                    icon={<DeleteOutlined />}
                  >
                    批量删除
                  </Button>
                </Popconfirm>
              )}
              <Button type="primary" icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>
                批量导入
              </Button>
            </>
          )}
        </Space>
      </div>

      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card size="small"><Statistic title="账号总数" value={accounts.length} /></Card>
        </Col>
        <Col span={6}>
          <Card size="small"><Statistic title="标签数" value={tags.length} /></Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic
              title="已分配"
              value={accounts.filter((a) => a.assigned_to).length}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic
              title="未分配"
              value={accounts.filter((a) => !a.assigned_to).length}
            />
          </Card>
        </Col>
      </Row>

      <Table
        rowSelection={canImport ? {
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys),
        } : undefined}
        columns={columns}
        dataSource={accounts}
        rowKey="id"
        loading={loading}
        size="small"
        pagination={{
          current: currentPage,
          pageSize,
          showSizeChanger: true,
          showTotal: (t) => `共 ${t} 条`,
          onChange: (page, size) => {
            setCurrentPage(page);
            if (size !== pageSize) {
              setPageSize(size);
              localStorage.setItem('account_page_size', String(size));
              setCurrentPage(1); // 切换 pageSize 时重置到第1页
            }
          },
        }}
      />

      <Modal
        title="批量导入账号"
        open={importOpen}
        onCancel={() => setImportOpen(false)}
        onOk={handleImport}
        confirmLoading={importing}
        okText="导入"
        width={600}
      >
        <Text type="secondary">
          格式：用户名|密码|邮箱|邮箱密码|标签（可选，每行一个）
        </Text>
        <TextArea
          rows={10}
          value={importText}
          onChange={(e) => setImportText(e.target.value)}
          placeholder={`用户名|密码|邮箱|邮箱密码|标签\n用户名|密码|邮箱|邮箱密码|标签`}
          style={{ marginTop: 8 }}
        />
      </Modal>

      <Modal
        title="批量设置标签"
        open={batchTagVisible}
        onCancel={() => setBatchTagVisible(false)}
        onOk={handleBatchTag}
        okText="确定"
        width={400}
      >
        <p>为选中的 {selectedRowKeys.length} 个账号设置标签：</p>
        <Select
          mode="tags"
          style={{ width: '100%' }}
          placeholder="输入或选择标签"
          value={batchTagInput ? [batchTagInput] : []}
          onChange={(vals) => setBatchTagInput(vals.length > 0 ? vals[vals.length - 1] : '')}
          options={tags.map((t) => ({ value: t, label: t }))}
        />
      </Modal>
    </div>
  );
}
