import { formatDateTime } from '../../utils/validation';
import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Space, App, Popconfirm, Modal, Form, Switch, Upload, Tabs, Select, Tag, Descriptions, Divider, Typography } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExportOutlined, ImportOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import api, { userGroupAPI } from '../../services/api';
import type { UploadProps } from 'antd';
import UserGroupManage from './UserGroupManage';
import GlassCard from '../../components/common/GlassCard';

interface User {
  id: string;
  name: string;
  phone: string;
  password: string;
  createdAt: string;
  examCount?: number; // 参加考试次数
  lastExamTime?: string; // 最后一次参加考试时间
  groups?: any[];
}

interface QuizRecord {
  id: string;
  userId: string;
  totalScore: number;
  scorePercentage: number;
  status: '不及格' | '合格' | '优秀';
  createdAt: string;
  subjectName?: string;
  taskName?: string;
}

interface RecordDetailAnswer {
  id: string;
  questionId: string;
  userAnswer: string | string[];
  score: number;
  isCorrect: boolean;
  questionContent?: string;
  questionType?: string;
  correctAnswer?: string | string[];
  questionScore?: number;
  questionAnalysis?: string;
}

interface RecordDetailResponse {
  record: QuizRecord;
  answers: RecordDetailAnswer[];
}

interface UserGroup {
  id: string;
  name: string;
  isSystem: boolean;
}

const getStatusColor = (status: string) => {
  switch (status) {
    case '不及格':
      return 'red';
    case '合格':
      return 'blue';
    case '优秀':
      return 'green';
    default:
      return 'default';
  }
};

const UserManagePage = () => {
  const { message } = App.useApp();
  const [users, setUsers] = useState<User[]>([]);
  const [userGroups, setUserGroups] = useState<UserGroup[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [visiblePasswords, setVisiblePasswords] = useState<Set<string>>(new Set());
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    size: 'small' as const,
  });
  // 新增搜索状态
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  
  // 新增状态：跟踪选定的用户和答题记录
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [userRecords, setUserRecords] = useState<QuizRecord[]>([]);
  const [recordsLoading, setRecordsLoading] = useState(false);
  const [recordsPagination, setRecordsPagination] = useState({
    current: 1,
    pageSize: 5,
    total: 0,
    size: 'small' as const,
  });
  // 新增状态：跟踪记录详情
  const [recordDetailVisible, setRecordDetailVisible] = useState(false);
  const [recordDetail, setRecordDetail] = useState<any>(null);
  const [recordDetailLoading, setRecordDetailLoading] = useState(false);

  const fetchUsers = async (page = 1, pageSize = 10, keyword = '') => {
    setLoading(true);
    try {
      const url = new URL('/admin/users', window.location.origin);
      url.searchParams.set('page', page.toString());
      url.searchParams.set('limit', pageSize.toString());
      if (keyword) {
        url.searchParams.set('keyword', keyword);
      }
      
      const res = await api.get(url.pathname + url.search);
      setUsers(res.data);
      setPagination({
        current: page,
        pageSize,
        total: (res as any).pagination?.total || res.data.length,
        size: 'small' as const,
      });
    } catch (error) {
      message.error('获取用户列表失败');
      console.error('获取用户列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchUserGroups = async () => {
    try {
      const res = await userGroupAPI.getAll();
      const groups = (res.data || []) as UserGroup[];
      setUserGroups(groups);
      return groups;
    } catch (error) {
      console.error('获取用户组失败');
      return [];
    }
  };

  useEffect(() => {
    fetchUsers();
    fetchUserGroups();
  }, []);

  const handleTableChange = (newPagination: any) => {
    fetchUsers(newPagination.current, newPagination.pageSize, searchKeyword);
  };

  const handleSearch = () => {
    fetchUsers(1, pagination.pageSize, searchKeyword);
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchKeyword(e.target.value);
  };

  const handleCreate = async () => {
    const groups = await fetchUserGroups();
    setEditingUser(null);
    form.resetFields();
    const systemGroups = groups.filter((g) => g.isSystem).map((g) => g.id);
    if (systemGroups.length) {
      form.setFieldsValue({ groupIds: systemGroups });
    }
    setModalVisible(true);
  };

  const handleEdit = async (user: User) => {
    await fetchUserGroups();
    setEditingUser(user);
    form.setFieldsValue({
      name: user.name,
      phone: user.phone,
      password: user.password,
      groupIds: user.groups?.map(g => g.id) || []
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete('/admin/users', { data: { userId: id } });
      message.success('删除成功');
      fetchUsers(pagination.current, pagination.pageSize);
    } catch (error) {
      message.error('删除失败');
      console.error('删除用户失败:', error);
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingUser) {
        // 编辑用户
        await api.put(`/admin/users/${editingUser.id}`, values);
        message.success('更新成功');
      } else {
        // 新增用户
        await api.post('/admin/users', values);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchUsers(pagination.current, pagination.pageSize, searchKeyword);
    } catch (error: any) {
      // 提取具体的错误信息
      let errorMessage = editingUser ? '更新失败' : '创建失败';
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.message) {
        errorMessage = error.message;
      }
      message.error(errorMessage);
      console.error('保存用户失败:', error);
    }
  };

  const handleExport = async () => {
    try {
      const res = await api.get('/admin/users/export');
      const data = res.data;
      const XLSX = await import('xlsx');
      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '用户列表');
      XLSX.writeFile(wb, '用户列表.xlsx');
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
      console.error('导出用户失败:', error);
    }
  };

  const handleImport = async (file: File) => {
    try {
      const XLSX = await import('xlsx');
      const data = await file.arrayBuffer();
      const workbook = XLSX.read(data);
      const sheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet);

      const formData = new FormData();
      const blob = new Blob([JSON.stringify(jsonData)], { type: 'application/json' });
      formData.append('file', blob, 'users.json');

      const res = await api.post('/admin/users/import', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });

      message.success(`导入成功，共导入 ${res.data.imported} 条数据`);
      fetchUsers();
    } catch (error) {
      message.error('导入失败');
      console.error('导入用户失败:', error);
    }
    return false;
  };

  const togglePasswordVisibility = (userId: string) => {
    const newVisible = new Set(visiblePasswords);
    if (newVisible.has(userId)) {
      newVisible.delete(userId);
    } else {
      newVisible.add(userId);
    }
    setVisiblePasswords(newVisible);
  };

  // 获取用户答题记录
  const fetchUserRecords = async (userId: string, page = 1, pageSize = 5) => {
    setRecordsLoading(true);
    try {
      const res = await api.get(`/admin/users/${userId}/records?page=${page}&limit=${pageSize}`);
      setUserRecords(res.data);
      setRecordsPagination({
        current: page,
        pageSize,
        total: (res as any).pagination?.total || res.data.length,
        size: 'small' as const,
      });
    } catch (error) {
      message.error('获取答题记录失败');
      console.error('获取答题记录失败:', error);
    } finally {
      setRecordsLoading(false);
    }
  };

  // 处理答题记录分页变化
  const handleRecordsPaginationChange = (newPagination: any) => {
    if (selectedUser) {
      fetchUserRecords(selectedUser.id, newPagination.current, newPagination.pageSize);
    }
  };

  // 查看用户答题记录
  const handleViewRecords = (user: User) => {
    setSelectedUser(user);
    setRecordsPagination({ ...recordsPagination, current: 1 }); // 重置分页
    fetchUserRecords(user.id, 1, recordsPagination.pageSize);
  };

  // 获取记录详情
  const fetchRecordDetail = async (recordId: string) => {
    setRecordDetailLoading(true);
    try {
      const res = await api.get(`/admin/quiz/records/detail/${recordId}`);
      const data = res.data as RecordDetailResponse;
      setRecordDetail(data);
      return data;
    } catch (error) {
      message.error('获取记录详情失败');
      console.error('获取记录详情失败:', error);
      return null;
    } finally {
      setRecordDetailLoading(false);
    }
  };

  // 查看记录详情
  const handleViewRecordDetail = async (recordId: string) => {
    const detail = await fetchRecordDetail(recordId);
    if (detail) {
      setRecordDetailVisible(true);
    }
  };

  // 关闭记录详情
  const handleCloseRecordDetail = () => {
    setRecordDetailVisible(false);
    setRecordDetail(null);
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '用户组',
      dataIndex: 'groups',
      key: 'groups',
      render: (groups: any[]) => (
        <Space size={[0, 4]} wrap>
          {groups?.map(g => (
             <Tag key={g.id} color={g.isSystem ? 'blue' : 'default'}>{g.name}</Tag>
          ))}
        </Space>
      )
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      render: (password: string, record: User) => (
        <Space>
          <span>
            {visiblePasswords.has(record.id) ? password : '••••••'}
          </span>
          <Button
            type="text"
            icon={visiblePasswords.has(record.id) ? <EyeInvisibleOutlined /> : <EyeOutlined />}
            onClick={() => togglePasswordVisibility(record.id)}
            size="small"
          />
        </Space>
      ),
    },
    {
      title: '参加考试次数',
      dataIndex: 'examCount',
      key: 'examCount',
      render: (count: number) => count || 0,
    },
    {
      title: '最后一次考试时间',
      dataIndex: 'lastExamTime',
      key: 'lastExamTime',
      render: (time: string) => (time ? formatDateTime(time, { includeSeconds: true }) : '无'),
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => formatDateTime(text, { includeSeconds: true }),
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作</div>,
      key: 'action',
      render: (_: any, record: User) => (
        <Space>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            onClick={() => handleViewRecords(record)}
          >
            答题记录
          </Button>
          <Popconfirm
            title="确定删除该用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const uploadProps: UploadProps = {
    accept: '.xlsx,.xls',
    showUploadList: false,
    beforeUpload: handleImport,
  };

  const UserListContent = () => (
    <GlassCard>
      <div className="mb-6">
        <div className="flex justify-between items-center">
          <Input
            placeholder="按姓名搜索"
            value={searchKeyword}
            onChange={handleSearchChange}
            onPressEnter={handleSearch}
            style={{ width: 200 }}
          />
          <Space>
            <Button icon={<ExportOutlined />} onClick={handleExport}>
              导出
            </Button>
            <Upload {...uploadProps}>
              <Button icon={<ImportOutlined />}>
                导入
              </Button>
            </Upload>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              新增用户
            </Button>
          </Space>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={users}
        rowKey="id"
        size="small"
        loading={loading}
        pagination={pagination}
        onChange={handleTableChange}
      />

      {/* 答题记录面板 */}
      {selectedUser && (
        <div className="mt-6">
          <h2 className="text-xl font-semibold text-white mb-4">
            {selectedUser.name}的答题记录
            <Button 
              type="text" 
              onClick={() => setSelectedUser(null)} 
              className="ml-4 text-white/70 hover:text-white"
            >
              关闭
            </Button>
          </h2>
          <Table
            className="bg-transparent"
            columns={[
              {
                title: '考试科目',
                dataIndex: 'subjectName',
                key: 'subjectName',
                render: (text: string) => text || '无科目',
              },
              {
                title: '考试任务',
                dataIndex: 'taskName',
                key: 'taskName',
                render: (text: string) => text || '无任务',
              },
              {
                title: '总分',
                dataIndex: 'totalScore',
                key: 'totalScore',
                render: (score: number) => score || 0,
              },
              {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: (status: string) => {
                  const color = getStatusColor(status);
                  return <Tag color={color}>{status}</Tag>;
                },
              },
              {
                title: '得分',
                dataIndex: 'obtainedScore',
                key: 'obtainedScore',
                render: (score: number, record: QuizRecord) => {
                  const actualScore = (score ?? record.totalScore) || 0;
                  const totalScore = record.totalScore || 0;
                  return (
                    <span className={`font-medium ${actualScore >= totalScore * 0.6 ? 'text-green-600' : 'text-red-600'}`}>
                      {actualScore}
                    </span>
                  );
                },
              },
              {
                title: '得分率',
                dataIndex: 'scoreRate',
                key: 'scoreRate',
                render: (_: any, record: QuizRecord) => {
                  const rate = typeof record.scorePercentage === 'number' ? record.scorePercentage : 0;
                  return `${rate.toFixed(1)}%`;
                },
              },
              {
                title: '考试时间',
                dataIndex: 'createdAt',
                key: 'createdAt',
                render: (time: string) => formatDateTime(time, { includeSeconds: true }),
              },
            ]}
            dataSource={userRecords}
            rowKey="id"
            size="small"
            loading={recordsLoading}
            pagination={recordsPagination}
            onChange={handleRecordsPaginationChange}
            scroll={{ x: 'max-content' }}
            onRow={(record) => ({
              onClick: () => handleViewRecordDetail(record.id),
              style: { cursor: 'pointer' },
            })}
          />
        </div>
      )}

      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        okText="确定"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[{ required: true, message: '请输入手机号' }]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            name="groupIds"
            label="所属用户组"
          >
            <Select
               mode="multiple"
               placeholder="请选择用户组"
               optionFilterProp="children"
            >
               {userGroups.map(g => (
                  <Select.Option key={g.id} value={g.id} disabled={g.isSystem}>
                     {g.name}
                  </Select.Option>
               ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 记录详情弹窗 */}
      <Modal
        title="答题记录详情"
        open={recordDetailVisible}
        onCancel={handleCloseRecordDetail}
        footer={null}
        width="90vw"
        style={{ maxWidth: 1100 }}
        loading={recordDetailLoading}
        bodyStyle={{ maxHeight: '75vh', overflowY: 'auto' }}
      >
        {recordDetail && (() => {
          const record = (recordDetail as RecordDetailResponse).record;
          const answers = (recordDetail as RecordDetailResponse).answers || [];
          const obtainedScore = record?.totalScore ?? 0;
          const scorePercentage = typeof record?.scorePercentage === 'number' ? record.scorePercentage : 0;

          const formatAnswer = (v: any) => {
            if (Array.isArray(v)) return v.join(', ');
            return String(v ?? '').trim();
          };

          const typeLabel = (t?: string) => {
            if (t === 'single') return '单选题';
            if (t === 'multiple') return '多选题';
            if (t === 'judgment') return '判断题';
            if (t === 'text') return '文字题';
            return t || '';
          };

          return (
            <div>
              <Descriptions
                size="small"
                bordered
                column={{ xs: 1, sm: 2, md: 3 }}
                items={[
                  { key: 'user', label: '用户', children: selectedUser?.name || record?.userId || '-' },
                  { key: 'subject', label: '科目', children: record?.subjectName || '无科目' },
                  { key: 'task', label: '任务', children: record?.taskName || '无任务' },
                  { key: 'totalScore', label: '得分', children: obtainedScore },
                  { key: 'scoreRate', label: '得分率', children: `${scorePercentage.toFixed(1)}%` },
                  { key: 'status', label: '状态', children: <Tag color={getStatusColor(record?.status)}>{record?.status || '-'}</Tag> },
                  { key: 'time', label: '考试时间', span: 3, children: record?.createdAt ? formatDateTime(record.createdAt, { includeSeconds: true }) : '-' },
                ]}
              />

              <Divider orientation="left" style={{ marginTop: 16 }}>题目详情</Divider>

              <div className="space-y-4">
                {answers.map((a, index) => {
                  const maxScore = Number(a.questionScore ?? 0);
                  const isZeroScore = maxScore === 0;
                  const correct = formatAnswer(a.correctAnswer);
                  const userAns = formatAnswer(a.userAnswer);
                  const showCorrectAnswer = a.questionType !== 'text' && correct !== '';
                  const showAnalysis = String(a.questionAnalysis ?? '').trim() !== '';
                  const isCorrect = Boolean(a.isCorrect);

                  return (
                    <div key={a.id} className="p-4 border rounded bg-white">
                      <div className="flex flex-wrap items-center gap-2 justify-between">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="font-medium">第 {index + 1} 题</span>
                          <Tag color="blue">{typeLabel(a.questionType)}</Tag>
                          <Tag>{maxScore} 分</Tag>
                          <Tag color={isCorrect ? 'green' : 'red'}>{isCorrect ? '答对' : '答错'}</Tag>
                          {isZeroScore ? <Tag color="default">0分题默认正确</Tag> : null}
                        </div>
                        <div className="text-sm text-gray-600">得分：{Number(a.score ?? 0)}</div>
                      </div>

                      <div className="mt-3">
                        <Typography.Paragraph style={{ marginBottom: 8 }}>
                          <span className="font-medium">题目：</span>
                          <span className="whitespace-pre-wrap">{a.questionContent || ''}</span>
                        </Typography.Paragraph>

                        <div className="grid gap-2" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))' }}>
                          <div>
                            <div className="text-sm text-gray-600 mb-1">你的答案</div>
                            <div className="whitespace-pre-wrap font-medium">{userAns || '未作答'}</div>
                          </div>
                          <div>
                            <div className="text-sm text-gray-600 mb-1">正确答案</div>
                            <div className="whitespace-pre-wrap">{showCorrectAnswer ? correct : (a.questionType === 'text' ? '（文字题无标准答案）' : (correct || ''))}</div>
                          </div>
                        </div>

                        {showAnalysis ? (
                          <div className="mt-3">
                            <div className="text-sm text-gray-600 mb-1">解析</div>
                            <div className="whitespace-pre-wrap">{String(a.questionAnalysis ?? '')}</div>
                          </div>
                        ) : null}
                      </div>
                    </div>
                  );
                })}

                {answers.length === 0 ? (
                  <div className="text-center py-10 text-gray-500">暂无题目详情</div>
                ) : null}
              </div>
            </div>
          );
        })()}
      </Modal>
    </GlassCard>
  );

  const UserGroupContent = () => (
    <GlassCard>
      <UserGroupManage />
    </GlassCard>
  );

  return (
    <div>
      <h1 className="text-2xl font-bold text-white mb-4">用户管理</h1>
      <Tabs
        defaultActiveKey="1"
        items={[
          {
            key: '1',
            label: '用户列表',
            children: <UserListContent />,
          },
          {
            key: '2',
            label: '用户组管理',
            children: <UserGroupContent />,
          },
        ]}
      />
    </div>
  );
};

export default UserManagePage;
