'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  LayoutTemplate,
  Search,
  Plus,
  Eye,
  Copy,
  Users,
  Loader2,
} from 'lucide-react';
import { toast } from '@/lib/toast';
import { useTranslation } from '@/hooks/useTranslation';
import { getFormTemplates, type FormTemplate } from '@/services/api/forms';
import { ApiClientError } from '@/lib/api-client';
import { PageState } from '@/components/common/feedback/PageState';

export default function FormTemplatesPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const [templates, setTemplates] = useState<FormTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('');

  useEffect(() => {
    loadTemplates();
  }, [categoryFilter]);

  const loadTemplates = async () => {
    try {
      setLoading(true);
      const response = await getFormTemplates({
        category: categoryFilter || undefined,
        isPublic: true,
      });
      setTemplates(response.items);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.loadFailed}: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const filteredTemplates = templates.filter((t) => {
    const name = t.nameI18n?.['zh-CN'] || t.nameI18n?.['en-US'] || Object.values(t.nameI18n || {})[0] || '';
    return !searchTerm || name.toLowerCase().includes(searchTerm.toLowerCase());
  });

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: '#f7f8fa' }}>
      {/* 标题栏 - 飞书风格，固定 h-12 */}
      <div className="bg-white border-b" style={{ borderColor: '#e5e6eb' }}>
        <div className="px-6 h-12">
          <div className="flex items-center justify-between h-full">
            {/* 左侧：标题 + 搜索 + 筛选 */}
            <div className="flex items-center gap-3">
              <h1 className="text-base font-semibold flex items-center" style={{ color: '#1f2329' }}>
                <LayoutTemplate className="w-5 h-5 mr-2 text-blue-600" />
                {'表单模板'}
              </h1>
              
              {/* 搜索框 - 无边框背景色风格 */}
              <div className="relative">
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder={'搜索模板...'}
                  className="px-3 py-1.5 pl-9 rounded-lg text-sm outline-none transition-all"
                  style={{ 
                    width: '280px',
                    backgroundColor: '#f7f8fa',
                    color: '#1f2329',
                    border: 'none'
                  }}
                  onFocus={(e) => {
                    e.target.style.backgroundColor = '#eff0f2';
                    e.target.style.boxShadow = '0 0 0 2px rgba(51, 112, 255, 0.1)';
                  }}
                  onBlur={(e) => {
                    e.target.style.backgroundColor = '#f7f8fa';
                    e.target.style.boxShadow = 'none';
                  }}
                />
                <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2" style={{ color: '#8f959e' }} />
              </div>
              
              {/* 分类筛选 */}
              <select
                value={categoryFilter || 'all'}
                onChange={(e) => setCategoryFilter(e.target.value === 'all' ? '' : e.target.value)}
                className="px-3 py-1.5 rounded-lg text-sm outline-none transition-all cursor-pointer"
                style={{ 
                  backgroundColor: '#f7f8fa',
                  color: '#1f2329',
                  border: 'none',
                  minWidth: '120px'
                }}
                onFocus={(e) => {
                  e.currentTarget.style.backgroundColor = '#eff0f2';
                }}
                onBlur={(e) => {
                  e.currentTarget.style.backgroundColor = '#f7f8fa';
                }}
              >
                <option value="all">{'全部分类'}</option>
                <option value="HR">{'人力资源'}</option>
                <option value="FINANCE">{'财务'}</option>
                <option value="IT">{'IT'}</option>
                <option value="ADMIN">{'行政'}</option>
              </select>
            </div>
            
            {/* 右侧：创建按钮 */}
            <button
              onClick={() => router.push('/forms/templates/new')}
              className="px-4 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-2"
              style={{ 
                backgroundColor: '#3370ff',
                color: '#ffffff',
                border: 'none'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#1e5eff';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = '#3370ff';
              }}
            >
              <Plus className="w-4 h-4" />
              {'创建模板'}
            </button>
          </div>
        </div>
      </div>

      {/* 内容区域 - flex-1 自动占满剩余空间 */}
      <div className="flex-1 overflow-auto">
        <div className="p-6">
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
            </div>
          ) : filteredTemplates.length === 0 ? (
            <div className="h-64 flex items-center justify-center">
              <PageState
                variant="empty"
                title={t.forms.templates.noTemplates}
                description={t.forms.templates.noTemplatesDesc}
                actionLabel={t.forms.templates.create}
                onAction={() => router.push('/forms/templates/new')}
                layout="center"
                className="mx-auto w-full max-w-2xl border-0 bg-transparent"
              />
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredTemplates.map((template) => {
                const name = template.nameI18n?.['zh-CN'] || template.nameI18n?.['en-US'] || Object.values(template.nameI18n || {})[0] || '未命名模板';
                const description = template.descriptionI18n?.['zh-CN'] || template.descriptionI18n?.['en-US'] || Object.values(template.descriptionI18n || {})[0];
                
                return (
                  <div
                    key={template.id}
                    className="bg-white rounded-lg shadow-sm transition-all cursor-pointer"
                    style={{ border: '1px solid #e5e6eb' }}
                    onClick={() => router.push(`/forms/templates/${template.id}`)}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.08)';
                      e.currentTarget.style.borderColor = '#c9cdd4';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.1)';
                      e.currentTarget.style.borderColor = '#e5e6eb';
                    }}
                  >
                    <div className="p-6">
                      {/* 顶部：图标 + 分类标签 */}
                      <div className="flex items-start justify-between mb-4">
                        <div 
                          className="w-12 h-12 rounded-lg flex items-center justify-center" 
                          style={{ 
                            background: template.color || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
                          }}
                        >
                          <LayoutTemplate className="w-6 h-6 text-white" />
                        </div>
                        <div className="flex items-center gap-2">
                          {template.category && (
                            <span 
                              className="text-xs px-2 py-0.5 rounded"
                              style={{ 
                                backgroundColor: 'rgba(134, 144, 156, 0.1)',
                                color: '#646a73'
                              }}
                            >
                              {template.category}
                            </span>
                          )}
                          {template.isBuiltin && (
                            <span 
                              className="text-xs px-2 py-0.5 rounded"
                              style={{ 
                                backgroundColor: 'rgba(51, 112, 255, 0.1)',
                                color: '#3370ff'
                              }}
                            >
                              {'内置'}
                            </span>
                          )}
                        </div>
                      </div>
                      
                      {/* 标题 */}
                      <h3 className="font-semibold mb-2 transition-colors" style={{ color: '#1f2329' }}>
                        {name}
                      </h3>
                      
                      {/* 描述 */}
                      {description && (
                        <p className="text-sm line-clamp-2 mb-4" style={{ color: '#8f959e' }}>
                          {description}
                        </p>
                      )}

                      {/* 创建者和公开标签 */}
                      <div className="flex items-center justify-between text-xs mb-4" style={{ color: '#8f959e' }}>
                        {template.creator && (
                          <div className="flex items-center gap-1">
                            <Users className="w-3 h-3" />
                            <span>{template.creator.displayName}</span>
                          </div>
                        )}
                        {template.isPublic && (
                          <span 
                            className="px-2 py-0.5 rounded-full"
                            style={{ 
                              backgroundColor: 'rgba(0, 180, 42, 0.1)',
                              color: '#00b42a'
                            }}
                          >
                            {'公开'}
                          </span>
                        )}
                      </div>

                      {/* 操作按钮 */}
                      <div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
                        <button
                          onClick={() => router.push(`/forms/templates/${template.id}`)}
                          className="flex-1 px-3 py-1.5 rounded text-sm flex items-center justify-center gap-1 transition-colors"
                          style={{
                            backgroundColor: '#ffffff',
                            color: '#646a73',
                            border: '1px solid #e5e6eb'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = '#f7f8fa';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = '#ffffff';
                          }}
                        >
                          <Eye className="w-4 h-4" />
                          {'预览'}
                        </button>
                        <button
                          onClick={() => router.push(`/forms/templates/${template.id}/use`)}
                          className="flex-1 px-3 py-1.5 rounded text-sm flex items-center justify-center gap-1 transition-colors"
                          style={{
                            backgroundColor: '#3370ff',
                            color: '#ffffff',
                            border: 'none'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = '#1e5eff';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = '#3370ff';
                          }}
                        >
                          <Copy className="w-4 h-4" />
                          {'使用'}
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
