import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { purchaserApi, http } from '../../api';
import { motion } from 'framer-motion';
import { ArrowLeft, Plus, Droplets, Calculator, AlertCircle } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import type { ProductWithInventory, Company } from '../../types';

interface WashingPlanForm {
  productId: string;
  washingFactoryId: string;
  plannedMeters: string;
  washingPrice: string;
  estimatedShrinkageRate: string;
  notes: string;
}

const initialForm: WashingPlanForm = {
  productId: '',
  washingFactoryId: '',
  plannedMeters: '',
  washingPrice: '',
  estimatedShrinkageRate: '',
  notes: ''
};

export function NewWashingPlan() {
  const navigate = useNavigate();
  const { auth } = useAuth();
  const { isMobile } = useResponsive();
  const [form, setForm] = useState<WashingPlanForm>(initialForm);
  const [products, setProducts] = useState<ProductWithInventory[]>([]);
  const [washingFactories, setWashingFactories] = useState<Company[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  // 获取产品信息（包含库存计算）
  const fetchProducts = useCallback(async () => {
    if (!auth.company) return;

    const res = await purchaserApi.listProducts();
    const productsData = res.data || [];

    const productsWithInventory: ProductWithInventory[] = productsData.map(product => ({
      ...product,
      raw_fabric_meters: product.raw_fabric_meters || 0,
      raw_fabric_rolls: product.raw_fabric_rolls || 0,
      total_stock: product.total_stock || 0,
      total_in_meters: 0,
      total_in_rolls: 0,
      total_out_meters: 0,
      total_out_rolls: 0
    }));

    setProducts(productsWithInventory);
  }, [auth.company]);

  // 获取水洗厂列表
  const fetchWashingFactories = useCallback(async () => {
    try {
      const res = await http.get<Company[]>('/purchaser/factories', { role: 'washing' });
      setWashingFactories(res.data || []);
    } catch {
      setWashingFactories([]);
    }
  }, []);

  useEffect(() => {
    fetchProducts();
    fetchWashingFactories();
  }, [fetchProducts, fetchWashingFactories]);

  // 计算预计洗后米数
  const estimatedWashedMeters = useMemo(() => {
    const planned = parseFloat(form.plannedMeters) || 0;
    const shrinkage = parseFloat(form.estimatedShrinkageRate) || 0;
    return planned * (1 - shrinkage / 100);
  }, [form.plannedMeters, form.estimatedShrinkageRate]);

  // 计算预计总费用
  const estimatedTotalCost = useMemo(() => {
    const planned = parseFloat(form.plannedMeters) || 0;
    const price = parseFloat(form.washingPrice) || 0;
    return planned * price;
  }, [form.plannedMeters, form.washingPrice]);

  // 生成计划编号
  const generatePlanCode = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const random = Math.random().toString(36).substring(2, 6).toUpperCase();
    return `WS${year}${month}${day}-${random}`;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!form.productId) {
      setError('请选择待水洗产品');
      return;
    }
    if (!form.washingFactoryId) {
      setError('请选择水洗厂');
      return;
    }
    if (!form.plannedMeters || parseFloat(form.plannedMeters) <= 0) {
      setError('请输入计划水洗米数');
      return;
    }
    if (!form.washingPrice || parseFloat(form.washingPrice) <= 0) {
      setError('请输入水洗单价');
      return;
    }

    // 检查库存是否充足
    const selectedProduct = products.find(p => p.id === form.productId);
    if (!selectedProduct) {
      setError('产品不存在');
      return;
    }
    const plannedMeters = parseFloat(form.plannedMeters);
    if ((selectedProduct.total_stock || 0) < plannedMeters) {
      setError(`库存不足，当前库存: ${selectedProduct.total_stock}米，计划水洗: ${plannedMeters}米`);
      return;
    }

    setSubmitting(true);

    try {
      await purchaserApi.createWashingPlan({
        product_id: form.productId,
        washing_factory_id: form.washingFactoryId,
        planned_meters: parseFloat(form.plannedMeters),
        washing_price: parseFloat(form.washingPrice),
        estimated_shrinkage_rate: parseFloat(form.estimatedShrinkageRate) || 0,
        notes: form.notes || undefined
      } as any);

      setSubmitting(false);
      navigate('/purchaser');
    } catch (err: any) {
      setSubmitting(false);
      setError('创建失败: ' + (err.message || '未知错误'));
    }
  };

  const selectedProduct = products.find(p => p.id === form.productId);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-3 sm:px-4 py-3 sm:py-4 flex items-center gap-3 sm:gap-4">
          <button
            onClick={() => navigate('/purchaser')}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-gray-600" />
          </button>
          <div className="flex items-center gap-2">
            <Droplets className="w-5 h-5 text-blue-600" />
            <h1 className="text-base sm:text-lg font-bold text-gray-900">新建水洗计划</h1>
          </div>
        </div>
      </header>

      <div className="max-w-4xl mx-auto py-4 sm:py-6 px-3 sm:px-4">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-100 overflow-hidden"
        >
          <form onSubmit={handleSubmit} className="p-4 sm:p-6 space-y-6">
            {/* 产品信息 */}
            <div>
              <h2 className="text-sm sm:text-base font-semibold text-gray-900 mb-3 flex items-center gap-2">
                <span className="w-6 h-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs">1</span>
                产品信息
              </h2>
              <div className="bg-gray-50 rounded-xl p-4 space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    选择待水洗产品 <span className="text-red-500">*</span>
                  </label>
                  <select
                    value={form.productId}
                    onChange={e => setForm({ ...form, productId: e.target.value })}
                    className="w-full px-3 sm:px-4 py-2.5 sm:py-3 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all bg-white"
                    required
                  >
                    <option value="">请选择产品</option>
                    {products.map(product => (
                      <option key={product.id} value={product.id}>
                        {product.product_name}-{product.weight}g-{product.color} (库存: {product.raw_fabric_meters}米)
                      </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-gray-900">{selectedProduct.color_code}</span></p>
                    <p className="text-gray-600">当前库存: <span className="font-medium text-blue-600">{selectedProduct.raw_fabric_meters}米</span></p>
                  </div>
                )}

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

            {/* 生产信息 */}
            <div>
              <h2 className="text-sm sm:text-base font-semibold text-gray-900 mb-3 flex items-center gap-2">
                <span className="w-6 h-6 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center text-xs">2</span>
                生产信息
              </h2>
              <div className="bg-gray-50 rounded-xl p-4 space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    请选择水洗厂 <span className="text-red-500">*</span>
                  </label>
                  <select
                    value={form.washingFactoryId}
                    onChange={e => setForm({ ...form, washingFactoryId: e.target.value })}
                    className="w-full px-3 sm:px-4 py-2.5 sm:py-3 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all bg-white"
                    required
                  >
                    <option value="">请选择水洗厂</option>
                    {washingFactories.map(factory => (
                      <option key={factory.id} value={factory.id}>
                        {factory.name}
                      </option>
                    ))}
                  </select>
                  {washingFactories.length === 0 && (
                    <p className="text-xs text-amber-600 mt-2 flex items-center gap-1">
                      <AlertCircle className="w-3 h-3" />
                      系统中暂无水洗厂，请先添加水洗厂
                    </p>
                  )}
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 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={form.plannedMeters}
                      onChange={e => setForm({ ...form, plannedMeters: e.target.value })}
                      placeholder="请输入米数"
                      min="0"
                      step="0.01"
                      className="w-full px-3 sm:px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                      required
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      水洗单价（元/m） <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="number"
                      value={form.washingPrice}
                      onChange={e => setForm({ ...form, washingPrice: e.target.value })}
                      placeholder="请输入单价"
                      min="0"
                      step="0.01"
                      className="w-full px-3 sm:px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                      required
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      预计缩水率（%）
                    </label>
                    <input
                      type="number"
                      value={form.estimatedShrinkageRate}
                      onChange={e => setForm({ ...form, estimatedShrinkageRate: e.target.value })}
                      placeholder="如: 5"
                      min="0"
                      max="100"
                      step="0.1"
                      className="w-full px-3 sm:px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* 自动计算 */}
            {(form.plannedMeters || form.washingPrice) && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                className="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-4 border border-amber-100"
              >
                <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                  <Calculator className="w-4 h-4 text-amber-600" />
                  预计计算结果
                </h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-500 mb-1">预计洗后米数</p>
                    <p className="text-lg font-bold text-amber-600">
                      {estimatedWashedMeters.toFixed(2)} <span className="text-sm font-normal text-gray-500">米</span>
                    </p>
                    <p className="text-xs text-gray-400 mt-1">
                      {form.plannedMeters || 0} × (1 - {form.estimatedShrinkageRate || 0}%)
                    </p>
                  </div>
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-500 mb-1">预计总费用</p>
                    <p className="text-lg font-bold text-emerald-600">
                      ¥{estimatedTotalCost.toFixed(2)}
                    </p>
                    <p className="text-xs text-gray-400 mt-1">
                      {form.plannedMeters || 0} × ¥{form.washingPrice || 0}
                    </p>
                  </div>
                </div>
                <p className="text-xs text-gray-500 mt-3 flex items-center gap-1">
                  <AlertCircle className="w-3 h-3" />
                  注：本次计算仅供参考，具体费用请以实际情况为准。
                </p>
              </motion.div>
            )}

            {/* 错误提示 */}
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-red-50 border border-red-200 rounded-xl p-3 flex items-center gap-2 text-red-600 text-sm"
              >
                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                {error}
              </motion.div>
            )}

            {/* 按钮 */}
            <div className="flex flex-col sm:flex-row gap-3 pt-4 border-t border-gray-100">
              <button
                type="button"
                onClick={() => navigate('/purchaser')}
                className="px-4 py-2.5 border border-gray-200 text-gray-700 rounded-xl text-sm font-medium hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                disabled={submitting || products.length === 0 || washingFactories.length === 0}
                className="flex-1 px-4 py-2.5 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl text-sm font-medium hover:from-blue-600 hover:to-indigo-600 transition-all shadow-md hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {submitting ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                    创建中...
                  </>
                ) : (
                  <>
                    <Plus className="w-4 h-4" />
                    创建计划
                  </>
                )}
              </button>
            </div>
          </form>
        </motion.div>

        {/* 说明 */}
        <div className="mt-4 bg-blue-50 rounded-xl p-4 text-sm text-gray-600">
          <p className="font-medium text-gray-900 mb-2">说明：</p>
          <ul className="space-y-1 list-disc list-inside">
            <li>水洗结束后的产品将自动统计进成品仓库中</li>
            <li>系统会保留水洗前的所有产品信息</li>
            <li>水洗完成后可录入实际缩水率、实际洗后米数等数据</li>
          </ul>
        </div>
      </div>
    </div>
  );
}
