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, CheckCircle, Droplets, ChevronRight } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import type { WashingPlan, WashingPlanCompletion } from '../../types';

interface CompletedFabricItem {
  id: string;
  plan_code: string;
  purchaser_name: string;
  product_name: string;
  product_color: string;
  fabric_code: string;
  planned_meters: number;
  actual_washed_meters: number;
  shrinkage_rate: number;
  washing_date: string;
  rolls: number;
  completed_at: string;
}

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

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

  const fetchCompletedFabric = async () => {
    setLoading(true);
    
    // 获取已完成的水洗计划
    const { data: washingPlans, 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)
      .eq('status', 'completed')
      .order('updated_at', { ascending: false });

    if (error) {
      console.error('获取已完成坯布失败:', error);
    } else {
      // 获取完成记录详情
      const planIds = (washingPlans || []).map(p => p.id);
      const { data: completions } = await supabase
        .from('washing_plan_completions')
        .select('*')
        .in('washing_plan_id', planIds);

      const completionMap: Record<string, WashingPlanCompletion> = {};
      (completions || []).forEach(c => {
        completionMap[c.washing_plan_id] = c;
      });

      const formattedItems = (washingPlans || []).map(plan => {
        const completion = completionMap[plan.id];
        return {
          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,
          actual_washed_meters: completion?.actual_washed_meters || plan.actual_washed_meters || 0,
          shrinkage_rate: completion?.actual_shrinkage_rate || plan.actual_shrinkage_rate || 0,
          washing_date: completion?.washing_date || plan.washing_date || '',
          rolls: completion?.rolls || 0,
          completed_at: completion?.completed_at || plan.updated_at
        };
      });
      setItems(formattedItems);
    }
    setLoading(false);
  };

  const totalBefore = items.reduce((sum, item) => sum + item.planned_meters, 0);
  const totalAfter = items.reduce((sum, item) => sum + item.actual_washed_meters, 0);
  const avgShrinkage = items.length > 0 
    ? items.reduce((sum, item) => sum + item.shrinkage_rate, 0) / items.length 
    : 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 md:grid-cols-4 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-purple-50 rounded-xl p-4 shadow-sm">
            <p className="text-xs text-purple-600 mb-1">水洗前米数</p>
            <p className="text-2xl font-bold text-purple-700">{totalBefore.toFixed(2)}</p>
          </div>
          <div className="bg-green-50 rounded-xl p-4 shadow-sm">
            <p className="text-xs text-green-600 mb-1">水洗后米数</p>
            <p className="text-2xl font-bold text-green-700">{totalAfter.toFixed(2)}</p>
          </div>
          <div className="bg-purple-50 rounded-xl p-4 shadow-sm">
            <p className="text-xs text-purple-600 mb-1">平均缩水率</p>
            <p className="text-2xl font-bold text-purple-700">{avgShrinkage.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">
            <CheckCircle 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 bg-green-50 text-green-600">
                          已完成
                        </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} | 匹/件数: {item.rolls}匹/件
                      </p>
                    </div>
                    <div className="text-right">
                      <div className="text-sm text-gray-600 mb-1">
                        <span className="text-blue-600">{item.planned_meters}米</span>
                        <span className="mx-1">→</span>
                        <span className="text-green-600 font-bold">{item.actual_washed_meters}米</span>
                      </div>
                      <p className="text-xs text-purple-600">
                        缩水率: {item.shrinkage_rate}%
                      </p>
                      <p className="text-xs text-gray-400 mt-1">
                        {item.washing_date ? new Date(item.washing_date).toLocaleDateString('zh-CN') : '-'}
                      </p>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
