import React, { useState, useEffect } from 'react';
import { Card, Typography, Button, Space, Tag, message, Empty, Radio, Modal, Input } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import apiClient from '../../utils/request';
import dayjs from 'dayjs';
import { useAuthStore } from '../../store/authStore';

const { Title, Paragraph, Text } = Typography;

interface Quotation {
  id: number;
  version: number;
  quotation_date: string;
  amount: number;
  currency: string;
  status: 'draft' | 'sent' | 'approved' | 'rejected';
  file_url?: string;
  remark?: string;
  created_at: string;
}

interface BudgetProject {
  id: number;
  name: string;
  customer_id: number;
  customer_name: string;
  manager_id: number;
  manager_name: string;
  location?: string;
  survey_date?: string;
  intermediary?: string;
  intermediary_fee_type?: 'fixed' | 'percentage';
  intermediary_fee_value?: number;
  customer_requirements?: string;
  project_overview?: string;
  attachments?: string[];
  survey_photos?: string[];
  status: 'negotiating' | 'signed' | 'unsigned';
  days_in_status: number;
  created_at: string;
  quotations: Quotation[];
}

type StatusFilter = 'all' | 'negotiating' | 'signed' | 'unsigned';

const CURRENCIES: Record<string, { label: string; symbol: string }> = {
  CNY: { label: '人民币', symbol: '¥' },
  USD: { label: '美元', symbol: '$' },
  LAK: { label: '老挝基普', symbol: '₭' },
  THB: { label: '泰铢', symbol: '฿' },
};

const BudgetProjectList: React.FC = () => {
  const [isMobile, setIsMobile] = useState(false);
  const [projects, setProjects] = useState<BudgetProject[]>([]);
  const [loading, setLoading] = useState(false);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteProjectId, setDeleteProjectId] = useState<number | null>(null);
  const [deletePassword, setDeletePassword] = useState('');
  const [deleteLoading, setDeleteLoading] = useState(false);
  const navigate = useNavigate();

  const { user: currentUser } = useAuthStore();
  const isAdmin = currentUser?.role === 'admin' || false;

  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth <= 768);
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

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

  const fetchProjects = async () => {
    setLoading(true);
    try {
      const res = await apiClient.get('/budget-projects');
      if (res.data.success) {
        // 后端已经解析了数据，直接使用
        const projectsWithParsedData = res.data.data.map((project: any) => {
          return {
            ...project,
            quotations: Array.isArray(project.quotations) ? project.quotations : [],
            attachments: Array.isArray(project.attachments) ? project.attachments : [],
            survey_photos: Array.isArray(project.survey_photos) ? project.survey_photos : []
          };
        });
        setProjects(projectsWithParsedData);
      }
    } catch (error) {
      console.error('获取预算项目失败:', error);
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const filteredProjects = projects.filter(p => 
    statusFilter === 'all' || p.status === statusFilter
  );

  const getStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; text: string }> = {
      negotiating: { color: 'processing', text: '商谈中' },
      signed: { color: 'success', text: '已签约' },
      unsigned: { color: 'error', text: '未签约' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getQuotationStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; text: string }> = {
      draft: { color: 'default', text: '草稿' },
      sent: { color: 'processing', text: '已发送' },
      approved: { color: 'success', text: '已通过' },
      rejected: { color: 'error', text: '已拒绝' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const formatAmount = (amount: number, currency: string = 'CNY') => {
    const c = CURRENCIES[currency];
    const symbol = c?.symbol || '¥';
    return `${symbol}${amount.toLocaleString('zh-CN')}`;
  };

  const handleDeleteProject = (projectId: number) => {
    setDeleteProjectId(projectId);
    setDeletePassword('');
    setDeleteModalVisible(true);
  };

  const handleDeleteConfirm = async () => {
    if (!deleteProjectId) return;
    
    // 验证密码（这里简单验证，实际项目中应该使用更安全的验证方式）
    if (deletePassword !== 'X123c321@') {
      message.error('密码错误');
      return;
    }
    
    setDeleteLoading(true);
    try {
      const res = await apiClient.delete(`/budget-projects/${deleteProjectId}`, {
        headers: {
          'x-user-role': currentUser?.role || 'employee'
        }
      });
      if (res.data.success) {
        message.success('删除成功');
        setDeleteModalVisible(false);
        fetchProjects();
      }
    } catch (error) {
      message.error('删除失败');
    } finally {
      setDeleteLoading(false);
    }
  };

  return (
    <div style={{ padding: isMobile ? 8 : 24 }}>
      <div style={{ marginBottom: isMobile ? 12 : 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <Title level={isMobile ? 3 : 2} style={{ marginBottom: 8 }}>预算报价管理</Title>
            <Paragraph type="secondary" style={{ marginBottom: 0 }}>管理商谈项目及报价版本</Paragraph>
          </div>
          {isAdmin && (
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={() => navigate('/budget-projects/create')}
              size={isMobile ? 'middle' : 'large'}
            >
              新建商谈项目
            </Button>
          )}
        </div>
      </div>

      {/* 状态筛选 */}
      <Card style={{ marginBottom: 16 }}>
        <Space>
          <Text strong>状态筛选:</Text>
          <Radio.Group 
            value={statusFilter} 
            onChange={(e) => setStatusFilter(e.target.value)}
            optionType="button"
            buttonStyle="solid"
          >
            <Radio.Button value="all">全部</Radio.Button>
            <Radio.Button value="negotiating">商谈中</Radio.Button>
            <Radio.Button value="signed">已签约</Radio.Button>
            <Radio.Button value="unsigned">未签约</Radio.Button>
          </Radio.Group>
        </Space>
      </Card>

      {/* 项目列表 */}
      <Card loading={loading}>
        {filteredProjects.length === 0 ? (
          <Empty description="暂无数据" />
        ) : (
          <div>
            {filteredProjects.map((project) => (
              <div 
                key={project.id} 
                style={{ 
                  border: '1px solid #f0f0f0', 
                  borderRadius: 8, 
                  marginBottom: 16,
                  overflow: 'hidden'
                }}
              >
                {/* 项目头部 */}
                <div 
                  style={{ 
                    padding: '16px 20px', 
                    background: '#fafafa',
                    borderBottom: '1px solid #f0f0f0',
                    cursor: 'pointer'
                  }}
                  onClick={() => navigate(`/budget-projects/${project.id}`)}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12 }}>
                    <Space size="middle">
                      <Text strong style={{ fontSize: 16 }}>{project.name}</Text>
                    </Space>
                    <Space>
                      {getStatusTag(project.status)}
                      <Text type="secondary">{project.days_in_status}天</Text>
                      {isAdmin && (
                        <Button 
                          danger 
                          size="small"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleDeleteProject(project.id);
                          }}
                        >
                          删除
                        </Button>
                      )}
                    </Space>
                  </div>
                  
                  <div style={{ marginTop: 12 }}>
                    <Space direction="vertical" size={4} style={{ width: '100%' }}>
                      <Text type="secondary">客户: {project.customer_name}</Text>
                      <Text type="secondary">业务经理: {project.manager_name}</Text>
                      {project.intermediary && (
                        <Text type="secondary">
                          居间人: {project.intermediary}
                          {project.intermediary_fee_value && (
                            <span> 居间费: {formatAmount(project.intermediary_fee_value, 'CNY')}</span>
                          )}
                        </Text>
                      )}
                    </Space>
                  </div>
                </div>


              </div>
            ))}
          </div>
        )}
      </Card>

      {/* 删除确认模态框 */}
      <Modal
        title="删除确认"
        open={deleteModalVisible}
        onOk={handleDeleteConfirm}
        onCancel={() => setDeleteModalVisible(false)}
        confirmLoading={deleteLoading}
        okText="确认删除"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <p>确定要删除这个预算项目吗？此操作不可恢复。</p>
          <p>请输入管理员密码确认删除操作：</p>
        </div>
        <Input.Password
          placeholder="请输入管理员密码"
          value={deletePassword}
          onChange={(e) => setDeletePassword(e.target.value)}
          size="large"
        />
      </Modal>
    </div>
  );
};

export default BudgetProjectList;
