import React, { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { projectAPI } from '../../services/project';

const ProjectList = ({ mode = 'list' }) => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [filters, setFilters] = useState({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({
    project_no: '',
    name: '',
    engineering_type: '',
    contract_amount: '',
    signing_date: '',
    start_date: '',
    planned_end_date: '',
  });

  useEffect(() => {
    if (mode === 'list') {
      fetchProjects();
    }
  }, [mode]);

  const fetchProjects = async (params = {}) => {
    try {
      setLoading(true);
      const result = await projectAPI.getList({
        page: pagination.current,
        page_size: pagination.pageSize,
        ...filters,
        ...params,
      });
      setList(result.items || []);
      setTotal(result.total || 0);
    } catch (error) {
      console.error('Failed to fetch projects:', error);
      alert('获取项目列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (page) => {
    setPagination({ ...pagination, current: page });
    fetchProjects({ page });
  };

  const handleCreate = () => {
    setEditingId(null);
    setForm({
      project_no: '',
      name: '',
      engineering_type: '',
      contract_amount: '',
      signing_date: '',
      start_date: '',
      planned_end_date: '',
    });
    setModalVisible(true);
  };

  const handleEdit = async (id) => {
    try {
      const project = await projectAPI.getDetail(id);
      setForm(project);
      setEditingId(id);
      setModalVisible(true);
    } catch (error) {
      console.error('Failed to fetch project detail:', error);
      alert('获取项目详情失败');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('确定要删除该项目吗？')) {
      return;
    }

    try {
      await projectAPI.delete(id);
      alert('项目删除成功');
      fetchProjects();
    } catch (error) {
      console.error('Failed to delete project:', error);
      alert('删除项目失败');
    }
  };

  const handleView = (id) => {
    navigate(`/projects/${id}`);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const requiredFields = ['project_no', 'name', 'engineering_type', 'contract_amount'];
    const missingFields = requiredFields.filter(field => !form[field]);

    if (missingFields.length > 0) {
      alert(`请填写必填字段: ${missingFields.join(', ')}`);
      return;
    }

    try {
      if (editingId) {
        await projectAPI.update(editingId, form);
        alert('项目更新成功');
      } else {
        await projectAPI.create(form);
        alert('项目创建成功');
      }

      setModalVisible(false);
      fetchProjects();
    } catch (error) {
      console.error('Failed to save project:', error);
      alert('保存项目失败');
    }
  };

  const handleCancel = () => {
    setModalVisible(false);
    setEditingId(null);
    setForm({
      project_no: '',
      name: '',
      engineering_type: '',
      contract_amount: '',
      signing_date: '',
      start_date: '',
      planned_end_date: '',
    });
  };

  const canEdit = (createdBy) => {
    return user.role === 'admin' || (user.role === 'market' && createdBy === user?.id);
  };

  const canDelete = (createdBy) => {
    return user.role === 'admin' || (user.role === 'market' && createdBy === user?.id);
  };

  return (
    <div>
      <h1 style={{ fontSize: '24px', marginBottom: '24px' }}>
        {mode === 'create' ? '新建项目' : '项目列表'}
      </h1>

      <div style={{ marginBottom: '16px', display: 'flex', gap: '12px' }}>
        <input
          type="text"
          placeholder="搜索项目名称、合同编号..."
          style={{
            padding: '8px 12px',
            border: '1px solid #d9d9d9',
            borderRadius: '4px',
            fontSize: '14px',
            width: '300px',
          }}
        />
        <select
          style={{
            padding: '8px 12px',
            border: '1px solid #d9d9d9',
            borderRadius: '4px',
            fontSize: '14px',
          }}
        >
          <option value="">工程类别</option>
          <option value="基建">基建</option>
          <option value="业扩">业扩</option>
          <option value="客户">客户</option>
          <option value="营销">营销</option>
          <option value="检修">检修</option>
        </select>
        {user?.role === 'admin' && (
          <button
            className="btn btn-primary"
            onClick={handleCreate}
          >
            新建项目
          </button>
        )}
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px' }}>加载中...</div>
      ) : list.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          暂无项目
        </div>
      ) : (
        <>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: '#fafafa' }}>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: '14px', fontWeight: 600, borderBottom: '1px solid #e8e8e8' }}>
                  合同编号
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  项目名称
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  工程类别
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'right', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  合同金额（万元）
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'center', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  操作
                </th>
              </tr>
            </thead>
            <tbody>
              {list.map((project) => (
                <tr
                  key={project.id}
                  style={{
                    borderBottom: '1px solid #f0f0f0',
                    cursor: 'pointer',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.background = '#fafafa';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.background = 'transparent';
                  }}
                  onClick={() => handleView(project.id)}
                >
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#666' }}>
                    {project.project_no}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#333' }}>
                    {project.name}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#666' }}>
                    {project.engineering_type}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#666', textAlign: 'right' }}>
                    {project.contract_amount?.toLocaleString('zh-CN')}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', textAlign: 'center' }}>
                    <button
                      className="btn btn-link"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleView(project.id);
                      }}
                    >
                      查看
                    </button>
                    {canEdit(project.created_by) && (
                      <button
                        className="btn btn-link"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleEdit(project.id);
                        }}
                      >
                        编辑
                      </button>
                    )}
                    {canDelete(project.created_by) && (
                      <button
                        className="btn btn-danger"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDelete(project.id);
                        }}
                      >
                        删除
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          <div
            style={{
              marginTop: '24px',
              display: 'flex',
              justifyContent: 'center',
              gap: '12px',
            }}
          >
            {total > pagination.pageSize && (
              <>
                <button
                  className="btn btn-default"
                  disabled={pagination.current === 1}
                  onClick={() => handlePageChange(pagination.current - 1)}
                >
                  上一页
                </button>
                <span>
                  {pagination.current} / {Math.ceil(total / pagination.pageSize)}
                </span>
                <button
                  className="btn btn-default"
                  disabled={pagination.current >= Math.ceil(total / pagination.pageSize)}
                  onClick={() => handlePageChange(pagination.current + 1)}
                >
                  下一页
                </button>
              </>
            )}
          </div>
        </>
      )}
      {modalVisible && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            background: 'rgba(0, 0, 0, 0.45)',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            zIndex: 1000,
          }}
          onClick={handleCancel}
        >
          <div
            style={{
              background: '#ffffff',
              width: '800px',
              maxWidth: '90vw',
              maxHeight: '90vh',
              borderRadius: '8px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                padding: '16px 24px',
                borderBottom: '1px solid #e8e8e8',
                fontSize: '16px',
                fontWeight: 600',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              {editingId ? '编辑项目' : '新建项目'}
              <button
                style={{
                  background: 'transparent',
                  border: 'none',
                  fontSize: '20px',
                  cursor: 'pointer',
                  color: '#999',
                }}
                onClick={handleCancel}
              >
                ×
              </button>
            </div>
            <form onSubmit={handleSubmit}>
              <div style={{ padding: '24px' }}>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    合同编号 *
                  </label>
                  <input
                    type="text"
                    name="project_no"
                    value={form.project_no}
                    onChange={handleChange}
                    required
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    项目名称 *
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={form.name}
                    onChange={handleChange}
                    required
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    工程类别 *
                  </label>
                  <select
                    name="engineering_type"
                    value={form.engineering_type}
                    onChange={handleChange}
                    required
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  >
                    <option value="">请选择</option>
                    <option value="基建">基建</option>
                    <option value="业扩">业扩</option>
                    <option value="客户">客户</option>
                    <option value="营销">营销</option>
                    <option value="检修">检修</option>
                  </select>
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    合同金额（万元） *
                  </label>
                  <input
                    type="number"
                    name="contract_amount"
                    value={form.contract_amount}
                    onChange={handleChange}
                    required
                    min="0"
                    step="0.01"
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    签订日期 *
                  </label>
                  <input
                    type="date"
                    name="signing_date"
                    value={form.signing_date}
                    onChange={handleChange}
                    required
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    开工日期
                  </label>
                  <input
                    type="date"
                    name="start_date"
                    value={form.start_date}
                    onChange={handleChange}
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    计划竣工日期
                  </label>
                  <input
                    type="date"
                    name="planned_end_date"
                    value={form.planned_end_date}
                    onChange={handleChange}
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div
                  style={{
                    marginTop: '24px',
                    padding: '16px 24px',
                    borderTop: '1px solid #e8e8e8',
                    display: 'flex',
                    justifyContent: 'flex',
                    gap: '12px',
                  }}
                >
                  <button
                    className="btn btn-default"
                    onClick={handleCancel}
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    className="btn btn-primary"
                    onClick={() => {}}
                  >
                    保存
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProjectList;
