import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Form, Input, DatePicker, InputNumber, Select, Upload, Button, message } from 'antd';
import { UploadOutlined, DeleteOutlined, FileOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import apiClient from '../../utils/request';
import useFormDraft from '../../hooks/useFormDraft';

const { Option } = Select;

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

interface BudgetProject {
  id: number;
  name: string;
  quotations: Quotation[];
}

interface QuotationCreateModalProps {
  visible: boolean;
  project: BudgetProject | null;
  onCancel: () => void;
  onSuccess: () => void;
}

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

const QuotationCreateModal: React.FC<QuotationCreateModalProps> = ({
  visible,
  project,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [uploadedFile, setUploadedFile] = useState<{ url: string; name: string } | null>(null);

  // 表单草稿保护
  const { save: saveDraft, restore: restoreDraft, clear: clearDraft, hasDraft } = useFormDraft({
    form,
    storageKey: 'quotation_create',
    onRestore: (data) => {
      if (data.uploadedFile) setUploadedFile(data.uploadedFile)
    },
  })

  const handleFormChange = useCallback(() => {
    saveDraft({ uploadedFile })
  }, [saveDraft, uploadedFile])

  // 计算下一个版本号
  const nextVersion = project?.quotations && Array.isArray(project.quotations) && project.quotations.length > 0
    ? Math.max(...project.quotations.map(q => q.version || 0)) + 1
    : 1;

  useEffect(() => {
    if (visible) {
      form.resetFields();
      form.setFieldsValue({
        quotation_date: dayjs(),
        currency: 'CNY',
        version: nextVersion,
      });
      setUploadedFile(null);
    }
  }, [visible, nextVersion, form]);

  const handleUpload = async (options: any) => {
    const { file, onSuccess: onUploadSuccess, onError } = options;
    
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('/api/upload/single', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (result.success) {
        message.success('上传成功');
        setUploadedFile({ url: result.data.url, name: file.name });
        onUploadSuccess(result.data, file);
      } else {
        message.error(result.error || '上传失败');
        onError?.(new Error(result.error));
      }
    } catch (error: any) {
      message.error('上传失败');
      onError?.(error);
    }
  };

  const handleRemoveFile = () => {
    setUploadedFile(null);
  };

  const handleSubmit = async () => {
    if (!project) return;

    try {
      const values = await form.validateFields();
      setLoading(true);

      const quotationData = {
        ...values,
        quotation_date: values.quotation_date.format('YYYY-MM-DD'),
        file_url: uploadedFile?.url,
        version: nextVersion,
      };

      const res = await apiClient.post(`/budget-projects/${project.id}/quotations`, quotationData, {
        headers: {
          'x-user-role': 'admin' // 创建报价版本需要管理员权限
        }
      });
      if (res.data.success) {
        message.success('新增报价版本成功');
        clearDraft()
        onSuccess();
      }
    } catch (error: any) {
      if (error.response?.data?.error) {
        message.error(error.response.data.error);
      } else {
        message.error('创建失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const getFileIcon = () => (
    <div
      style={{
        width: 60,
        height: 60,
        border: '1px solid #d9d9d9',
        borderRadius: 4,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#fafafa',
      }}
    >
      <FileOutlined style={{ fontSize: 24, color: '#1890ff' }} />
    </div>
  );

  return (
    <Modal
      title="新增报价版本"
      open={visible}
      onOk={handleSubmit}
      onCancel={() => {
        if (form.isFieldsTouched()) {
          Modal.confirm({
            title: '确认关闭',
            content: '表单数据尚未保存，关闭后可通过草稿恢复。确定关闭吗？',
            okText: '关闭',
            cancelText: '继续编辑',
            onOk: () => {
              saveDraft({ uploadedFile })
              onCancel()
            },
          })
        } else {
          onCancel()
        }
      }}
      width={600}
      confirmLoading={loading}
      okText="保存"
      cancelText="取消"
      maskClosable={false}
    >
      <Form form={form} layout="vertical" onValuesChange={handleFormChange}>
        {/* 项目信息展示 */}
        <div style={{ 
          padding: 16, 
          background: '#f5f5f5', 
          borderRadius: 8, 
          marginBottom: 24 
        }}>
          <div style={{ marginBottom: 8 }}>
            <span style={{ color: '#666' }}>项目名称: </span>
            <span style={{ fontWeight: 500 }}>{project?.name}</span>
          </div>
          <div>
            <span style={{ color: '#666' }}>当前版本: </span>
            <span style={{ fontWeight: 500 }}>V{nextVersion - 1}</span>
            <span style={{ color: '#999', marginLeft: 8 }}>
              (新创建将为 V{nextVersion})
            </span>
          </div>
        </div>

        <Form.Item
          name="quotation_date"
          label="报价日期"
          rules={[{ required: true, message: '请选择报价日期' }]}
        >
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="amount"
          label="报价金额"
          rules={[{ required: true, message: '请输入报价金额' }]}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={0}
            precision={2}
            placeholder="请输入报价金额"
            addonAfter="元"
          />
        </Form.Item>

        <Form.Item
          name="currency"
          label="币种"
          rules={[{ required: true, message: '请选择币种' }]}
        >
          <Select placeholder="请选择币种">
            {CURRENCIES.map((c) => (
              <Option key={c.value} value={c.value}>
                {c.label} ({c.symbol})
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item label="报价文件">
          {uploadedFile ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              {getFileIcon()}
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500 }}>{uploadedFile.name}</div>
                <a href={uploadedFile.url} target="_blank" rel="noopener noreferrer">
                  查看文件
                </a>
              </div>
              <Button 
                danger 
                icon={<DeleteOutlined />} 
                onClick={handleRemoveFile}
                size="small"
              >
                删除
              </Button>
            </div>
          ) : (
            <Upload
              accept=".pdf,.doc,.docx,.xlsx,.xls,.jpg,.jpeg,.png"
              customRequest={handleUpload}
              showUploadList={false}
              maxCount={1}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          )}
        </Form.Item>

        <Form.Item name="remark" label="备注">
          <Input.TextArea rows={3} placeholder="请输入备注信息" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default QuotationCreateModal;
