import React, { useState, useEffect, useMemo } from 'react';
import { Table, Button, Input, Space, App, Popconfirm, Modal, Form, DatePicker, Select, Tabs, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, FileTextOutlined } from '@ant-design/icons';
import api, { userGroupAPI } from '../../services/api';
import dayjs from 'dayjs';
import { formatDateTime, parseUtcDateTime } from '../../utils/validation';
import GlassCard from '../../components/common/GlassCard';

interface ExamTask {
  id: string;
  name: string;
  subjectId: string;
  subjectName: string;
  startAt: string;
  endAt: string;
  userCount: number;
  completedUsers: number;
  passRate: number;
  excellentRate: number;
  createdAt: string;
  selectionConfig?: string;
}

interface ExamSubject {
  id: string;
  name: string;
}

interface User {
  id: string;
  name: string;
  phone: string;
}

interface UserGroup {
  id: string;
  name: string;
  memberCount: number;
}

const ExamTaskPage = () => {
  const { message } = App.useApp();
  const [tasks, setTasks] = useState<ExamTask[]>([]);
  const [subjects, setSubjects] = useState<ExamSubject[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [userGroups, setUserGroups] = useState<UserGroup[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [reportModalVisible, setReportModalVisible] = useState(false);
  const [reportData, setReportData] = useState<any>(null);
  const [editingTask, setEditingTask] = useState<ExamTask | null>(null);
  const [form] = Form.useForm();
  
  // Cache for group members to calculate unique users
  const [groupMembersMap, setGroupMembersMap] = useState<Record<string, string[]>>({});

  const fetchData = async () => {
    setLoading(true);
    try {
      const [tasksRes, subjectsRes, usersRes, groupsRes] = await Promise.all([
        api.get('/admin/tasks'),
        api.get('/admin/subjects'),
        api.get('/admin/users'),
        userGroupAPI.getAll(),
      ]);
      setTasks(tasksRes.data);
      setSubjects(subjectsRes.data);
      setUsers(usersRes.data);
      setUserGroups(groupsRes.data);
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // Watch form values for real-time calculation
  const selectedUserIds = Form.useWatch<string[]>('userIds', form) || [];
  const selectedGroupIds = Form.useWatch<string[]>('groupIds', form) || [];

  // Fetch members when groups are selected
  useEffect(() => {
    const fetchMissingGroupMembers = async () => {
      if (selectedGroupIds.length > 0) {
        for (const gid of selectedGroupIds) {
          if (!groupMembersMap[gid]) {
            try {
              const membersRes = await userGroupAPI.getMembers(gid);
              const members = (membersRes as any).data as any[];
              setGroupMembersMap(prev => ({
                ...prev,
                [gid]: (members || []).map((u: any) => u.id)
              }));
            } catch (e) {
              console.error(`Failed to fetch members for group ${gid}`, e);
            }
          }
        }
      }
    };
    
    if (modalVisible) {
      fetchMissingGroupMembers();
    }
  }, [selectedGroupIds, modalVisible]);

  const uniqueUserCount = useMemo(() => {
    const uniqueSet = new Set<string>(selectedUserIds);
    selectedGroupIds.forEach((gid: string) => {
      const members = groupMembersMap[gid] || [];
      members.forEach(uid => uniqueSet.add(uid));
    });
    return uniqueSet.size;
  }, [selectedUserIds, selectedGroupIds, groupMembersMap]);

  const handleCreate = () => {
    setEditingTask(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = async (task: ExamTask) => {
    setEditingTask(task);
    try {
      // Parse selection config if available
      let userIds = [];
      let groupIds = [];
      
      if (task.selectionConfig) {
        try {
          const config = JSON.parse(task.selectionConfig);
          userIds = config.userIds || [];
          groupIds = config.groupIds || [];
        } catch (e) {
          console.error('Failed to parse selection config', e);
        }
      } 
      
      // Fallback or if no selection config (legacy tasks), fetch from API which returns resolved users
      // But for editing legacy tasks, we might not have group info. 
      // If selectionConfig is missing, we assume individual users only.
      if (!task.selectionConfig) {
        const userIdsRes = await api.get(`/admin/tasks/${task.id}/users`);
        userIds = userIdsRes.data;
      }
      
      form.setFieldsValue({
        name: task.name,
        subjectId: task.subjectId,
        startAt: dayjs(parseUtcDateTime(task.startAt) ?? task.startAt),
        endAt: dayjs(parseUtcDateTime(task.endAt) ?? task.endAt),
        userIds: userIds,
        groupIds: groupIds,
      });
    } catch (error) {
      message.error('获取任务详情失败');
    }
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/admin/tasks/${id}`);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleReport = async (taskId: string) => {
    try {
      const res = await api.get(`/admin/tasks/${taskId}/report`);
      setReportData(res.data);
      setReportModalVisible(true);
    } catch (error) {
      message.error('获取报表失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (uniqueUserCount === 0) {
        message.warning('请至少选择一位用户或一个用户组');
        return;
      }

      const payload = {
        ...values,
        startAt: values.startAt.toISOString(),
        endAt: values.endAt.toISOString(),
      };

      if (editingTask) {
        await api.put(`/admin/tasks/${editingTask.id}`, payload);
        message.success('更新成功');
      } else {
        await api.post('/admin/tasks', payload);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const columns = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      width: 210,
      ellipsis: true,
    },
    {
      title: '考试科目',
      dataIndex: 'subjectName',
      key: 'subjectName',
      width: 180,
      ellipsis: true,
    },
    {
      title: '开始时间',
      dataIndex: 'startAt',
      key: 'startAt',
      width: 110,
      render: (text: string) => formatDateTime(text),
    },
    {
      title: '结束时间',
      dataIndex: 'endAt',
      key: 'endAt',
      width: 110,
      render: (text: string) => formatDateTime(text),
    },
    {
      title: '考试进程',
      dataIndex: ['startAt', 'endAt'],
      key: 'progress',
      width: 160,
      render: (_: any, record: ExamTask) => {
        const now = dayjs();
        const start = dayjs(parseUtcDateTime(record.startAt) ?? record.startAt);
        const end = dayjs(parseUtcDateTime(record.endAt) ?? record.endAt);
        
        let progress = 0;
        if (now < start) {
          progress = 0;
        } else if (now > end) {
          progress = 100;
        } else {
          const totalDuration = end.diff(start, 'millisecond');
          const elapsedDuration = now.diff(start, 'millisecond');
          progress = Math.round((elapsedDuration / totalDuration) * 100);
        }
        
        return (
          <div className="w-32">
            <div className="flex justify-between text-sm mb-1">
              <span>{progress}%</span>
            </div>
            <div className="w-full bg-white/10 rounded-full h-2">
              <div 
                className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                style={{ width: `${progress}%` }}
              ></div>
            </div>
          </div>
        );
      },
    },
    {
      title: '参与人数',
      dataIndex: 'userCount',
      key: 'userCount',
      width: 75,
      render: (count: number) => `${count} 人`,
    },
    {
      title: '已完成人数',
      dataIndex: 'completedUsers',
      key: 'completedUsers',
      width: 75,
      render: (count: number) => `${count} 人`,
    },
    {
      title: '合格率',
      dataIndex: 'passRate',
      key: 'passRate',
      width: 75,
      render: (rate: number) => `${rate}%`,
    },
    {
      title: '优秀率',
      dataIndex: 'excellentRate',
      key: 'excellentRate',
      width: 75,
      render: (rate: number) => `${rate}%`,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 110, 
      render: (text: string) => formatDateTime(text),
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作</div>,
      key: 'action',
      width: 230,
      render: (_: any, record: ExamTask) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            icon={<FileTextOutlined />}
            onClick={() => handleReport(record.id)}
            size="small"
          >
            报表
          </Button>
          <Popconfirm
            title="确定删除该任务吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />} size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <GlassCard>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-white">考试任务管理</h1>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          新增任务
        </Button>
      </div>

      <Table
        className="bg-transparent"
        columns={columns}
        dataSource={tasks}
        rowKey="id"
        size="small"
        loading={loading}
        scroll={{ x: 1400 }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          size: 'small',
        }}
      />

      <Modal
        title={editingTask ? '编辑任务' : '新增任务'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="任务名称"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>

          <Form.Item
            name="subjectId"
            label="考试科目"
            rules={[{ required: true, message: '请选择考试科目' }]}
          >
            <Select
              placeholder="请选择考试科目"
              style={{ width: '100%' }}
              showSearch
              optionFilterProp="children"
              dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
              virtual
            >
              {subjects.map((subject) => (
                <Select.Option key={subject.id} value={subject.id}>
                  {subject.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="startAt"
            label="开始时间"
            rules={[{ required: true, message: '请选择开始时间' }]}
          >
            <DatePicker
              showTime
              placeholder="请选择开始时间"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="endAt"
            label="结束时间"
            rules={[{ required: true, message: '请选择结束时间' }]}
          >
            <DatePicker
              showTime
              placeholder="请选择结束时间"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <div className="bg-white/5 p-4 rounded mb-4">
            <h4 className="mb-2 font-medium">任务分配对象</h4>
            
            <Form.Item
              name="groupIds"
              label="按用户组选择"
            >
              <Select
                mode="multiple"
                placeholder="请选择用户组"
                style={{ width: '100%' }}
                optionFilterProp="children"
              >
                {userGroups.map((group) => (
                  <Select.Option key={group.id} value={group.id}>
                    {group.name} ({group.memberCount}人)
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="userIds"
              label="按单个用户选择"
              normalize={(value) => {
                if (!Array.isArray(value)) return value;
                return [...value].sort((a, b) => {
                  const nameA = users.find(u => u.id === a)?.name || '';
                  const nameB = users.find(u => u.id === b)?.name || '';
                  return nameA.localeCompare(nameB, 'zh-CN');
                });
              }}
            >
              <Select
                mode="multiple"
                placeholder="请选择用户"
                style={{ width: '100%' }}
                className="user-select-scrollable"
                showSearch
                optionLabelProp="label"
                filterOption={(input, option) => {
                  const inputLower = input.toLowerCase();
                  const labelText = String((option as any)?.label ?? '').toLowerCase();
                  return labelText.includes(inputLower);
                }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                virtual
              >
                {users.map((user) => (
                  <Select.Option key={user.id} value={user.id} label={user.name}>
                    {user.name} ({user.phone})
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <div className="mt-2 text-right text-gray-400">
              实际分配人数（去重后）：<span className="font-bold text-blue-400">{uniqueUserCount}</span> 人
            </div>
          </div>
        </Form>
      </Modal>

      <Modal
        title="任务报表"
        open={reportModalVisible}
        onCancel={() => setReportModalVisible(false)}
        onOk={() => setReportModalVisible(false)}
        okText="关闭"
        width={800}
      >
        {reportData && (
          <div>
            <div className="mb-4">
              <h3 className="text-lg font-bold">{reportData.taskName}</h3>
              <p>考试科目：{reportData.subjectName}</p>
              <p>参与人数：{reportData.totalUsers} 人</p>
              <p>完成人数：{reportData.completedUsers} 人</p>
              <p>平均得分：{reportData.averageScore.toFixed(2)} 分</p>
              <p>最高得分：{reportData.topScore} 分</p>
              <p>最低得分：{reportData.lowestScore} 分</p>
            </div>

            <Table
              columns={[
                { title: '姓名', dataIndex: 'userName', key: 'userName' },
                { title: '手机号', dataIndex: 'userPhone', key: 'userPhone' },
                {
                  title: '得分',
                  dataIndex: 'score',
                  key: 'score',
                  render: (score: number | null) => score !== null ? `${score} 分` : '未答题',
                },
                {
                  title: '得分占比',
                  dataIndex: 'scorePercentage',
                  key: 'scorePercentage',
                  render: (pct: number | null) => {
                    if (pct === null || pct === undefined || Number.isNaN(Number(pct))) return '未答题';
                    return `${Math.round(Number(pct) * 10) / 10}%`;
                  },
                },
                {
                  title: '完成时间',
                  dataIndex: 'completedAt',
                  key: 'completedAt',
                  render: (date: string | null) => (date ? formatDateTime(date) : '未答题'),
                },
              ]}
              dataSource={reportData.details}
              rowKey="userId"
              size="small"
              pagination={false}
            />
          </div>
        )}
      </Modal>
    </GlassCard>
  );
};

export default ExamTaskPage;
