import React, { useState, useEffect } from 'react';
import { ArrowLeft, Plus, AlertTriangle, ArrowDownLeft, ArrowUpRight } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { textileApi, http } from '../../api';
import { motion, AnimatePresence } from 'framer-motion';
import type { YarnStock, Warehouse } from '../../types';

interface YarnStockRecord {
  id: string;
  yarn_stock_id: string | null;
  plan_id: string | null;
  record_type: 'inbound' | 'outbound';
  quantity: number;
  unit: string;
  batch_no: string | null;
  notes: string | null;
  created_at: string;
  yarn_name?: string;
}

export function YarnWarehouse() {
  const navigate = useNavigate();
  const { auth } = useAuth();
  const [activeTab, setActiveTab] = useState<'stock' | 'record'>('stock');
  const [yarns, setYarns] = useState<YarnStock[]>([]);
  const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
  const [records, setRecords] = useState<YarnStockRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddModal, setShowAddModal] = useState(false);
  const [newYarn, setNewYarn] = useState({ name: '', spec: '', quantity: 0, minStock: 0, unit: 'kg' });

  useEffect(() => {
    if (!auth.company) return;
    fetchData();
  }, [auth.company]);

  useEffect(() => {
    if (activeTab === 'record' && auth.company) {
      fetchRecords();
    }
  }, [activeTab, auth.company]);

  const fetchData = async () => {
    const response = await textileApi.listYarnStock();
    setYarns(response.data || []);

    const { data: whData } = await http.get<Warehouse[]>('/textile/warehouses', { type: 'yarn' });
    setWarehouses(whData || []);
    setLoading(false);
  };

  const fetchRecords = async () => {
    setLoading(true);
    const { data: recordsData } = await http.get<any[]>('/textile/yarn-stock/records');

    const yarnMap = new Map(yarns.map(y => [y.id, y.name]));

    const recordsWithNames: YarnStockRecord[] = (recordsData || []).map(r => ({
      ...r,
      yarn_name: r.yarn_stock_id ? yarnMap.get(r.yarn_stock_id) || r.yarn_name || '未知纱线' : '未知纱线',
      record_type: r.record_type as 'inbound' | 'outbound'
    }));

    setRecords(recordsWithNames);
    setLoading(false);
  };

  const handleAddYarn = async () => {
    if (!newYarn.name) return;
    const yarnWarehouse = warehouses[0];

    try {
      const newYarnData = await textileApi.createYarnStock({
        company_id: auth.company!.id,
        warehouse_id: yarnWarehouse?.id || null,
        name: newYarn.name,
        spec: newYarn.spec || null,
        quantity: newYarn.quantity,
        min_stock: newYarn.minStock,
        unit: newYarn.unit
      } as any);

      await textileApi.addYarnRecord(newYarnData.id, {
        change_type: 'inbound',
        quantity: newYarn.quantity,
        notes: `纱线入库 - ${newYarn.name}`
      });

      setShowAddModal(false);
      setNewYarn({ name: '', spec: '', quantity: 0, minStock: 0, unit: 'kg' });
      await fetchData();
    } catch {
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-white shadow-sm sticky top-0 z-10">
        <div className="max-w-4xl mx-auto px-3 sm:px-4 py-3 sm:py-4 flex items-center gap-3 sm:gap-4">
          <motion.button
            whileTap={{ scale: 0.95 }}
            onClick={() => navigate('/textile')}
            className="p-2 hover:bg-gray-100 rounded-full will-change-transform"
          >
            <ArrowLeft className="w-5 h-5" />
          </motion.button>
          <h1 className="text-base sm:text-lg font-semibold">原料纱仓库</h1>
        </div>
      </div>

      <div className="max-w-4xl mx-auto px-3 sm:px-4 py-4 sm:py-6">
        <div className="flex gap-2 mb-3 sm:mb-4">
          <motion.button
            whileTap={{ scale: 0.98 }}
            onClick={() => setActiveTab('stock')}
            className={`flex-1 py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors will-change-transform ${
              activeTab === 'stock' ? 'bg-emerald-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'
            }`}
          >
            库存列表
          </motion.button>
          <motion.button
            whileTap={{ scale: 0.98 }}
            onClick={() => setActiveTab('record')}
            className={`flex-1 py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors will-change-transform ${
              activeTab === 'record' ? 'bg-emerald-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'
            }`}
          >
            出入库记录
          </motion.button>
        </div>

        {loading ? (
          <div className="flex flex-col items-center justify-center py-12 sm:py-16">
            <motion.div
              animate={{ rotate: 360 }}
              transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}
              className="w-6 h-6 sm:w-8 sm:h-8 border-2 border-emerald-500 border-t-transparent rounded-full mb-3"
            />
            <p className="text-gray-400 text-sm">加载中...</p>
          </div>
        ) : activeTab === 'stock' ? (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="bg-white rounded-lg shadow-sm"
          >
            <div className="p-3 sm:p-4 border-b flex justify-between items-center">
              <h2 className="font-medium text-sm sm:text-base">纱线库存</h2>
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={() => setShowAddModal(true)}
                className="flex items-center gap-1 text-xs sm:text-sm text-emerald-600 will-change-transform"
              >
                <Plus className="w-4 h-4" /> 入库
              </motion.button>
            </div>
            {yarns.length === 0 ? (
              <p className="text-center text-gray-400 py-6 sm:py-8 text-sm">暂无纱线库存</p>
            ) : (
              <div className="divide-y">
                {yarns.map((yarn, index) => (
                  <motion.div
                    key={yarn.id}
                    initial={{ opacity: 0, x: -10 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: Math.min(index * 0.02, 0.15), duration: 0.2 }}
                    className="p-3 sm:p-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
                  >
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-sm sm:text-base truncate">{yarn.name}</span>
                        {yarn.quantity < yarn.min_stock && (
                          <motion.span
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            className="flex items-center gap-1 text-[10px] sm:text-xs text-amber-600 bg-amber-50 px-1.5 sm:px-2 py-0.5 rounded flex-shrink-0"
                          >
                            <AlertTriangle className="w-3 h-3" /> 库存不足
                          </motion.span>
                        )}
                      </div>
                      <p className="text-xs sm:text-sm text-gray-500">{yarn.spec || '-'}</p>
                    </div>
                    <div className="text-right flex-shrink-0 ml-2">
                      <p className={`font-semibold text-sm sm:text-base ${yarn.quantity < yarn.min_stock ? 'text-amber-600' : 'text-gray-800'}`}>
                        {yarn.quantity} {yarn.unit}
                      </p>
                      <p className="text-[10px] sm:text-xs text-gray-400">最低: {yarn.min_stock}{yarn.unit}</p>
                    </div>
                  </motion.div>
                ))}
              </div>
            )}
          </motion.div>
        ) : (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="bg-white rounded-lg shadow-sm"
          >
            <div className="p-3 sm:p-4 border-b">
              <h2 className="font-medium text-sm sm:text-base">出入库记录</h2>
            </div>
            {records.length === 0 ? (
              <p className="text-center text-gray-400 py-6 sm:py-8 text-sm">暂无出入库记录</p>
            ) : (
              <div className="divide-y">
                {records.map((record, index) => (
                  <motion.div
                    key={record.id}
                    initial={{ opacity: 0, x: -10 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: Math.min(index * 0.02, 0.15), duration: 0.2 }}
                    className="p-3 sm:p-4 hover:bg-gray-50 transition-colors"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-sm sm:text-base">{record.yarn_name}</span>
                          <span className={`text-[10px] sm:text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${
                            record.record_type === 'inbound'
                              ? 'bg-emerald-100 text-emerald-600'
                              : 'bg-amber-100 text-amber-600'
                          }`}>
                            {record.record_type === 'inbound' ? (
                              <span className="flex items-center gap-1">
                                <ArrowDownLeft className="w-3 h-3" /> 入库
                              </span>
                            ) : (
                              <span className="flex items-center gap-1">
                                <ArrowUpRight className="w-3 h-3" /> 出库
                              </span>
                            )}
                          </span>
                        </div>
                        <p className="text-xs sm:text-sm text-gray-500 mt-1">
                          {record.notes || '-'}
                        </p>
                        {record.plan_id && (
                          <p className="text-[10px] sm:text-xs text-gray-400 mt-0.5">
                            关联计划: {record.plan_id.slice(0, 8)}...
                          </p>
                        )}
                      </div>
                      <div className="text-right flex-shrink-0 ml-2">
                        <p className={`font-semibold text-sm sm:text-base ${
                          record.record_type === 'inbound' ? 'text-emerald-600' : 'text-amber-600'
                        }`}>
                          {record.record_type === 'inbound' ? '+' : '-'}{record.quantity} {record.unit}
                        </p>
                        <p className="text-[10px] sm:text-xs text-gray-400">
                          {new Date(record.created_at).toLocaleDateString()}
                        </p>
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            )}
          </motion.div>
        )}
      </div>

      <AnimatePresence>
        {showAddModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0, y: 20 }}
              animate={{ scale: 1, opacity: 1, y: 0 }}
              exit={{ scale: 0.95, opacity: 0, y: 20 }}
              transition={{ duration: 0.2, ease: [0.25, 0.46, 0.45, 0.94] }}
              className="bg-white rounded-xl p-4 sm:p-6 w-full max-w-sm"
            >
              <h3 className="text-base sm:text-lg font-semibold mb-3 sm:mb-4">纱线入库</h3>
              <div className="space-y-3 sm:space-y-4">
                <div>
                  <label className="block text-xs sm:text-sm text-gray-600 mb-1">纱线名称</label>
                  <input
                    type="text"
                    value={newYarn.name}
                    onChange={e => setNewYarn(prev => ({ ...prev, name: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                    placeholder="输入纱线名称"
                  />
                </div>
                <div>
                  <label className="block text-xs sm:text-sm text-gray-600 mb-1">规格</label>
                  <input
                    type="text"
                    value={newYarn.spec}
                    onChange={e => setNewYarn(prev => ({ ...prev, spec: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                    placeholder="输入规格"
                  />
                </div>
                <div>
                  <label className="block text-xs sm:text-sm text-gray-600 mb-1">数量（kg）</label>
                  <input
                    type="number"
                    value={newYarn.quantity}
                    onChange={e => setNewYarn(prev => ({ ...prev, quantity: Number(e.target.value) }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                    placeholder="输入数量"
                  />
                </div>
                <div>
                  <label className="block text-xs sm:text-sm text-gray-600 mb-1">最低库存预警（kg）</label>
                  <input
                    type="number"
                    value={newYarn.minStock}
                    onChange={e => setNewYarn(prev => ({ ...prev, minStock: Number(e.target.value) }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                    placeholder="输入最低库存"
                  />
                </div>
              </div>
              <div className="flex gap-3 mt-4 sm:mt-6">
                <motion.button
                  whileTap={{ scale: 0.98 }}
                  onClick={() => setShowAddModal(false)}
                  className="flex-1 py-2 border rounded-lg text-sm will-change-transform"
                >
                  取消
                </motion.button>
                <motion.button
                  whileTap={{ scale: 0.98 }}
                  onClick={handleAddYarn}
                  className="flex-1 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 text-sm will-change-transform"
                >
                  确认入库
                </motion.button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}