import React, { useState, useEffect } from 'react';
import { Card, Button, Progress, Tag, Checkbox, Input, Upload, Space, Spin, message, List, Typography, Modal, Image, Divider } from 'antd';
import { ArrowLeftOutlined, CameraOutlined, CheckCircleOutlined, ClockCircleOutlined, MinusCircleOutlined, UndoOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import apiClient from '../../utils/request';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

interface Phase {
  id: number;
  phase_name: string;
  phase_order: number;
  phase_type: string;
  depends_on: number[];
  status: string;
  started_at: string | null;
  completed_at: string | null;
  remark: string | null;
  photos: string[];
  sub_items: { name: string; completed: boolean }[];
}

const ConstructionProgress: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [project, setProject] = useState<any>(null);
  const [phases, setPhases] = useState<Phase[]>([]);
  const [loading, setLoading] = useState(false);
  const [completingPhaseId, setCompletingPhaseId] = useState<number | null>(null);
  const [remark, setRemark] = useState('');
  const navigate = useNavigate();

  useEffect(() => { if (id) { fetchProject(); fetchPhases(); } }, [id]);

  const fetchProject = async () => {
    try {
      const res = await apiClient.get(`/projects/${id}`);
      if (res.data.success) setProject(res.data.data);
    } catch (e) { message.error('获取项目信息失败'); }
  };

  const fetchPhases = async () => {
    setLoading(true);
    try {
      const res = await apiClient.get(`/projects/${id}/phases`);
      if (res.data.success) setPhases(res.data.data || []);
    } catch (e) { message.error('获取阶段信息失败'); }
    finally { setLoading(false); }
  };

  const handleCompletePhase = (phaseId: number) => {
    setCompletingPhaseId(phaseId);
    setRemark('');
  };

  const confirmComplete = async () => {
    if (!completingPhaseId || !id) return;
    try {
      const res = await apiClient.put(`/projects/${id}/phases/${completingPhaseId}/complete`, {
        remark,
        completed_by: 1,
      });
      if (res.data.success) {
        message.success(`阶段完成！进度: ${res.data.data.progress}%`);
        if (res.data.data.nextPhase) {
          message.info(`已推进到: ${res.data.data.nextPhase}`);
        }
        fetchPhases();
        fetchProject();
      }
    } catch (e) { message.error('操作失败'); }
    finally { setCompletingPhaseId(null); }
  };

  const handleReopen = async (phaseId: number) => {
    if (!id) return;
    Modal.confirm({
      title: '重新打开阶段',
      content: '确定要重新打开此阶段吗？项目进度将回退。',
      onOk: async () => {
        try {
          const res = await apiClient.put(`/projects/${id}/phases/${phaseId}/reopen`, {});
          if (res.data.success) {
            message.success('阶段已重新打开');
            fetchPhases();
            fetchProject();
          }
        } catch (e) { message.error('操作失败'); }
      },
    });
  };

  const handleSubItemToggle = async (phaseId: number, subItemIndex: number, completed: boolean) => {
    if (!id) return;
    try {
      await apiClient.put(`/projects/${id}/phases/${phaseId}/sub-item`, {
        sub_item_index: subItemIndex,
        completed,
      });
      fetchPhases();
    } catch (e) { message.error('更新子项失败'); }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return <CheckCircleOutlined style={{ color: '#52c41a', fontSize: 20 }} />;
      case 'in_progress': return <ClockCircleOutlined style={{ color: '#1890ff', fontSize: 20 }} />;
      default: return <MinusCircleOutlined style={{ color: '#d9d9d9', fontSize: 20 }} />;
    }
  };

  const getStatusTag = (status: string) => {
    switch (status) {
      case 'completed': return <Tag color="green">已完成</Tag>;
      case 'in_progress': return <Tag color="blue">进行中</Tag>;
      default: return <Tag>待开始</Tag>;
    }
  };

  const currentPhase = phases.find(p => p.status === 'in_progress');
  const completedPhases = phases.filter(p => p.status === 'completed').reverse();
  const pendingPhases = phases.filter(p => p.status === 'pending');
  const progress = project?.phase_progress || 0;

  return (
    <div style={{ padding: '16px', maxWidth: 600, margin: '0 auto' }}>
      <div style={{ marginBottom: 16 }}>
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/construction')}>返回总览</Button>
      </div>

      <Card style={{ marginBottom: 16 }}>
        <Title level={4} style={{ margin: 0 }}>{project?.name || '加载中...'}</Title>
        <div style={{ marginTop: 8 }}>
          <Progress percent={progress} strokeColor="#1890ff" />
          <Space style={{ marginTop: 4 }}>
            {project?.current_phase && <Tag color="blue">当前: {project.current_phase}</Tag>}
            {getStatusTag(project?.status)}
          </Space>
        </div>
      </Card>

      <Spin spinning={loading}>
        {currentPhase && (
          <Card
            title={<Space>{getStatusIcon('in_progress')} 📍 当前阶段：{currentPhase.phase_name}</Space>}
            style={{ marginBottom: 16, borderColor: '#1890ff', borderWidth: 2 }}
          >
            {currentPhase.phase_type === 'parallel' && (
              <Tag color="blue" style={{ marginBottom: 8 }}>并行阶段（可与其他阶段同时进行）</Tag>
            )}

            {currentPhase.sub_items && currentPhase.sub_items.length > 0 && (
              <div style={{ marginBottom: 16 }}>
                <Text strong>完工标准：</Text>
                <div style={{ marginTop: 8 }}>
                  {currentPhase.sub_items.map((item, idx) => (
                    <div key={idx} style={{ marginBottom: 4 }}>
                      <Checkbox
                        checked={item.completed}
                        onChange={(e) => handleSubItemToggle(currentPhase.id, idx, e.target.checked)}
                      >
                        <Text delete={item.completed} type={item.completed ? 'secondary' : undefined}>{item.name}</Text>
                      </Checkbox>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div style={{ marginBottom: 16 }}>
              <Text strong>备注（可选）：</Text>
              <TextArea rows={2} value={remark} onChange={e => setRemark(e.target.value)} placeholder="填写完成备注..." style={{ marginTop: 4 }} />
            </div>

            <Button
              type="primary"
              size="large"
              block
              icon={<CheckCircleOutlined />}
              onClick={() => handleCompletePhase(currentPhase.id)}
            >
              确认完成此阶段
            </Button>
          </Card>
        )}

        {pendingPhases.length > 0 && (
          <Card title="后续阶段" style={{ marginBottom: 16 }} size="small">
            {pendingPhases.map(phase => (
              <div key={phase.id} style={{ padding: '8px 0', borderBottom: '1px solid #f0f0f0' }}>
                <Space>
                  {getStatusIcon('pending')}
                  <Text type="secondary">{phase.phase_order}. {phase.phase_name}</Text>
                  {phase.phase_type === 'parallel' && <Tag color="blue">并行</Tag>}
                </Space>
              </div>
            ))}
          </Card>
        )}

        {completedPhases.length > 0 && (
          <Card title="阶段历史" size="small">
            {completedPhases.map(phase => (
              <div key={phase.id} style={{ padding: '8px 0', borderBottom: '1px solid #f0f0f0' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Space>
                    {getStatusIcon('completed')}
                    <Text>{phase.phase_order}. {phase.phase_name}</Text>
                  </Space>
                  <Space>
                    {phase.completed_at && <Text type="secondary" style={{ fontSize: 12 }}>{new Date(phase.completed_at).toLocaleDateString()}</Text>}
                    <Button size="small" type="link" icon={<UndoOutlined />} onClick={() => handleReopen(phase.id)}>回退</Button>
                  </Space>
                </div>
                {phase.remark && <Paragraph type="secondary" style={{ margin: '4px 0 0 28px', fontSize: 12 }}>{phase.remark}</Paragraph>}
              </div>
            ))}
          </Card>
        )}

        {!currentPhase && pendingPhases.length === 0 && completedPhases.length === 0 && (
          <Card>
            <div style={{ textAlign: 'center', padding: 24 }}>
              <Text type="secondary">此项目尚未初始化施工阶段</Text>
              <div style={{ marginTop: 16 }}>
                <Button type="primary" onClick={() => navigate(`/projects/${id}`)}>返回项目详情</Button>
              </div>
            </div>
          </Card>
        )}
      </Spin>

      <Modal
        title="确认完成阶段"
        open={completingPhaseId !== null}
        onOk={confirmComplete}
        onCancel={() => setCompletingPhaseId(null)}
        okText="确认完成"
        cancelText="取消"
      >
        <Paragraph>确认此阶段已完成？系统将自动推进到下一阶段。</Paragraph>
        {remark && <Paragraph type="secondary">备注：{remark}</Paragraph>}
      </Modal>
    </div>
  );
};

export default ConstructionProgress;
