import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, Package, AlertCircle, Building2, Tag } from 'lucide-react';
import { http, commonApi } from '../../api';
import { purchaserApi } from '../../api';
import type { ProductWithInventory, ProductInRecord, Company } from '../../types';

interface OutboundFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: () => void;
  products: ProductWithInventory[];
  formData: {
    product_id: string;
    batch_no: string;
    rolls: number;
    meters: number;
    notes: string;
    source_batch_id?: string;
    recipient_company_id?: string;
    recipient_company_name?: string;
  };
  setFormData: (data: any) => void;
}

export function OutboundForm({
  isOpen,
  onClose,
  onSubmit,
  products,
  formData,
  setFormData
}: OutboundFormProps) {
  const [inboundBatches, setInboundBatches] = useState<ProductInRecord[]>([]);
  const [companies, setCompanies] = useState<Company[]>([]);
  const [loadingBatches, setLoadingBatches] = useState(false);

  useEffect(() => {
    if (isOpen && formData.product_id) {
      fetchInboundBatches();
    }
  }, [isOpen, formData.product_id]);

  useEffect(() => {
    if (isOpen) {
      fetchCompanies();
    }
  }, [isOpen]);

  const fetchInboundBatches = async () => {
    if (!formData.product_id) return;
    setLoadingBatches(true);
    try {
      const data = await purchaserApi.getRecords(formData.product_id);
      setInboundBatches(data || []);
    } catch {
      setInboundBatches([]);
    }
    setLoadingBatches(false);
  };

  const fetchCompanies = async () => {
    try {
      const data = await purchaserApi.listFactories();
      setCompanies(data || []);
    } catch {
      setCompanies([]);
    }
  };

  if (!isOpen) return null;

  const selectedProduct = products.find(p => p.id === formData.product_id);
  const maxMeters = selectedProduct?.total_stock || 0;
  const maxRolls = selectedProduct?.raw_fabric_rolls || 0;

  const selectedBatch = inboundBatches.find(b => b.id === formData.source_batch_id);

  const canSubmit = formData.product_id && 
    formData.batch_no && 
    formData.rolls > 0 && 
    formData.meters > 0 &&
    formData.rolls <= maxRolls &&
    formData.meters <= maxMeters &&
    formData.source_batch_id &&
    formData.recipient_company_id;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        className="bg-white rounded-2xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-hidden"
        onClick={e => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-amber-50 to-orange-50">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-gradient-to-br from-amber-500 to-orange-500 rounded-xl flex items-center justify-center">
              <Package className="w-5 h-5 text-white" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900">产品出库</h3>
              <p className="text-xs text-gray-500">手动出库操作</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 表单内容 */}
        <div className="p-4 space-y-4 overflow-y-auto max-h-[60vh]">
          {/* 产品选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              选择产品 <span className="text-red-500">*</span>
            </label>
            <select
              value={formData.product_id}
              onChange={e => {
                const newProductId = e.target.value;
                setFormData({ 
                  ...formData, 
                  product_id: newProductId,
                  source_batch_id: '',
                  batch_no: ''
                });
              }}
              className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all bg-white"
            >
              <option value="">请选择产品</option>
              {products.map(product => (
                <option key={product.id} value={product.id}>
                  {product.product_name}-{product.weight}g-{product.color} (库存: {product.total_stock}米/{product.raw_fabric_rolls}匹/件)
                </option>
              ))}
            </select>
            {products.length === 0 && (
              <p className="text-xs text-amber-600 mt-2 flex items-center gap-1">
                <AlertCircle className="w-3 h-3" />
                没有可出库的产品
              </p>
            )}
          </div>

          {/* 库存提示 */}
          {selectedProduct && (
            <div className="bg-blue-50 rounded-lg p-3 text-sm">
              <p className="text-gray-600">产品码: <span className="font-medium text-gray-900">{selectedProduct.fabric_code}</span></p>
              <p className="text-gray-600">当前库存: <span className="font-medium text-blue-600">{selectedProduct.total_stock}米 / {selectedProduct.raw_fabric_rolls}匹/件</span></p>
            </div>
          )}

          {/* 生产批号选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <span className="flex items-center gap-1">
                <Tag className="w-3.5 h-3.5" />
                选择生产批号 <span className="text-red-500">*</span>
              </span>
            </label>
            <select
              value={formData.source_batch_id || ''}
              onChange={e => {
                const batchId = e.target.value;
                const batch = inboundBatches.find(b => b.id === batchId);
                setFormData({ 
                  ...formData, 
                  source_batch_id: batchId,
                  batch_no: batch?.batch_no || ''
                });
              }}
              disabled={!formData.product_id || loadingBatches}
              className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all bg-white disabled:bg-gray-100 disabled:text-gray-400"
            >
              <option value="">请选择生产批号</option>
              {inboundBatches.map(batch => (
                <option key={batch.id} value={batch.id}>
                  {batch.batch_no} - {batch.rolls}匹/件/{batch.meters}米
                  {batch.source === 'textile' ? ' (纺织厂)' : ' (自录入)'}
                </option>
              ))}
            </select>
            {loadingBatches && (
              <p className="text-xs text-gray-400 mt-1">加载批次中...</p>
            )}
            {!loadingBatches && formData.product_id && inboundBatches.length === 0 && (
              <p className="text-xs text-amber-600 mt-1 flex items-center gap-1">
                <AlertCircle className="w-3 h-3" />
                该产品没有入库批次，请先入库
              </p>
            )}
          </div>

          {/* 接手公司选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <span className="flex items-center gap-1">
                <Building2 className="w-3.5 h-3.5" />
                接手公司 <span className="text-red-500">*</span>
              </span>
            </label>
            <select
              value={formData.recipient_company_id || ''}
              onChange={e => {
                const companyId = e.target.value;
                const company = companies.find(c => c.id === companyId);
                setFormData({ 
                  ...formData, 
                  recipient_company_id: companyId,
                  recipient_company_name: company?.name || ''
                });
              }}
              className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all bg-white"
            >
              <option value="">请选择接手公司</option>
              {companies.map(company => (
                <option key={company.id} value={company.id}>
                  {company.name}
                </option>
              ))}
            </select>
          </div>

          {/* 批号（自动填充，可修改） */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              出库批号 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={formData.batch_no}
              onChange={e => setFormData({ ...formData, batch_no: e.target.value })}
              placeholder="请输入出库批号"
              className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all"
            />
            {selectedBatch && (
              <p className="text-xs text-gray-400 mt-1">
                来源批号: {selectedBatch.batch_no}
              </p>
            )}
          </div>

          {/* 匹/件数和米数 */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                出库匹/件数 <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                value={formData.rolls || ''}
                onChange={e => setFormData({ ...formData, rolls: parseInt(e.target.value) || 0 })}
                placeholder={`最大: ${maxRolls}`}
                min="1"
                max={maxRolls}
                className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all"
              />
              {formData.rolls > maxRolls && (
                <p className="text-xs text-red-500 mt-1">超出库存限制</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                出库米数 <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                value={formData.meters || ''}
                onChange={e => setFormData({ ...formData, meters: parseFloat(e.target.value) || 0 })}
                placeholder={`最大: ${maxMeters}`}
                min="0.01"
                step="0.01"
                max={maxMeters}
                className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all"
              />
              {formData.meters > maxMeters && (
                <p className="text-xs text-red-500 mt-1">超出库存限制</p>
              )}
            </div>
          </div>

          {/* 备注 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">备注</label>
            <textarea
              value={formData.notes}
              onChange={e => setFormData({ ...formData, notes: e.target.value })}
              placeholder="请输入备注信息..."
              rows={3}
              className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all resize-none"
            />
          </div>
        </div>

        {/* 底部按钮 */}
        <div className="p-4 border-t border-gray-200 bg-gray-50 flex gap-3">
          <button
            onClick={onClose}
            className="flex-1 px-4 py-2.5 border border-gray-300 text-gray-700 rounded-xl text-sm font-medium hover:bg-gray-100 transition-colors"
          >
            取消
          </button>
          <button
            onClick={onSubmit}
            disabled={!canSubmit}
            className="flex-1 px-4 py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-xl text-sm font-medium hover:from-amber-600 hover:to-orange-600 transition-all shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
          >
            确认出库
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
}
