import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { supabase } from '../../supabase/client';
import { motion } from 'framer-motion';
import { ArrowLeft, Package, Clock, ChevronRight } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import type { WashingPlan } from '../../types';

interface PendingFabricItem {
  id: string;
  plan_code: string;
  purchaser_name: string;
  product_name: string;
  product_color: string;
  fabric_code: string;
  planned_meters: number;
  status: string;
  created_at: string;
}

const statusMap: Record<string, { label: string; color: string; bgColor: string }> = {
  pending: { label: '待确认', color: 'text-amber-600', bgColor: 'bg-amber-50' },
  processing: { label: '处理中', color: 'text-purple-600', bgColor: 'bg-purple-50' }
};

export function PendingFabric() {
  const navigate = useNavigate();
  const { auth } = useAuth();
  const { isMobile } = useResponsive();
  const [items, setItems] = useState<PendingFabricItem[]>([]);
  const [loading, setLoading] = useState(true);

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

  const fetchPendingFabric = async () => {
    setLoading(true);
    
    const { data, error } = await supabase
      .from('washing_plans')
      .select(`
        *,
        product:product_id(product_name, color, fabric_code),
        company:company_id(name)
      `)
      .eq('washing_factory_id', auth.company!.id)
      .in('status', ['pending', 'processing'])
      .order('created_at', { ascending: false });

    if (error) {
      console.error('获取待处理坯布失败:', error);
    } else {
      const formattedItems = (data || []).map(plan => ({
        id: plan.id,
        plan_code: plan.plan_code,
        purchaser_name: (plan.company as any)?.name || '未知采购商',
        product_name: (plan.product as any)?.product_name || '-',
        product_color: (plan.product as any)?.color || '-',
        fabric_code: (plan.product as any)?.fabric_code || '-',
        planned_meters: plan.planned_meters,
        status: plan.status,
        created_at: plan.created_at
      }));
      setItems(formattedItems);
    }
    setLoading(false);
  };

  const totalMeters = items.reduce((sum, item) => sum + item.planned_meters, 0);

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-purple-50/30 to-violet-50/30">
      {/* Header - 与 Dashboard 一致 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-gray-200/50 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 md:px-8 py-4 flex items-center gap-3">
          <button
            onClick={() => navigate('/washing')}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-gray-600" />
          </button>
          <div>
            <h1 className="text-lg font-bold text-gray-900">待处理坯布</h1>
            <p className="text-xs text-gray-500">查看待处理的水洗坯布</p>
          </div>
        </div>
      </header>

      <div className="p-4 md:p-8 max-w-7xl mx-auto">
        {/* 统计卡片 */}
        <div className="grid grid-cols-2 gap-3 md:gap-4 mb-6">
          <div className="bg-white rounded-xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-1">待处理计划</p>
            <p className="text-2xl font-bold text-gray-800">{items.length}</p>
          </div>
          <div className="bg-amber-50 rounded-xl p-4 shadow-sm">
            <p className="text-xs text-amber-600 mb-1">待处理米数</p>
            <p className="text-2xl font-bold text-amber-700">{totalMeters.toFixed(2)}</p>
          </div>
        </div>

        {/* 列表 */}
        {loading ? (
          <div className="text-center py-12 text-gray-400">加载中...</div>
        ) : items.length === 0 ? (
          <div className="text-center py-12 text-gray-400">
            <Package className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p>暂无待处理坯布</p>
          </div>
        ) : (
          <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
            <div className="p-4 border-b border-gray-100">
              <h2 className="text-base font-semibold text-gray-800">待处理列表</h2>
            </div>
            <div className="divide-y divide-gray-100">
              {items.map((item, index) => (
                <motion.div
                  key={item.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: Math.min(index * 0.02, 0.1) }}
                  onClick={() => navigate(`/washing/plans?id=${item.id}`)}
                  className="p-4 hover:bg-gray-50 transition-colors cursor-pointer"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <span className={`px-2 py-1 rounded-lg text-xs font-medium ${statusMap[item.status]?.bgColor} ${statusMap[item.status]?.color}`}>
                          {statusMap[item.status]?.label}
                        </span>
                        <span className="text-xs text-gray-400">{item.plan_code}</span>
                      </div>
                      <p className="font-medium text-gray-800 mb-1">
                        {item.purchaser_name}
                      </p>
                      <p className="text-sm text-gray-600">
                        {item.product_name} - {item.product_color}
                      </p>
                      <p className="text-xs text-gray-400 mt-1">
                        坯布码: {item.fabric_code}
                      </p>
                    </div>
                    <div className="text-right">
                      <p className="text-lg font-bold text-amber-600">
                        {item.planned_meters}米
                      </p>
                      <p className="text-xs text-gray-400">
                        {new Date(item.created_at).toLocaleDateString('zh-CN')}
                      </p>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
