import React, { useState, useEffect } from 'react'
import {
  Table, Button, Modal, Form, Input, Select, message, Space, Tag, Card,
  Row, Col, Statistic, DatePicker, InputNumber, Tabs
} from 'antd'
import {
  PlusOutlined, SearchOutlined, InboxOutlined, ExportOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'

// ==================== 类型定义 ====================
interface InventoryRecord {
  id: number
  record_type: string
  project_id?: number | null
  project_name?: string
  purchase_request_id?: number | null
  product_id: number
  product_name?: string
  quantity: number
  unit_price?: number | null
  total_amount?: number | null
  record_date: string
  operator?: string | null
  remark?: string | null
  created_at: string
}

interface InventorySummary {
  product_id: number
  product_name: string
  unit?: string | null
  total_in: number
  total_out: number
  current_quantity: number
}

interface Product {
  id: number
  name: string
}

interface Project {
  id: number
  name: string
}

// ==================== 组件 ====================
const InventoryPage: React.FC = () => {
  // 状态
  const [records, setRecords] = useState<InventoryRecord[]>([])
  const [summary, setSummary] = useState<InventorySummary[]>([])
  const [loading, setLoading] = useState(false)
  const [products, setProducts] = useState<Product[]>([])
  const [projects, setProjects] = useState<Project[]>([])
  
  // 筛选状态
  const [selectedProductId, setSelectedProductId] = useState<number | null>(null)
  const [selectedProjectId, setSelectedProjectId] = useState<number | null>(null)
  const [selectedRecordType, setSelectedRecordType] = useState<string | null>(null)
  
  // 弹窗状态
  const [outModalVisible, setOutModalVisible] = useState(false)
  const [form] = Form.useForm()
  
  // Tab状态
  const [activeTab, setActiveTab] = useState('records')
  
  // ==================== 渲染 ====================
  
  const getRecordTypeTag = (type: string) => {
    if (type === 'in') {
      return <Tag color="green" icon={<InboxOutlined />}>入库</Tag>
    } else {
      return <Tag color="orange" icon={<ExportOutlined />}>出库</Tag>
    }
  }
  
  const recordColumns: ColumnsType<InventoryRecord> = [
    {
      title: '记录类型',
      dataIndex: 'record_type',
      key: 'record_type',
      width: 100,
      render: getRecordTypeTag
    },
    {
      title: '商品',
      dataIndex: 'product_name',
      key: 'product_name'
    },
    {
      title: '项目',
      dataIndex: 'project_name',
      key: 'project_name'
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 100
    },
    {
      title: '单价',
      dataIndex: 'unit_price',
      key: 'unit_price',
      width: 120,
      render: (price) => price ? price.toFixed(2) : '-'
    },
    {
      title: '总金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 120,
      render: (amount) => amount ? amount.toFixed(2) : '-'
    },
    {
      title: '记录日期',
      dataIndex: 'record_date',
      key: 'record_date',
      width: 120
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
      width: 120
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark'
    }
  ]
  
  const summaryColumns: ColumnsType<InventorySummary> = [
    {
      title: '商品',
      dataIndex: 'product_name',
      key: 'product_name'
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      width: 80
    },
    {
      title: '入库总量',
      dataIndex: 'total_in',
      key: 'total_in',
      width: 120,
      render: (val) => (val || 0).toFixed(2)
    },
    {
      title: '出库总量',
      dataIndex: 'total_out',
      key: 'total_out',
      width: 120,
      render: (val) => (val || 0).toFixed(2)
    },
    {
      title: '当前库存',
      dataIndex: 'current_quantity',
      key: 'current_quantity',
      width: 120,
      render: (val) => (
        <span style={{ fontWeight: 'bold', color: (val || 0) < 0 ? '#ff4d4f' : '#52c41a' }}>
          {(val || 0).toFixed(2)}
        </span>
      )
    }
  ]
  
  const tabItems = [
    {
      key: 'records',
      label: '库存记录',
      children: (
        <>
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={6}>
              <Select
                placeholder="选择商品筛选"
                allowClear
                style={{ width: '100%' }}
                onChange={(value) => setSelectedProductId(value)}
              >
                {products.map(product => (
                  <Select.Option key={product.id} value={product.id}>
                    {product.name}
                  </Select.Option>
                ))}
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="选择项目筛选"
                allowClear
                style={{ width: '100%' }}
                onChange={(value) => setSelectedProjectId(value)}
              >
                {projects.map(project => (
                  <Select.Option key={project.id} value={project.id}>
                    {project.name}
                  </Select.Option>
                ))}
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="选择记录类型"
                allowClear
                style={{ width: '100%' }}
                onChange={(value) => setSelectedRecordType(value)}
              >
                <Select.Option value="in">入库</Select.Option>
                <Select.Option value="out">出库</Select.Option>
              </Select>
            </Col>
            <Col span={6} style={{ textAlign: 'right' }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => setOutModalVisible(true)}>
                出库
              </Button>
            </Col>
          </Row>
          
          <Table
            columns={recordColumns}
            dataSource={records}
            rowKey="id"
            loading={loading}
          />
        </>
      )
    },
    {
      key: 'summary',
      label: '库存汇总',
      children: (
        <Table
          columns={summaryColumns}
          dataSource={summary}
          rowKey="product_id"
          loading={loading}
        />
      )
    }
  ]
  
  // ==================== 数据加载 ====================
  
  const fetchRecords = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (selectedProductId) params.append('product_id', selectedProductId.toString())
      if (selectedProjectId) params.append('project_id', selectedProjectId.toString())
      if (selectedRecordType) params.append('record_type', selectedRecordType)
      
      const response = await fetch(`/api/inventory?${params}`)
      const data = await response.json()
      
      if (data.success) {
        setRecords(data.data)
      } else {
        message.error('获取库存记录失败')
      }
    } catch (error) {
      console.error('获取库存记录失败:', error)
      message.error('获取库存记录失败')
    } finally {
      setLoading(false)
    }
  }
  
  const fetchSummary = async () => {
    try {
      const response = await fetch('/api/inventory/summary')
      const data = await response.json()
      
      if (data.success) {
        setSummary(data.data)
      }
    } catch (error) {
      console.error('获取库存汇总失败:', error)
    }
  }
  
  const fetchProducts = async () => {
    try {
      const response = await fetch('/api/products')
      const data = await response.json()
      if (data.success) {
        setProducts(data.data)
      }
    } catch (error) {
      console.error('获取商品列表失败:', error)
    }
  }
  
  const fetchProjects = async () => {
    try {
      const response = await fetch('/api/projects')
      const data = await response.json()
      if (data.success) {
        setProjects(data.data)
      }
    } catch (error) {
      console.error('获取项目列表失败:', error)
    }
  }
  
  useEffect(() => {
    fetchProducts()
    fetchProjects()
  }, [])
  
  useEffect(() => {
    if (activeTab === 'records') {
      fetchRecords()
    } else {
      fetchSummary()
    }
  }, [activeTab, selectedProductId, selectedProjectId, selectedRecordType])
  
  // ==================== 操作函数 ====================
  
  const handleOutModalOk = async () => {
    try {
      const values = await form.validateFields()
      
      const response = await fetch('/api/inventory/out', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...values,
          operator: '系统管理员'
        })
      })
      
      const data = await response.json()
      
      if (data.success) {
        message.success('出库成功')
        setOutModalVisible(false)
        form.resetFields()
        fetchRecords()
        fetchSummary()
      } else {
        message.error('出库失败')
      }
    } catch (error) {
      console.error('出库失败:', error)
      message.error('出库失败')
    }
  }
  
  return (
    <div style={{ padding: 24 }}>
      <Card>
          <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
        </Card>
      
      {/* 出库弹窗 */}
      <Modal
        title="商品出库"
        open={outModalVisible}
        onOk={handleOutModalOk}
        onCancel={() => setOutModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="project_id"
            label="关联项目"
            rules={[{ required: true, message: '请选择项目' }]}
          >
            <Select placeholder="请选择项目">
              {projects.map(project => (
                <Select.Option key={project.id} value={project.id}>
                  {project.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="product_id"
            label="商品"
            rules={[{ required: true, message: '请选择商品' }]}
          >
            <Select placeholder="请选择商品">
              {products.map(product => (
                <Select.Option key={product.id} value={product.id}>
                  {product.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="quantity"
            label="出库数量"
            rules={[{ required: true, message: '请输入出库数量' }]}
          >
            <InputNumber style={{ width: '100%' }} min={0} placeholder="请输入出库数量" />
          </Form.Item>
          
          <Form.Item name="unit_price" label="单价">
            <InputNumber style={{ width: '100%' }} min={0} placeholder="请输入单价" />
          </Form.Item>
          
          <Form.Item name="total_amount" label="总金额">
            <InputNumber style={{ width: '100%' }} min={0} placeholder="请输入总金额" />
          </Form.Item>
          
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} placeholder="请输入备注" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default InventoryPage
