import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { washingApi } from '../../api';
import { motion } from 'framer-motion';
import { Import, Warehouse, CreditCard, ArrowLeft, Users, Droplets, Package, CheckCircle, Clock, LogOut, FileText, Plus, TrendingUp, Building2, ChevronRight, Hash, Target, Activity } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import { OnboardingGuide, shouldShowOnboarding } from '../../components/OnboardingGuide';
import { NotificationCenter } from '../../components/NotificationCenter';
import { HelpCenter, HelpButton } from '../../components/HelpCenter';
import { VersionUpdate, useVersionCheck, AboutModal } from '../../components/VersionUpdate';
import { FeedbackModal } from '../../components/FeedbackModal';
import { UserManual } from '../../components/UserManual';
import { CrashReporter } from '../../components/CrashReporter';
import type { WashingPlan } from '../../types';
import { LoadingSpinner } from '../../components/ui/LoadingSpinner';
import { AccountProfileCard } from '../../components/AccountProfileCard';
import { PLAN_STATUS } from '../../utils/constants';

const statusMap: Record<string, { label: string; color: string; bgColor: string; icon: any; borderColor: string }> = {
  pending: { label: '待处理', color: 'text-amber-600', bgColor: 'bg-amber-50', borderColor: 'border-amber-200', icon: Clock },
  processing: { label: '处理中', color: 'text-violet-600', bgColor: 'bg-violet-50', borderColor: 'border-violet-200', icon: TrendingUp },
  completed: { label: '已完成', color: 'text-emerald-600', bgColor: 'bg-emerald-50', borderColor: 'border-emerald-200', icon: Package }
};

const getQuickActions = (isMaster: boolean) => {
  const actions = [
    { id: 'plans', icon: FileText, label: '计划总览', path: '/washing/plans', gradient: 'from-violet-400 to-fuchsia-400', description: '查看所有计划' },
    { id: 'pending', icon: Package, label: '待处理坯布', path: '/washing/pending', gradient: 'from-amber-500 to-orange-500', description: '处理待水洗坯布' },
    { id: 'completed', icon: CheckCircle, label: '已完成坯布', path: '/washing/completed', gradient: 'from-emerald-500 to-green-500', description: '查看已完成水洗' },
    { id: 'finished', icon: Warehouse, label: '成品仓库', path: '/washing/finished-warehouse', gradient: 'from-violet-400 to-fuchsia-400', description: '管理成品库存' },
    { id: 'payment', icon: CreditCard, label: '待结款', path: '/washing/payments', gradient: 'from-rose-500 to-pink-500', description: '查看待结款项' }
  ];
  if (isMaster) {
    actions.push({ id: 'members', icon: Users, label: '账号管理', path: '/members', gradient: 'from-fuchsia-400 to-purple-400', description: '管理团队账号' });
  }
  return actions;
};


export function WashingDashboard() {
  const navigate = useNavigate();
  const { auth, logout } = useAuth();
  const { isMobile } = useResponsive();
  const [plans, setPlans] = useState<WashingPlan[]>([]);
  const [loading, setLoading] = useState(true);

  // 帮助中心状态
  const [showHelp, setShowHelp] = useState(false);
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [showUserManual, setShowUserManual] = useState(false);
  const [showFeedback, setShowFeedback] = useState(false);
  const [showAbout, setShowAbout] = useState(false);

  // 版本更新检查
  const { showUpdate, setShowUpdate } = useVersionCheck();

  // 账户卡片弹窗状态
  const [showAccountCard, setShowAccountCard] = useState(false);

  // 最近计划轮播索引
  const [currentPlanIndex, setCurrentPlanIndex] = useState(0);

  // 检查是否显示新手引导
  useEffect(() => {
    if (shouldShowOnboarding('washing')) {
      setShowOnboarding(true);
    }
  }, []);

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

  const fetchPlans = async () => {
    const response = await washingApi.listPlans();
    setPlans(response.data || []);
    setLoading(false);
  };

  const stats = {
    all: plans.length,
    producing: plans.filter(p => p.status === 'processing').length,
    completed: plans.filter(p => p.status === PLAN_STATUS.COMPLETED).length
  };

  // 获取进行中的计划用于轮播
  const processingPlans = plans.filter(p => p.status === 'processing').slice(0, isMobile ? 5 : 6);
  const recentPlans = plans.slice(0, isMobile ? 5 : 10);

  // 桌面端统计卡片数据
  const statCards = [
    { id: 'all', label: '所有计划', value: stats.all, sublabel: '累计接收', icon: FileText, color: 'from-violet-400 to-fuchsia-400', bgColor: 'bg-violet-50', textColor: 'text-violet-600', path: '/washing/plans' },
    { id: 'producing', label: '进行中', value: stats.producing, sublabel: '正在水洗', icon: TrendingUp, color: 'from-blue-500 to-indigo-600', bgColor: 'bg-blue-50', textColor: 'text-blue-600', path: '/washing/plans?filter=processing' },
    { id: 'completed', label: '已完成', value: stats.completed, sublabel: '已完工', icon: Package, color: 'from-emerald-500 to-green-600', bgColor: 'bg-emerald-50', textColor: 'text-emerald-600', path: '/washing/plans?filter=completed' }
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-violet-50/40 to-fuchsia-50/30">
      {/* Header - 与采购商一致 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-3 sm:px-4 md:px-8 py-3 sm:py-4 flex justify-between items-center">
          <div className="flex items-center gap-2 sm:gap-3">
            <button
              onClick={() => setShowAccountCard(true)}
              className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-violet-400 to-fuchsia-400 rounded-xl flex items-center justify-center shadow-lg shadow-violet-400/20 cursor-pointer overflow-hidden active:scale-95 transition-transform"
            >
              {(auth.user as any)?.image_url ? (
                <img
                  src={(auth.user as any).image_url}
                  alt="头像"
                  className="w-full h-full object-cover"
                  onError={(e) => {
                    (e.target as HTMLImageElement).style.display = 'none';
                  }}
                />
              ) : (
                <Droplets className="w-4 h-4 sm:w-5 sm:h-5 text-white" />
              )}
            </button>
            <div>
              <h1 className="text-sm sm:text-lg font-bold text-slate-900 flex items-center gap-2 whitespace-nowrap">
                <span className="sm:hidden truncate max-w-[80px]">{(auth.user as any)?.display_name || auth.user?.username || '用户'}</span>
                <span className="hidden sm:inline">{auth.company?.name || '水洗厂'}工作台</span>
                <span className="text-[10px] sm:text-xs bg-gradient-to-r from-violet-400 to-fuchsia-400 text-white px-1.5 sm:px-2 py-0.5 rounded-full font-medium whitespace-nowrap">限时免费</span>
              </h1>
              <p className="text-xs text-slate-500 hidden sm:block truncate max-w-[150px]">{(auth.user as any)?.display_name || auth.user?.username || '用户'}，欢迎回来</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <HelpButton onClick={() => setShowHelp(true)} />
            <NotificationCenter theme="violet" />
            <button
              onClick={async () => { await logout(); navigate('/login'); }}
              className="p-2 sm:px-3 sm:py-1.5 text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg transition-colors"
              title="退出登录"
            >
              <LogOut className="w-5 h-5 sm:hidden" />
              <span className="hidden sm:inline text-xs sm:text-sm">退出</span>
            </button>
          </div>
        </div>
      </header>

      <div className="p-3 sm:p-4 md:p-8 max-w-7xl mx-auto">
        {loading ? (
          <LoadingSpinner text="加载仪表盘数据..." className="py-20" />
        ) : (
          <div className="space-y-4 sm:space-y-6 animate-fade-in">
            {/* 统计卡片 - 移动端3列紧凑布局，桌面端3列 */}
            <div className="grid grid-cols-3 sm:grid-cols-3 gap-2 sm:gap-4">
              {statCards.map((stat) => (
                <div
                  key={stat.id}
                  onClick={() => navigate(stat.path)}
                  className="bg-white rounded-xl sm:rounded-2xl p-3 sm:p-5 shadow-sm border border-slate-200 cursor-pointer hover:border-violet-300 hover:shadow-md transition-all"
                >
                  <div className="flex items-center justify-between mb-2 sm:mb-3">
                    <p className="text-xs sm:text-sm text-slate-500">{stat.label}</p>
                    <div className={`w-6 h-6 sm:w-8 sm:h-8 ${stat.bgColor} rounded-lg flex items-center justify-center`}>
                      <stat.icon className={`w-3 h-3 sm:w-4 sm:h-4 ${stat.textColor}`} />
                    </div>
                  </div>
                  <p className="text-xl sm:text-3xl font-bold text-slate-900">{stat.value}</p>
                  <p className="text-xs text-slate-400 mt-0.5 sm:mt-1">{stat.sublabel}</p>
                </div>
              ))}
            </div>

            {/* 最近计划 - 左右滑动展示 */}
            <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-slate-200 p-3 sm:p-4 md:p-6">
              <div className="flex justify-between items-center mb-3 sm:mb-4">
                <h2 className="text-sm sm:text-base font-semibold text-slate-900 whitespace-nowrap">最近计划</h2>
                <button
                  onClick={() => navigate('/washing/plans')}
                  className="text-xs sm:text-sm text-violet-600 hover:text-violet-700 font-medium flex items-center gap-1 whitespace-nowrap"
                >
                  查看全部
                  <ArrowLeft className="w-3 h-3 sm:w-4 sm:h-4 rotate-180" />
                </button>
              </div>

              {processingPlans.length === 0 ? (
                <div className="text-center py-8 sm:py-12 text-slate-400">
                  <Package className="w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-3 text-slate-300" />
                  <p className="text-sm">暂无进行中的计划</p>
                  <button
                    onClick={() => navigate('/washing/plans')}
                    className="mt-3 px-4 py-2 bg-violet-400 text-white rounded-lg text-sm hover:bg-violet-500 transition-colors"
                  >
                    查看计划
                  </button>
                </div>
              ) : (
                <div className="relative">
                  {/* 滑动容器 - 移动端 */}
                  {isMobile ? (
                    <>
                      <div className="overflow-hidden">
                        <div
                          className="flex transition-transform duration-300 ease-out"
                          style={{ transform: `translateX(-${currentPlanIndex * 100}%)` }}
                        >
                          {processingPlans.map((plan) => {
                            const status = statusMap[plan.status] || statusMap.pending;
                            const StatusIcon = status.icon;

                            return (
                              <div
                                key={plan.id}
                                className="w-full flex-shrink-0 px-1"
                                onClick={() => navigate(`/washing/plans?id=${plan.id}`)}
                              >
                                <div className="group p-3 sm:p-4 rounded-xl border border-slate-200 hover:border-violet-200 hover:bg-violet-50/30 cursor-pointer transition-all">
                                  {/* 计划标题行 */}
                                  <div className="flex items-center gap-2 sm:gap-3">
                                    <div className={`w-8 h-8 sm:w-10 sm:h-10 rounded-lg flex items-center justify-center ${status.bgColor}`}>
                                      <StatusIcon className={`w-4 h-4 sm:w-5 sm:h-5 ${status.color}`} />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                      <div className="flex items-center gap-1.5 sm:gap-2">
                                        <h3 className="font-medium text-slate-900 text-sm sm:text-base truncate">{plan.plan_code}</h3>
                                        <span className={`px-1.5 py-0.5 text-xs rounded-full whitespace-nowrap ${status.bgColor} ${status.color}`}>
                                          {status.label}
                                        </span>
                                      </div>
                                      <p className="text-xs text-slate-500">{plan.planned_meters}米</p>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>

                      {/* 左右滑动按钮 */}
                      {processingPlans.length > 1 && (
                        <>
                          <button
                            onClick={() => setCurrentPlanIndex(prev => Math.max(0, prev - 1))}
                            disabled={currentPlanIndex === 0}
                            className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-2 w-8 h-8 bg-white shadow-lg rounded-full flex items-center justify-center disabled:opacity-30 disabled:cursor-not-allowed hover:bg-slate-50 transition-colors z-10"
                          >
                            <ArrowLeft className="w-4 h-4 text-slate-600" />
                          </button>
                          <button
                            onClick={() => setCurrentPlanIndex(prev => Math.min(processingPlans.length - 1, prev + 1))}
                            disabled={currentPlanIndex === processingPlans.length - 1}
                            className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-2 w-8 h-8 bg-white shadow-lg rounded-full flex items-center justify-center disabled:opacity-30 disabled:cursor-not-allowed hover:bg-slate-50 transition-colors z-10"
                          >
                            <ArrowLeft className="w-4 h-4 text-slate-600 rotate-180" />
                          </button>
                        </>
                      )}

                      {/* 指示器 */}
                      {processingPlans.length > 1 && (
                        <div className="flex items-center justify-center gap-1.5 mt-4">
                          {processingPlans.map((_, i) => (
                            <button
                              key={i}
                              onClick={() => setCurrentPlanIndex(i)}
                              className={`w-2 h-2 rounded-full transition-all ${
                                i === currentPlanIndex ? 'bg-violet-500 w-4' : 'bg-slate-300 hover:bg-slate-400'
                              }`}
                            />
                          ))}
                        </div>
                      )}
                    </>
                  ) : (
                    /* 桌面端列表布局 */
                    <div className="space-y-3">
                      {recentPlans.map((plan) => {
                        const status = statusMap[plan.status] || statusMap.pending;
                        const StatusIcon = status.icon;

                        return (
                          <motion.div
                            key={plan.id}
                            whileHover={{ scale: 1.01 }}
                            onClick={() => navigate(`/washing/plans?id=${plan.id}`)}
                            className="group p-4 rounded-xl border border-slate-200 hover:border-violet-300 hover:shadow-md cursor-pointer transition-all bg-slate-50/50 hover:bg-white"
                          >
                            <div className="flex items-center gap-4">
                              <div className={`w-12 h-12 rounded-xl ${status.bgColor} border ${status.borderColor} flex items-center justify-center`}>
                                <StatusIcon className={`w-6 h-6 ${status.color}`} />
                              </div>
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2 mb-1">
                                  <h3 className="font-semibold text-slate-900 truncate">{plan.plan_code}</h3>
                                  <span className={`px-2 py-0.5 text-xs font-medium rounded-full ${status.bgColor} ${status.color} border ${status.borderColor}`}>
                                    {status.label}
                                  </span>
                                </div>
                                <div className="flex items-center gap-4 text-sm text-slate-500">
                                  <span className="flex items-center gap-1">
                                    <Target className="w-3.5 h-3.5" />
                                    {plan.planned_meters}米
                                  </span>
                                  <span className="flex items-center gap-1">
                                    <Activity className="w-3.5 h-3.5" />
                                    状态: {status.label}
                                  </span>
                                </div>
                              </div>
                              <ChevronRight className="w-5 h-5 text-slate-400 group-hover:text-violet-500 transition-colors" />
                            </div>
                          </motion.div>
                        );
                      })}
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 快捷操作 */}
            <div className="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-slate-200 p-3 sm:p-4 md:p-6">
              <h2 className="text-sm sm:text-base font-semibold text-slate-900 mb-3 sm:mb-4 whitespace-nowrap">快捷操作</h2>
              <div className="grid grid-cols-3 sm:grid-cols-4 gap-2 sm:gap-3">
                {getQuickActions(auth.user?.is_master || false).map((action) => (
                  <motion.button
                    key={action.id}
                    whileHover={isMobile ? {} : { scale: 1.03, y: -2 }}
                    whileTap={{ scale: 0.97 }}
                    onClick={() => navigate(action.path)}
                    className="group flex flex-col items-center p-2 sm:p-3 rounded-lg sm:rounded-xl border border-slate-100 hover:border-transparent hover:shadow-md transition-all bg-slate-50/50 hover:bg-white"
                  >
                    <div className={`w-8 h-8 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl flex items-center justify-center mb-1 sm:mb-2 bg-gradient-to-br ${action.gradient} shadow-sm group-hover:shadow-md transition-shadow`}>
                      <action.icon className="w-4 h-4 sm:w-5 sm:h-5 text-white" />
                    </div>
                    <span className="text-[10px] sm:text-xs font-medium text-slate-700 group-hover:text-slate-900 text-center whitespace-nowrap">{action.label}</span>
                  </motion.button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 帮助中心弹窗 */}
      <HelpCenter isOpen={showHelp} onClose={() => setShowHelp(false)} />

      {/* 新手引导 */}
      <OnboardingGuide
        role="washing"
        isOpen={showOnboarding}
        onClose={() => setShowOnboarding(false)}
      />

      {/* 用户手册 */}
      <UserManual isOpen={showUserManual} onClose={() => setShowUserManual(false)} />

      {/* 反馈弹窗 */}
      <FeedbackModal isOpen={showFeedback} onClose={() => setShowFeedback(false)} />

      {/* 关于窗口 */}
      <AboutModal isOpen={showAbout} onClose={() => setShowAbout(false)} />

      {/* 版本更新弹窗 */}
      <VersionUpdate
        isOpen={showUpdate}
        onClose={() => setShowUpdate(false)}
      />

      {/* 崩溃报告 */}
      <CrashReporter />

      {/* 账户卡片弹窗 */}
      <AccountProfileCard
        isOpen={showAccountCard}
        onClose={() => setShowAccountCard(false)}
        role="washing"
        onShowUserManual={() => setShowUserManual(true)}
        onShowFeedback={() => setShowFeedback(true)}
        onShowAbout={() => setShowAbout(true)}
      />
    </div>
  );
}
