import React, { useState, useEffect, useCallback } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { Table, Button, Modal, Form, Input, Select, message, Space, Tag, Card, Row, Col, Statistic } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ShopOutlined, BankOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import FileUpload from '../components/FileUpload'
import useFormDraft from '../hooks/useFormDraft'

interface Contact {
  name: string
  position: string
  phone: string
  is_primary?: boolean
}

interface PaymentInfo {
  account_name: string
  bank_account: string
  bank_name: string
  qr_code?: string
  is_primary: boolean
}

interface Supplier {
  id: number
  code: string
  name: string
  supply_category: string
  country: string
  contacts: Contact[]
  payment_infos: PaymentInfo[]
  remark: string
  total_purchase_amount: number
  total_paid: number
  total_payable: number
  created_at: string
}

const SupplierPage: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const [suppliers, setSuppliers] = useState<Supplier[]>([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingSupplier, setEditingSupplier] = useState<Supplier | null>(null)
  const [searchText, setSearchText] = useState('')
  const [form] = Form.useForm()
  
  // 从 location state 中获取返回路径
  const returnTo = (location.state as { returnTo?: string })?.returnTo

  // 表单草稿保护
  const { save: saveDraft, restore: restoreDraft, clear: clearDraft, hasDraft } = useFormDraft({
    form,
    storageKey: 'supplier_create',
  })

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

  const fetchSuppliers = async () => {
    setLoading(true)
    try {
      const response = await fetch('/api/suppliers')
      const data = await response.json()
      if (data.success) setSuppliers(data.data || [])
    } catch (error) {
      message.error('获取供应商列表失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { fetchSuppliers() }, [])

  const stats = {
    total: suppliers.length,
    totalPurchase: suppliers.reduce((sum, s) => sum + (s.total_purchase_amount || 0), 0),
    totalPayable: suppliers.reduce((sum, s) => sum + (s.total_payable || 0), 0)
  }

  const getPrimaryContact = (contacts: Contact[]) => {
    const primary = contacts?.find(c => c.is_primary)
    return primary?.name || '-'
  }

  const getPrimaryPaymentInfo = (paymentInfos: PaymentInfo[]) => {
    const primary = paymentInfos?.find(p => p.is_primary)
    return primary
  }

  const columns: ColumnsType<Supplier> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Button type="link" style={{ padding: 0, fontWeight: 'bold' }} onClick={() => navigate(`/suppliers/${record.id}`)}>
          {text}
        </Button>
      )
    },
    { title: '供应类别', dataIndex: 'supply_category', key: 'supply_category', width: 120 },
    { title: '国家', dataIndex: 'country', key: 'country', width: 80, render: (country) => <Tag>{country || '-'}</Tag> },
    { title: '采购金额', dataIndex: 'total_purchase_amount', key: 'total_purchase_amount', width: 100, render: (amount) => `¥${(amount || 0).toLocaleString()}` },
    { title: '应付金额', dataIndex: 'total_payable', key: 'total_payable', width: 100, render: (amount) => <span style={{ color: amount > 0 ? '#ff4d4f' : '#52c41a' }}>¥{(amount || 0).toLocaleString()}</span> },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="text" icon={<EditOutlined />} onClick={() => handleEdit(record)} size="small" />
          <Button type="text" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)} size="small" />
        </Space>
      )
    }
  ]

  const filteredSuppliers = suppliers.filter(s =>
    s.code?.toLowerCase().includes(searchText.toLowerCase()) ||
    s.name?.toLowerCase().includes(searchText.toLowerCase()) ||
    s.supply_category?.toLowerCase().includes(searchText.toLowerCase())
  )

  const handleContactChange = (index: number, field: string, value: any) => {
    form.setFieldsValue({
      contacts: form.getFieldValue('contacts').map((contact: any, i: number) => {
        if (field === 'is_primary' && value) {
          return i === index ? { ...contact, [field]: value } : { ...contact, is_primary: false }
        }
        return i === index ? { ...contact, [field]: value } : contact
      })
    })
  }

  const handlePaymentInfoChange = (index: number, field: string, value: any) => {
    form.setFieldsValue({
      payment_infos: form.getFieldValue('payment_infos').map((info: any, i: number) => {
        if (field === 'is_primary' && value) {
          return i === index ? { ...info, [field]: value } : { ...info, is_primary: false }
        }
        return i === index ? { ...info, [field]: value } : info
      })
    })
  }

  const handleSubmit = async (values: any) => {
    try {
      let contacts = values.contacts || [{ name: '', position: '', phone: '', is_primary: true }]
      const hasPrimary = contacts.some((c: Contact) => c.is_primary)
      if (!hasPrimary && contacts[0].name) contacts[0].is_primary = true
      
      let paymentInfos = values.payment_infos || []
      const hasPrimaryPayment = paymentInfos.some((p: PaymentInfo) => p.is_primary)
      if (!hasPrimaryPayment && paymentInfos.length > 0 && paymentInfos[0].account_name) {
        paymentInfos[0].is_primary = true
      }
      
      const url = editingSupplier ? `/api/suppliers/${editingSupplier.id}` : '/api/suppliers'
      const method = editingSupplier ? 'PUT' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...values, contacts, payment_infos: paymentInfos })
      })
      
      const data = await response.json()
      if (data.success) {
        message.success(editingSupplier ? '更新成功' : '创建成功')
        clearDraft()
        setModalVisible(false)
        form.resetFields()
        setEditingSupplier(null)
        fetchSuppliers()
        
        // 如果是从采购申请页面跳转过来的，创建成功后返回
        if (returnTo && !editingSupplier) {
          navigate(returnTo, { state: { supplierCreated: true } })
        }
      } else {
        message.error(data.message || '操作失败')
      }
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleEdit = (supplier: Supplier) => {
    setEditingSupplier(supplier)
    form.setFieldsValue({
      name: supplier.name,
      supply_category: supplier.supply_category,
      country: supplier.country,
      remark: supplier.remark,
      contacts: supplier.contacts?.length ? supplier.contacts : [{ name: '', position: '', phone: '', is_primary: true }],
      payment_infos: supplier.payment_infos?.length ? supplier.payment_infos : []
    })
    setModalVisible(true)
  }

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此供应商吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await fetch(`/api/suppliers/${id}`, { method: 'DELETE' })
          const data = await response.json()
          if (data.success) { message.success('删除成功'); fetchSuppliers() }
          else message.error(data.message || '删除失败')
        } catch (error) {
          message.error('删除失败')
        }
      }
    })
  }

  const handleAdd = () => {
    setEditingSupplier(null)
    form.resetFields()
    form.setFieldsValue({ 
      country: 'Laos', 
      contacts: [{ name: '', position: '', phone: '', is_primary: true }],
      payment_infos: []
    })
    setModalVisible(true)
    // 检查是否有草稿，提示用户是否恢复
    setTimeout(() => {
      if (hasDraft()) {
        Modal.confirm({
          title: '发现未完成的草稿',
          content: '检测到上次未提交的供应商信息，是否恢复？',
          okText: '恢复草稿',
          cancelText: '重新填写',
          onOk: () => {
            restoreDraft()
          },
          onCancel: () => {
            clearDraft()
            form.resetFields()
            form.setFieldsValue({ 
              country: 'Laos', 
              contacts: [{ name: '', position: '', phone: '', is_primary: true }],
              payment_infos: []
            })
          },
        })
      }
    }, 0)
  }
  
  // 如果是从采购申请页面跳转过来的，自动打开新增供应商弹窗
  useEffect(() => {
    if (returnTo) {
      handleAdd()
    }
  }, [returnTo])

  return (
    <div style={{ padding: 24 }}>
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={8}><Card><Statistic title="供应商总数" value={stats.total} prefix={<ShopOutlined />} /></Card></Col>
        <Col span={8}><Card><Statistic title="采购总金额" value={stats.totalPurchase} prefix="¥" valueStyle={{ color: '#1890ff' }} /></Card></Col>
        <Col span={8}><Card><Statistic title="应付总金额" value={stats.totalPayable} prefix="¥" valueStyle={{ color: stats.totalPayable > 0 ? '#ff4d4f' : '#52c41a' }} /></Card></Col>
      </Row>

      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Input placeholder="搜索供应商编号、名称或供应类别" prefix={<SearchOutlined />} value={searchText} onChange={(e) => setSearchText(e.target.value)} allowClear style={{ width: 350 }} />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增供应商</Button>
        </div>
      </Card>

      <Card>
        <Table columns={columns} dataSource={filteredSuppliers} rowKey="id" loading={loading} pagination={{ pageSize: 10, showTotal: (total) => `共 ${total} 条` }} scroll={{ x: 1100 }} />
      </Card>

      <Modal 
        title={editingSupplier ? '编辑供应商' : '新增供应商'} 
        open={modalVisible} 
        onCancel={() => {
          if (form.isFieldsTouched()) {
            Modal.confirm({
              title: '确认关闭',
              content: '表单数据尚未保存，关闭后可通过草稿恢复。确定关闭吗？',
              okText: '关闭',
              cancelText: '继续编辑',
              onOk: () => {
                saveDraft()
                setModalVisible(false)
                form.resetFields()
                setEditingSupplier(null)
              },
            })
          } else {
            setModalVisible(false)
            form.resetFields()
            setEditingSupplier(null)
          }
        }} 
        onOk={() => form.submit()} 
        width={800}
        maskClosable={false}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit} onValuesChange={handleFormChange}>
          <Form.Item name="name" label="名称" rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder="供应商名称" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="supply_category" label="供应类别">
                <Input placeholder="手填：如电力设备、建筑材料" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="country" label="国家" initialValue="Laos">
                <Select>
                  <Select.Option value="China">中国</Select.Option>
                  <Select.Option value="Laos">老挝</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={2} placeholder="备注信息" />
          </Form.Item>
          
          <h4>联系人</h4>
          <Form.List name="contacts" initialValue={[{ name: '', position: '', phone: '', is_primary: true }]}>
            {(fields, { add, remove }) => (
              <div>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} style={{ display: 'flex', gap: 8, marginBottom: 8, alignItems: 'center' }}>
                    <Form.Item {...restField} name={[name, 'name']} style={{ marginBottom: 0, flex: 1 }}>
                      <Input placeholder="姓名" />
                    </Form.Item>
                    <Form.Item {...restField} name={[name, 'position']} style={{ marginBottom: 0, flex: 1 }}>
                      <Input placeholder="职位" />
                    </Form.Item>
                    <Form.Item {...restField} name={[name, 'phone']} style={{ marginBottom: 0, flex: 1 }}>
                      <Input placeholder="电话" />
                    </Form.Item>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Form.Item {...restField} name={[name, 'is_primary']} valuePropName="checked" style={{ marginBottom: 0, marginRight: 8 }}>
                        <input 
                          type="checkbox" 
                          onChange={(e) => handleContactChange(name, 'is_primary', e.target.checked)}
                        />
                      </Form.Item>
                      <span>主联系人</span>
                    </div>
                    {fields.length > 1 && <Button type="link" danger onClick={() => remove(name)}>删除</Button>}
                  </div>
                ))}
                <Button type="dashed" onClick={() => add()} style={{ width: '100%' }}>+ 添加联系人</Button>
              </div>
            )}
          </Form.List>

          <h4 style={{ marginTop: 24 }}>收款信息</h4>
          <Form.List name="payment_infos" initialValue={[]}>
            {(fields, { add, remove }) => (
              <div>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} style={{ border: '1px solid #e8e8e8', padding: 16, marginBottom: 16, borderRadius: 4, backgroundColor: '#fafafa' }}>
                    <div style={{ display: 'flex', gap: 8, marginBottom: 8, alignItems: 'center' }}>
                      <Form.Item {...restField} name={[name, 'account_name']} label="收款户名" style={{ marginBottom: 0, flex: 1 }}>
                        <Input placeholder="收款户名" />
                      </Form.Item>
                      <Form.Item {...restField} name={[name, 'bank_name']} label="开户银行" style={{ marginBottom: 0, flex: 1 }}>
                        <Input placeholder="开户银行" />
                      </Form.Item>
                    </div>
                    <div style={{ display: 'flex', gap: 8, marginBottom: 8, alignItems: 'center' }}>
                      <Form.Item {...restField} name={[name, 'bank_account']} label="银行账号" style={{ marginBottom: 0, flex: 1 }}>
                        <Input placeholder="银行账号" />
                      </Form.Item>
                      <div style={{ display: 'flex', alignItems: 'center', marginTop: 30 }}>
                        <Form.Item {...restField} name={[name, 'is_primary']} valuePropName="checked" style={{ marginBottom: 0, marginRight: 8 }}>
                          <input 
                            type="checkbox" 
                            onChange={(e) => handlePaymentInfoChange(name, 'is_primary', e.target.checked)}
                          />
                        </Form.Item>
                        <span>主要收款账户</span>
                      </div>
                    </div>
                    <Form.Item {...restField} name={[name, 'qr_code']} label="收款码" style={{ marginBottom: 0 }}>
                      <FileUpload 
                        maxCount={1} 
                        accept="image/*"
                        value={form.getFieldValue([name, 'qr_code']) ? [form.getFieldValue([name, 'qr_code'])] : []}
                        onChange={(urls) => {
                          form.setFieldsValue({
                            payment_infos: form.getFieldValue('payment_infos').map((info: any, i: number) => {
                              return i === Number(name) ? { ...info, qr_code: urls[0] || '' } : info
                            })
                          })
                        }}
                      />
                    </Form.Item>
                    {fields.length > 0 && (
                      <Button type="link" danger onClick={() => remove(name)} style={{ marginTop: 8 }}>删除此收款信息</Button>
                    )}
                  </div>
                ))}
                <Button type="dashed" onClick={() => add({ account_name: '', bank_account: '', bank_name: '', is_primary: false })} style={{ width: '100%' }}>
                  + 添加收款信息
                </Button>
              </div>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  )
}

export default SupplierPage
