'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthGuard } from '@/hooks/useAuthGuard';
import { useTranslation } from '@/hooks/useTranslation';
import { PageState } from '@/components/common/feedback/PageState';
import { 
  getFormDefinitions, 
  type FormDefinition 
} from '@/services/api/form-management';
import { 
  Search, 
  FileText,
  Car,
  DollarSign,
  ShoppingCart,
  Clock,
  Plane,
  Calendar,
  Users,
  X
} from 'lucide-react';
import { toast } from '@/lib/toast';

// ============================================
// 类型定义
// ============================================

interface CategoryGroup {
  name: string;
  nameEn: string;
  forms: FormDefinition[];
}

// 图标映射
const iconMap: Record<string, React.ReactNode> = {
  car: <Car className="w-5 h-5" />,
  dollar: <DollarSign className="w-5 h-5" />,
  shopping: <ShoppingCart className="w-5 h-5" />,
  clock: <Clock className="w-5 h-5" />,
  plane: <Plane className="w-5 h-5" />,
  calendar: <Calendar className="w-5 h-5" />,
  users: <Users className="w-5 h-5" />,
  file: <FileText className="w-5 h-5" />,
};

// 图标颜色映射
const iconColorMap: Record<string, string> = {
  car: 'bg-orange-500',
  dollar: 'bg-blue-500',
  shopping: 'bg-blue-600',
  clock: 'bg-blue-500',
  plane: 'bg-green-500',
  calendar: 'bg-pink-500',
  users: 'bg-purple-500',
  file: 'bg-gray-500',
};

// ============================================
// 主组件
// ============================================

export default function SubmitRequestPage() {
  const router = useRouter();
  const { isReady } = useAuthGuard();
  const { t, locale } = useTranslation();

  // ========== 状态管理 ==========
  const [searchTerm, setSearchTerm] = useState('');
  const [recentForms, setRecentForms] = useState<FormDefinition[]>([]);
  const [allForms, setAllForms] = useState<FormDefinition[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCategory, setSelectedCategory] = useState<string>('');

  // ========== 数据加载 ==========
  useEffect(() => {
    if (!isReady) return;
    loadData();
  }, [isReady]);

  const loadData = async () => {
    try {
      setLoading(true);
      
      // 加载所有表单（按创建时间倒序，最新的在前面）
      const allRes = await getFormDefinitions({ 
        forUse: true, 
        status: 'PUBLISHED',
        limit: 100 
      });
      
      // 取前 5 个作为最近表单
      const recentRes = allRes.items.slice(0, 5);
      
      console.log('[SubmitRequest] Loaded forms:', {
        total: allRes.items.length,
        recent: recentRes.length,
      });
      
      setRecentForms(recentRes);
      setAllForms(allRes.items);
      
      // 默认选中第一个分类
      if (allRes.items.length > 0) {
        const categories = getCategoryGroups(allRes.items);
        if (categories.length > 0) {
          setSelectedCategory(categories[0].name);
        }
      }
    } catch (error) {
      console.error('[SubmitRequest] Load data error:', error);
      toast.error(t.common.error);
    } finally {
      setLoading(false);
    }
  };

  // ========== 数据处理 ==========
  
  // 按分类分组
  const getCategoryGroups = (forms: FormDefinition[]): CategoryGroup[] => {
    const groupMap = new Map<string, FormDefinition[]>();
    
    forms.forEach(form => {
      const category = form.category || (locale === 'zh' ? '未分类' : 'Uncategorized');
      if (!groupMap.has(category)) {
        groupMap.set(category, []);
      }
      groupMap.get(category)!.push(form);
    });
    
    return Array.from(groupMap.entries()).map(([name, forms]) => ({
      name,
      nameEn: name, // TODO: 需要分类的多语言支持
      forms,
    }));
  };

  // 搜索过滤
  const filteredForms = allForms.filter(form => {
    if (!searchTerm) return true;
    const term = searchTerm.toLowerCase();
    return (
      form.name.toLowerCase().includes(term) ||
      form.key.toLowerCase().includes(term) ||
      form.description?.toLowerCase().includes(term)
    );
  });

  // 推荐表单（最近使用 + 高频使用）
  const recommendedForms = recentForms.slice(0, 6);

  // 获取分类列表
  const categoryGroups = getCategoryGroups(filteredForms);

  // ========== 交互处理 ==========
  const handleFormClick = (form: FormDefinition) => {
    // 跳转到表单填写页面
    router.push(`/forms/fill/${form.key}`);
  };

  // 清除最近编辑
  const clearRecentForm = () => {
    setRecentForms([]);
  };

  // ========== 渲染函数 ==========
  
  // 获取表单图标
  const getFormIcon = (form: FormDefinition) => {
    const iconKey = form.icon || 'file';
    return iconMap[iconKey] || iconMap.file;
  };

  // 获取表单图标颜色
  const getFormIconColor = (form: FormDefinition) => {
    const iconKey = form.icon || 'file';
    return iconColorMap[iconKey] || iconColorMap.file;
  };

  // 渲染表单卡片
  const renderFormCard = (form: FormDefinition, showCategory = false) => (
    <button
      key={form.id}
      onClick={() => handleFormClick(form)}
      className="flex items-center gap-3 p-4 bg-white border border-gray-200 rounded-lg hover:border-[#3370ff] hover:shadow-md transition-all group text-left"
    >
      {/* 图标 */}
      <div className={`w-10 h-10 rounded-lg ${getFormIconColor(form)} flex items-center justify-center text-white flex-shrink-0`}>
        {getFormIcon(form)}
      </div>
      
      {/* 内容 */}
      <div className="flex-1 min-w-0">
        <h3 className="text-sm font-medium text-gray-900 truncate group-hover:text-[#3370ff]">
          {form.name}
        </h3>
        {showCategory && form.category && (
          <p className="text-xs text-gray-500 mt-0.5 truncate">
            {form.category}
          </p>
        )}
      </div>
    </button>
  );

  // ========== 主渲染 ==========
  if (!isReady) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex flex-col items-center gap-3">
          <div className="animate-spin rounded-full h-10 w-10 border-3 border-gray-200 border-t-blue-600"></div>
          <p className="text-sm text-gray-500">{t.common.loading}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#f7f8fa]">
      {/* 顶部搜索栏 */}
      <div className="bg-white border-b" style={{ borderColor: '#e5e6eb' }}>
        <div className="max-w-7xl mx-auto px-6 py-6">
          <div className="relative max-w-2xl">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder={locale === 'zh' ? '请输入应用名称' : 'Please enter the name of the application'}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
        </div>
      </div>

      {/* 主内容区 */}
      <div className="max-w-7xl mx-auto px-6 py-6">
        {/* 最近编辑 */}
        {!searchTerm && recentForms.length > 0 && (
          <div className="mb-8">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-sm font-medium text-gray-700">
                {locale === 'zh' ? '最近编辑：' : 'Last edited:'}
                <span className="ml-2 text-[#3370ff] underline cursor-pointer">
                  {recentForms[0].name}
                </span>
              </h2>
              <button
                onClick={clearRecentForm}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}

        {/* 推荐应用 */}
        {!searchTerm && recommendedForms.length > 0 && (
          <div className="mb-8">
            <h2 className="text-base font-semibold text-gray-900 mb-4">
              {locale === 'zh' ? '推荐' : 'Recommended'}
            </h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
              {recommendedForms.map(form => renderFormCard(form, true))}
            </div>
          </div>
        )}

        {/* 所有应用 */}
        <div>
          <h2 className="text-base font-semibold text-gray-900 mb-4">
            {locale === 'zh' ? '所有应用' : 'All Applications'}
          </h2>

          {loading ? (
            <div className="flex items-center justify-center py-16">
              <div className="flex flex-col items-center gap-3">
                <div className="animate-spin rounded-full h-8 w-8 border-2 border-gray-200 border-t-blue-600"></div>
                <p className="text-sm text-gray-500">{t.common.loading}</p>
              </div>
            </div>
          ) : categoryGroups.length === 0 ? (
            <div className="flex items-center justify-center py-16">
              <PageState
                variant="empty"
                title={t.approvals.emptyStates.noFormsAvailable}
                layout="center"
                className="border-0 bg-transparent"
              />
            </div>
          ) : (
            <div className="flex gap-6">
              {/* 左侧分类列表 */}
              <div className="w-64 flex-shrink-0">
                <div className="bg-white rounded-lg border border-gray-200 p-2">
                  {categoryGroups.map(group => (
                    <button
                      key={group.name}
                      onClick={() => setSelectedCategory(group.name)}
                      className={`
                        w-full px-4 py-2.5 text-left text-sm rounded-lg transition-colors
                        ${selectedCategory === group.name
                          ? 'bg-[#eef2ff] text-[#3370ff] font-medium'
                          : 'text-gray-700 hover:bg-gray-50'
                        }
                      `}
                    >
                      {group.name}
                    </button>
                  ))}
                </div>
              </div>

              {/* 右侧表单列表 */}
              <div className="flex-1">
                {categoryGroups.map(group => {
                  if (selectedCategory && group.name !== selectedCategory) {
                    return null;
                  }
                  
                  return (
                    <div key={group.name} className="mb-8 last:mb-0">
                      <h3 className="text-base font-semibold text-gray-900 mb-4">
                        {group.name}
                      </h3>
                      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                        {group.forms.map(form => renderFormCard(form))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
