import { useState } from 'react';
import { Button } from '@/client/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
import { Badge } from '@/client/components/ui/badge';
import { Separator } from '@/client/components/ui/separator';
import {
  FileText,
  Upload,
  Download,
  Image,
  Settings,
  CheckCircle,
  Zap,
  Package,
  Rocket,
  Shield,
  User,
  Check,
  Clock,
  Calendar,
  Infinity
} from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import UserInfoModal from '@/client/home/components/UserInfoModal';
import { useAuth } from '@/client/home/hooks/AuthProvider';
import { useQuery } from '@tanstack/react-query';
import { membershipPlanClient, publicSettingsClient } from '@/client/api';
import type { InferResponseType } from 'hono/client';

export default function HomePage() {
  const navigate = useNavigate();
  const { user, isAuthenticated } = useAuth();
  const [hoveredFeature, setHoveredFeature] = useState<number | null>(null);
  const [showUserModal, setShowUserModal] = useState(false);
  const [registerEnabled, setRegisterEnabled] = useState(true);

  const { data: membershipPlans } = useQuery({
    queryKey: ['membership-plans-home'],
    queryFn: async () => {
      const response = await membershipPlanClient.$get();
      if (!response.ok) throw new Error('获取套餐失败');
      const data = await response.json();
      return data.data.filter((plan: any) => plan.isActive === 1).sort((a: any, b: any) => a.sortOrder - b.sortOrder);
    },
  });

  // 获取首页注册设置状态
  useQuery({
    queryKey: ['register-setting-public'],
    queryFn: async () => {
      try {
        const res = await publicSettingsClient.registerStatus.$get();
        if (res.status === 200) {
          const data = await res.json();
          setRegisterEnabled(data.enabled);
        }
      } catch (error) {
        console.error('获取注册设置失败:', error);
      }
      return null;
    }
  });

  const features = [
    {
      icon: <FileText className="h-8 w-8" />,
      title: "元亨Word模板批量处理",
      description: "支持.docx格式，最大10MB，智能字段替换",
      color: "text-blue-600"
    },
    {
      icon: <Image className="h-8 w-8" />,
      title: "智能图片处理",
      description: "支持6种图片格式，自动尺寸控制，保持比例",
      color: "text-green-600"
    },
    {
      icon: <Upload className="h-8 w-8" />,
      title: "Excel数据驱动",
      description: "一键导入Excel数据，批量生成个性化文档",
      color: "text-purple-600"
    },
    {
      icon: <Settings className="h-8 w-8" />,
      title: "灵活配置",
      description: "自定义图片尺寸，实时预览，进度跟踪",
      color: "text-orange-600"
    }
  ];

  const stats = [
    { value: "10MB", label: "Word模板上限", icon: <FileText className="h-5 w-5" /> },
    { value: "500MB", label: "图片压缩包上限", icon: <Package className="h-5 w-5" /> },
    { value: "1000+", label: "支持像素范围", icon: <Image className="h-5 w-5" /> },
    { value: "6种", label: "图片格式支持", icon: <CheckCircle className="h-5 w-5" /> }
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50">
      {/* Header Navigation */}
      <header className="fixed top-0 left-0 right-0 z-50 bg-white/90 backdrop-blur-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center">
              <h1 className="text-xl font-bold text-gray-900">元亨Word</h1>
            </div>
            
            <nav className="hidden md:flex items-center space-x-8">
              <button
                onClick={() => navigate('/templates')}
                className="text-gray-700 hover:text-blue-600 transition-colors font-medium"
              >
                模板广场
              </button>
              <button
                onClick={() => navigate('/pricing')}
                className="text-gray-700 hover:text-blue-600 transition-colors font-medium"
              >
                收费标准
              </button>
              {isAuthenticated ? (
                <button
                  onClick={() => setShowUserModal(true)}
                  className="flex items-center space-x-2 text-gray-700 hover:text-blue-600 transition-colors font-medium"
                >
                  <User className="h-5 w-5" />
                  <span>{user?.nickname || user?.username || '个人中心'}</span>
                </button>
              ) : (
                <>
                  <button
                    onClick={() => navigate('/login')}
                    className="text-gray-700 hover:text-blue-600 transition-colors font-medium"
                  >
                    登录
                  </button>
                  {registerEnabled && (
                    <button
                      // onClick={() => navigate('/register')}
                      // className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors font-medium"
                    >
                      {/* 注册 */}
                    </button>
                  )}
                </>
              )}
            </nav>
          </div>
        </div>
      </header>

      {/* Hero Section */}
      <div className="relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-r from-blue-600/5 to-purple-600/5" />
        
        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-32 pb-16">
          <div className="text-center">
            <div className="inline-flex items-center px-4 py-2 rounded-full bg-blue-100 text-blue-800 text-sm font-medium mb-6">
              <Zap className="h-4 w-4 mr-2" />
              AI驱动的文档批量处理工具
            </div>
            
            <h1 className="text-5xl md:text-6xl font-bold text-gray-900 mb-6">
              元亨Word批量处理
              <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-purple-600">
                增强版
              </span>
            </h1>
            
            <p className="text-xl text-gray-600 max-w-3xl mx-auto mb-8">
              一键批量生成个性化Word文档，智能图片处理，高效数据驱动，
              让繁琐的文档工作变得简单高效
            </p>
            
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <Button 
                size="lg" 
                className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white px-8 py-3 text-lg"
                onClick={() => navigate('/word-preview')}
              >
                <Rocket className="h-5 w-5 mr-2" />
                立即开始
              </Button>
              <Button 
                size="lg" 
                variant="outline"
                className="border-2 px-8 py-3 text-lg"
                onClick={() => document.getElementById('features')?.scrollIntoView({ behavior: 'smooth' })}
              >
                了解更多
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Section */}
      <div className="bg-white/50 backdrop-blur-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
            {stats.map((stat, index) => (
              <div key={index} className="text-center">
                <div className="flex justify-center mb-3">
                  <div className="p-3 bg-blue-100 rounded-full">
                    {stat.icon}
                  </div>
                </div>
                <div className="text-3xl font-bold text-gray-900 mb-1">{stat.value}</div>
                <div className="text-sm text-gray-600">{stat.label}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Features Section */}
      <div id="features" className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">
              为什么选择我们
            </h2>
            <p className="text-xl text-gray-600 max-w-2xl mx-auto">
              专业、高效、智能的文档处理解决方案
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8">
            {features.map((feature, index) => (
              <Card 
                key={index}
                className={`border-0 shadow-lg transition-all duration-300 hover:shadow-xl hover:-translate-y-1 cursor-pointer ${
                  hoveredFeature === index ? 'shadow-xl -translate-y-1' : ''
                }`}
                onMouseEnter={() => setHoveredFeature(index)}
                onMouseLeave={() => setHoveredFeature(null)}
                onClick={() => navigate('/word-preview')}
              >
                <CardHeader>
                  <div className={`p-3 rounded-lg bg-gray-50 inline-block mb-4 ${feature.color}`}>
                    {feature.icon}
                  </div>
                  <CardTitle className="text-xl">{feature.title}</CardTitle>
                </CardHeader>
                <CardContent>
                  <CardDescription className="text-base">
                    {feature.description}
                  </CardDescription>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </div>

      {/* Pricing Section */}
      <div className="py-20 bg-gradient-to-br from-gray-50 to-blue-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">
              灵活的会员套餐
            </h2>
            <p className="text-xl text-gray-600">
              选择最适合您的套餐，享受高效文档处理体验
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8">
            {membershipPlans?.map((plan) => (
              <Card
                key={plan.id}
                className={`relative border-0 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 ${
                  plan.type === 'yearly' ? 'ring-2 ring-blue-500' : ''
                }`}
              >
                {plan.type === 'yearly' && (
                  <div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
                    <Badge className="bg-gradient-to-r from-blue-600 to-purple-600 text-white">
                      推荐
                    </Badge>
                  </div>
                )}
                
                <CardHeader>
                  <div className="text-center">
                    <h3 className="text-2xl font-bold mb-2">{plan.name}</h3>
                    <div className="text-4xl font-bold text-blue-600 mb-2">
                      ¥{plan.price}
                    </div>
                    <p className="text-gray-600">
                      {plan.durationDays === 0 ? '永久有效' :
                       plan.durationDays === 1 ? '24小时有效' :
                       `${plan.durationDays}天有效`}
                    </p>
                  </div>
                </CardHeader>
                
                <CardContent>
                  <ul className="space-y-3">
                    {plan.features?.map((feature: string, index: number) => (
                      <li key={index} className="flex items-start">
                        <Check className="h-5 w-5 text-green-500 mr-2 flex-shrink-0 mt-0.5" />
                        <span className="text-gray-700 text-sm">{feature}</span>
                      </li>
                    ))}
                  </ul>
                  
                  <Button
                    className="w-full mt-6 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700"
                    onClick={() => navigate('/pricing')}
                  >
                    立即选择
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </div>

      {/* How It Works */}
      <div className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">
              简单三步，完成批量处理
            </h2>
            <p className="text-xl text-gray-600">
              无需复杂配置，轻松上手
            </p>
          </div>

          <div className="grid md:grid-cols-3 gap-8">
            {[
              { step: 1, title: "上传模板", description: "选择Word模板文件，支持{字段名}和{%图片名%}占位符", icon: <Upload className="h-8 w-8" /> },
              { step: 2, title: "导入数据", description: "上传Excel数据文件，自动匹配模板字段", icon: <FileText className="h-8 w-8" /> },
              { step: 3, title: "批量生成", description: "一键生成所有个性化文档，支持批量下载", icon: <Download className="h-8 w-8" /> }
            ].map((item, index) => (
              <div key={index} className="text-center">
                <div className="w-16 h-16 bg-blue-600 text-white rounded-full flex items-center justify-center text-2xl font-bold mx-auto mb-4">
                  {item.step}
                </div>
                <h3 className="text-xl font-semibold mb-2">{item.title}</h3>
                <p className="text-gray-600">{item.description}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Application Scenarios */}
      <div className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">
              应用场景
            </h2>
            <p className="text-xl text-gray-600 max-w-3xl mx-auto">
              元亨WORD批量处理广泛应用于各类重复性文档工作场景
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
            {[
              {
                title: "项目资料安装调试表",
                description: "批量生成项目安装调试记录表，自动填充项目名称、设备型号、安装位置等关键信息",
                icon: <FileText className="h-8 w-8" />,
                color: "text-blue-600"
              },
              {
                title: "项目勘察设计点位表",
                description: "快速生成勘察设计点位标记文档，包含坐标、尺寸、材质等详细参数",
                icon: <Package className="h-8 w-8" />,
                color: "text-green-600"
              },
              {
                title: "合同批量生成",
                description: "基于标准合同模板，批量生成个性化合同文档，自动填充客户信息、金额等变量",
                icon: <Shield className="h-8 w-8" />,
                color: "text-purple-600"
              },
              {
                title: "报告文档自动化",
                description: "将固定格式的报告模板与数据源结合，自动生成包含不同数据的完整报告",
                icon: <FileText className="h-8 w-8" />,
                color: "text-orange-600"
              },
              {
                title: "证书批量制作",
                description: "批量生成各类证书、证明文件，自动填充获奖者信息、日期、编号等",
                icon: <CheckCircle className="h-8 w-8" />,
                color: "text-red-600"
              },
              {
                title: "表格数据填充",
                description: "将Excel数据批量填充到Word表格模板中，适用于各类统计报表生成",
                icon: <Settings className="h-8 w-8" />,
                color: "text-indigo-600"
              }
            ].map((scenario, index) => (
              <Card key={index} className="border-0 shadow-lg hover:shadow-xl transition-all duration-300">
                <CardHeader>
                  <div className={`p-3 rounded-lg bg-gray-50 inline-block mb-4 ${scenario.color}`}>
                    {scenario.icon}
                  </div>
                  <CardTitle className="text-xl">{scenario.title}</CardTitle>
                </CardHeader>
                <CardContent>
                  <CardDescription className="text-base">
                    {scenario.description}
                  </CardDescription>
                </CardContent>
              </Card>
            ))}
          </div>

          <div className="mt-12 text-center">
            <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-xl p-8">
              <h3 className="text-2xl font-bold text-gray-900 mb-4">核心技术特征</h3>
              <p className="text-lg text-gray-700 max-w-4xl mx-auto">
                适用于所有符合"基础格式固定、核心信息可变量替换"特征的文档场景。
                通过自动化"重复的格式排版、固定内容录入"工作，让您专注于"差异化信息填充"，
                大幅减少人工冗余操作，提升工作效率10倍以上。
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* CTA Section */}
      <div className="py-20 bg-gradient-to-r from-blue-600 to-purple-600">
        <div className="max-w-4xl mx-auto text-center px-4 sm:px-6 lg:px-8">
          <h2 className="text-4xl font-bold text-white mb-4">
            开始您的文档批量处理之旅
          </h2>
          <p className="text-xl text-blue-100 mb-8">
            立即体验高效、智能的文档处理方式
          </p>
          <Button 
            size="xl" 
            className="bg-white text-blue-600 hover:bg-gray-100 px-12 py-4 text-xl font-semibold"
            onClick={() => navigate('/word-preview')}
          >
            <Shield className="h-5 w-5 mr-2" />
            免费开始使用（5份以内3次免费体验）
          </Button>
        </div>
      </div>

      {/* Footer */}
      <footer className="bg-gray-900 text-white py-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <h3 className="text-2xl font-bold mb-4">元亨Word批量处理工具</h3>
            <p className="text-gray-400 mb-6">
              让每一份文档都充满个性，让批量处理变得简单
            </p>
            <div className="flex justify-center space-x-6">
              <Button 
                variant="ghost" 
                className="text-white hover:text-blue-400"
                onClick={() => navigate('/word-preview')}
              >
                立即体验
              </Button>
            </div>
          </div>
        </div>
      </footer>

      <UserInfoModal
        isOpen={showUserModal}
        onClose={() => setShowUserModal(false)}
      />
    </div>
  );
}