import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { purchaserApi, http } from '../../api';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, ChevronDown, ChevronRight, DollarSign, Package, CheckCircle, Clock, AlertCircle } from 'lucide-react';

interface AccountsPayable {
  id: string;
  plan_id: string;
  textile_factory_id: string;
  factory_name: string;
  total_amount: number;
  paid_amount: number;
  unpaid_amount: number;
  total_quantity: number;
  paid_quantity: number;
  unpaid_quantity: number;
  price_per_meter: number;
  status: string;
  created_at: string;
  updated_at: string;
  plan_code: string;
  product_name: string;
  color: string;
}

interface AccountsPayableItem {
  id: string;
  inventory_record_id: string | null;
  quantity: number;
  rolls: number | null;
  price_per_meter: number;
  amount: number;
  status: string;
  created_at: string;
  paid_at: string | null;
}

export function AccountsPayable() {
  const navigate = useNavigate();
  const { auth } = useAuth();
  const [payables, setPayables] = useState<AccountsPayable[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedPlan, setExpandedPlan] = useState<string | null>(null);
  const [payableItems, setPayableItems] = useState<Record<string, AccountsPayableItem[]>>({});

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

  const fetchPayables = async () => {
    setLoading(true);

    try {
      const res = await purchaserApi.listAccountsPayable();
      setPayables((res.data || []) as AccountsPayable[]);
    } catch {
      setPayables([]);
    }

    setLoading(false);
  };

  const fetchPayableItems = async (payableId: string) => {
    try {
      const res = await http.get<AccountsPayableItem[]>(
        `/purchaser/accounts-payable/${payableId}/items`
      );
      setPayableItems(prev => ({
        ...prev,
        [payableId]: res.data || []
      }));
    } catch {
      setPayableItems(prev => ({
        ...prev,
        [payableId]: []
      }));
    }
  };

  const toggleExpand = (payableId: string) => {
    if (expandedPlan === payableId) {
      setExpandedPlan(null);
    } else {
      setExpandedPlan(payableId);
      if (!payableItems[payableId]) {
        fetchPayableItems(payableId);
      }
    }
  };

  const getStatusConfig = (status: string) => {
    switch (status) {
      case 'paid':
        return { label: '已结清', color: 'text-green-600', bgColor: 'bg-green-50', icon: CheckCircle };
      case 'partial':
        return { label: '部分付款', color: 'text-amber-600', bgColor: 'bg-amber-50', icon: Clock };
      default:
        return { label: '未付款', color: 'text-red-600', bgColor: 'bg-red-50', icon: AlertCircle };
    }
  };

  // 统计
  const totalUnpaid = payables.reduce((sum, p) => sum + p.unpaid_amount, 0);
  const totalPaid = payables.reduce((sum, p) => sum + p.paid_amount, 0);

  return (
    <div className="min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="flex items-center gap-2 sm:gap-3 md:gap-4 mb-4 sm:mb-5 md:mb-6">
          <motion.button
            whileTap={{ scale: 0.95 }}
            onClick={() => navigate('/purchaser')}
            className="p-2 hover:bg-gray-200 rounded-full transition-colors will-change-transform"
          >
            <ArrowLeft className="w-5 h-5 sm:w-6 sm:h-6 text-gray-600" />
          </motion.button>
          <h1 className="text-lg sm:text-xl md:text-2xl font-bold text-gray-800">应付账款</h1>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-2 gap-3 sm:gap-4 mb-4 sm:mb-6">
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="bg-white rounded-xl shadow-sm border border-gray-200 p-3 sm:p-4"
          >
            <div className="flex items-center gap-2 mb-2">
              <div className="w-8 h-8 rounded-lg bg-red-100 flex items-center justify-center">
                <DollarSign className="w-4 h-4 text-red-600" />
              </div>
              <span className="text-xs sm:text-sm text-gray-500">未付金额</span>
            </div>
            <p className="text-lg sm:text-xl font-bold text-red-600">¥{totalUnpaid.toFixed(2)}</p>
          </motion.div>
          
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="bg-white rounded-xl shadow-sm border border-gray-200 p-3 sm:p-4"
          >
            <div className="flex items-center gap-2 mb-2">
              <div className="w-8 h-8 rounded-lg bg-green-100 flex items-center justify-center">
                <CheckCircle className="w-4 h-4 text-green-600" />
              </div>
              <span className="text-xs sm:text-sm text-gray-500">已付金额</span>
            </div>
            <p className="text-lg sm:text-xl font-bold text-green-600">¥{totalPaid.toFixed(2)}</p>
          </motion.div>
        </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-blue-500 border-t-transparent rounded-full mb-3"
            />
            <p className="text-gray-400 text-sm">加载中...</p>
          </div>
        ) : payables.length === 0 ? (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center py-12 sm:py-16 text-gray-400 bg-white rounded-xl border border-dashed border-gray-300"
          >
            <Package className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p className="mb-2 text-sm sm:text-base">暂无应付账款</p>
            <p className="text-xs sm:text-sm text-gray-400">生产记录将自动生成应付账款</p>
          </motion.div>
        ) : (
          <div className="space-y-3 sm:space-y-4">
            {payables.map((payable, index) => {
              const statusConfig = getStatusConfig(payable.status);
              const StatusIcon = statusConfig.icon;
              const isExpanded = expandedPlan === payable.id;
              const items = payableItems[payable.id] || [];

              return (
                <motion.div
                  key={payable.id}
                  initial={{ opacity: 0, y: 15 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: Math.min(index * 0.03, 0.2), duration: 0.25 }}
                  className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden"
                >
                  {/* 头部 */}
                  <motion.div
                    onClick={() => toggleExpand(payable.id)}
                    whileTap={{ scale: 0.995 }}
                    className="flex items-center justify-between p-3 sm:p-4 cursor-pointer hover:bg-gray-50 transition-colors will-change-transform"
                  >
                    <div className="flex items-center gap-2 sm:gap-3 min-w-0 flex-1">
                      <motion.div
                        animate={{ rotate: isExpanded ? 90 : 0 }}
                        transition={{ duration: 0.2 }}
                        className="p-1 rounded hover:bg-gray-200 will-change-transform flex-shrink-0"
                      >
                        <ChevronRight size={18} className="sm:w-5 sm:h-5" />
                      </motion.div>
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <h3 className="font-semibold text-gray-800 text-sm sm:text-base truncate">
                            {payable.product_name}-{payable.color}
                          </h3>
                          <span className={`px-2 py-0.5 text-xs rounded-full whitespace-nowrap ${statusConfig.bgColor} ${statusConfig.color}`}>
                            {statusConfig.label}
                          </span>
                        </div>
                        <p className="text-xs text-gray-500">{payable.plan_code} · {payable.factory_name}</p>
                      </div>
                    </div>
                    <div className="text-right flex-shrink-0 ml-2">
                      <p className="text-sm font-bold text-gray-800">¥{payable.unpaid_amount.toFixed(2)}</p>
                      <p className="text-xs text-gray-400">未付</p>
                    </div>
                  </motion.div>

                  {/* 展开的明细 */}
                  <AnimatePresence>
                    {isExpanded && (
                      <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.3, ease: [0.25, 0.46, 0.45, 0.94] }}
                        className="border-t border-gray-100"
                      >
                        <div className="p-3 sm:p-4 bg-gray-50">
                          {/* 汇总信息 */}
                          <div className="grid grid-cols-3 gap-2 sm:gap-4 mb-4 p-3 bg-white rounded-lg border border-gray-200">
                            <div>
                              <p className="text-xs text-gray-500 mb-1">总数量</p>
                              <p className="text-sm font-medium text-gray-800">{payable.total_quantity}米</p>
                            </div>
                            <div>
                              <p className="text-xs text-gray-500 mb-1">单价</p>
                              <p className="text-sm font-medium text-gray-800">¥{payable.price_per_meter}/米</p>
                            </div>
                            <div>
                              <p className="text-xs text-gray-500 mb-1">总金额</p>
                              <p className="text-sm font-medium text-gray-800">¥{payable.total_amount.toFixed(2)}</p>
                            </div>
                          </div>

                          {/* 入库明细 */}
                          <h4 className="text-xs font-medium text-gray-500 mb-2">入库明细</h4>
                          {items.length === 0 ? (
                            <p className="text-xs text-gray-400 py-2">暂无明细</p>
                          ) : (
                            <div className="space-y-2">
                              {items.map((item, itemIndex) => (
                                <motion.div
                                  key={item.id}
                                  initial={{ opacity: 0, x: -10 }}
                                  animate={{ opacity: 1, x: 0 }}
                                  transition={{ delay: itemIndex * 0.05 }}
                                  className="flex items-center justify-between p-2 bg-white rounded-lg border border-gray-200"
                                >
                                  <div className="flex items-center gap-2">
                                    <span className="text-xs text-gray-500">
                                      {new Date(item.created_at).toLocaleDateString('zh-CN')}
                                    </span>
                                    <span className="text-xs text-gray-700">
                                      {item.quantity}米 / {item.rolls}匹/件
                                    </span>
                                  </div>
                                  <div className="flex items-center gap-2">
                                    <span className="text-xs text-gray-500">
                                      ¥{item.price_per_meter}/米
                                    </span>
                                    <span className="text-sm font-medium text-gray-800">
                                      ¥{item.amount.toFixed(2)}
                                    </span>
                                    {item.status === 'paid' ? (
                                      <span className="px-1.5 py-0.5 text-xs rounded-full bg-green-50 text-green-600">
                                        已付
                                      </span>
                                    ) : (
                                      <span className="px-1.5 py-0.5 text-xs rounded-full bg-red-50 text-red-600">
                                        未付
                                      </span>
                                    )}
                                  </div>
                                </motion.div>
                              ))}
                            </div>
                          )}
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
