import React, { useState, useEffect } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, message, Card, Radio, DatePicker, Select } from 'antd';
import { EyeOutlined, CheckCircleOutlined, SearchOutlined, UserOutlined } from '@ant-design/icons';
import axios from 'axios';
import API_BASE_URL from '../config';
import AchievementDetails from '../components/AchievementDetails';
import { maskPhone } from '../utils/phoneMask';

const Audit = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [detailsVisible, setDetailsVisible] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [keyword, setKeyword] = useState('');
  const [dateRange, setDateRange] = useState(null);
  const [filterType, setFilterType] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterType]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const params = {
        status: 'pending',
        type: filterType,
        keyword: keyword,
        startDate: dateRange && dateRange[0] ? dateRange[0].format('YYYY-MM-DD') : null,
        endDate: dateRange && dateRange[1] ? dateRange[1].format('YYYY-MM-DD') : null
      };
      const response = await axios.get(`${API_BASE_URL}/api/achievements`, {
        headers: { Authorization: `Bearer ${token}` },
        params
      });
      setData(response.data);
    } catch (error) {
      message.error('获取待审核列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAudit = (record) => {
    setCurrentRecord(record);
    setIsModalVisible(true);
  };

  const submitAudit = async (values) => {
    try {
      const token = localStorage.getItem('token');
      await axios.post(`${API_BASE_URL}/api/achievements/audit/${currentRecord.id}`, values, {
        headers: { Authorization: `Bearer ${token}` }
      });
      message.success('审核提交成功');
      setIsModalVisible(false);
      form.resetFields();
      fetchData();
    } catch (error) {
      const errorMsg = error.response?.data?.message || '审核提交失败';
      message.error(errorMsg);
    }
  };

  const columns = [
    { 
      title: '类型', 
      dataIndex: 'type', 
      key: 'type',
      width: 80,
      render: (type) => {
        const typeMap = {
          paper: '论文', project: '项目', award: '奖励', standard: '标准',
          monograph: '专著', report: '技术报告', plan: '规划', patent: '专利',
          transformation: '成果转化', software: '软著'
        };
        return <Tag color="blue">{typeMap[type] || type}</Tag>;
      }
    },
    {
      title: '成果名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      render: (text, record) => {
        const dateLabels = {
          paper: '发表日期', project: '验收时间', award: '获奖日期', standard: '发布日期',
          monograph: '出版时间', report: '报告提交时间', plan: '发布日期', patent: '授权时间',
          transformation: '验收时间', software: '授权证书时间'
        };
        const dateLabel = dateLabels[record.type] || '成果时间';
        
        return (
          <Space direction="vertical" size={0}>
            <b>{text}</b>
            <small style={{ color: '#888' }}>
              {dateLabel}: {record.achievement_date ? new Date(record.achievement_date).toLocaleDateString() : '无'}
            </small>
          </Space>
        );
      }
    },
    {
      title: '提交人',
      key: 'submitter',
      width: 150,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <span><UserOutlined style={{ marginRight: 4 }} />{record.submitter_name || '未知'}</span>
          <small style={{ color: '#888' }}>{maskPhone(record.username)}</small>
        </Space>
      )
    },
    {
      title: '完成人',
      dataIndex: 'contributors',
      key: 'contributors',
      render: (contributors) => (
        <Space size={[0, 4]} wrap>
          {(contributors || []).map((c, idx) => (
            <Tag key={idx} color={c.isMain ? 'orange' : 'default'} style={{ borderRadius: '10px' }}>
              {c.name}
              {c.isMain && <span style={{ marginLeft: 2, fontSize: '10px' }}>★</span>}
            </Tag>
          ))}
        </Space>
      )
    },
    {
      title: '归属部门',
      dataIndex: 'assigned_departments',
      key: 'assigned_departments',
      render: (depts) => (
        <Space size={[0, 4]} wrap>
          {(depts || []).map(dept => (
            <Tag color="cyan" key={dept}>{dept}</Tag>
          ))}
        </Space>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <Space>
          <Button 
            size="small"
            icon={<EyeOutlined />} 
            onClick={() => {
              setSelectedId(record.id);
              setDetailsVisible(true);
            }}
          >
            详情
          </Button>
          <Button 
            size="small"
            type="primary" 
            icon={<CheckCircleOutlined />}
            onClick={() => handleAudit(record)}
          >
            审核
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Card title="成果审核管理">
      <div style={{ marginBottom: 16 }}>
        <Space wrap>
          <Input 
            placeholder="搜索名称/完成人/手机号" 
            style={{ width: 200 }} 
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
            onPressEnter={fetchData}
            allowClear
          />
          <DatePicker.RangePicker 
            style={{ width: 250 }}
            onChange={setDateRange}
          />
          <Select
            placeholder="按类型筛选"
            style={{ width: 120 }}
            allowClear
            onChange={setFilterType}
          >
            <Select.Option value="paper">论文</Select.Option>
            <Select.Option value="project">项目</Select.Option>
            <Select.Option value="award">奖励</Select.Option>
            <Select.Option value="standard">标准</Select.Option>
            <Select.Option value="monograph">专著</Select.Option>
            <Select.Option value="report">技术报告</Select.Option>
            <Select.Option value="plan">规划</Select.Option>
            <Select.Option value="patent">专利</Select.Option>
            <Select.Option value="transformation">成果转化</Select.Option>
            <Select.Option value="software">软著</Select.Option>
          </Select>
          <Button type="primary" icon={<SearchOutlined />} onClick={fetchData}>查询</Button>
        </Space>
      </div>
      <Table columns={columns} dataSource={data} rowKey="id" loading={loading} size="middle" />
      
      <AchievementDetails 
        id={selectedId} 
        open={detailsVisible} 
        onClose={() => {
          setDetailsVisible(false);
          setSelectedId(null);
        }} 
      />

      <Modal
        title="成果审核"
        open={isModalVisible}
        onOk={() => form.submit()}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        destroyOnClose
      >
        <Form form={form} onFinish={submitAudit} layout="vertical">
          <Form.Item name="status" label="审核结果" rules={[{ required: true, message: '请选择审核结果' }]}>
            <Radio.Group buttonStyle="solid">
              <Radio.Button value="approved">通过</Radio.Button>
              <Radio.Button value="rejected">不通过</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="audit_comment" label="审核意见">
            <Input.TextArea rows={4} placeholder="请输入审核意见..." />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default Audit;
