'use client';

import { Suspense, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  FileText,
  Plus,
  Search,
  MoreVertical,
  Copy,
  Archive,
  Trash2,
  Eye,
  GitBranch,
  Palette,
  CheckCircle2,
  Clock,
  PowerOff,
  Loader2,
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import { toast } from '@/lib/toast';
import { useTranslation } from '@/hooks/useTranslation';
import { useConfirm } from '@/components/common/feedback/ConfirmProvider';
import {
  getFormDefinitions,
  deleteFormDefinition,
  archiveFormDefinition,
  type FormDefinition,
  type FormDefinitionStatus,
} from '@/services/api/form-management';
import { getTopLevelOrganizations, type Department } from '@/services/api/organization';
import { ApiClientError } from '@/lib/api-client';

// 加载状态组件
function FormDefinitionsLoading() {
  return (
    <div className="p-8 flex items-center justify-center">
      <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
    </div>
  );
}

// 主页面包装器，使用 Suspense 包裹使用 useSearchParams 的组件
export default function FormDefinitionsPage() {
  return (
    <Suspense fallback={<FormDefinitionsLoading />}>
      <FormDefinitionsContent />
    </Suspense>
  );
}

function FormDefinitionsContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t, locale } = useTranslation();
  const confirm = useConfirm();
  const initialStatus = searchParams.get('status') as FormDefinitionStatus | null;
  
  const [forms, setForms] = useState<FormDefinition[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>(initialStatus || '');
  const [organizationFilter, setOrganizationFilter] = useState<string>('');
  const [organizations, setOrganizations] = useState<Department[]>([]);
  const [loadingOrgs, setLoadingOrgs] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const limit = 20;

  // Load organizations
  useEffect(() => {
    const loadOrganizations = async () => {
      try {
        setLoadingOrgs(true);
        const orgs = await getTopLevelOrganizations();
        setOrganizations(orgs);
      } catch (error) {
        console.error('Failed to load organizations:', error);
      } finally {
        setLoadingOrgs(false);
      }
    };
    loadOrganizations();
  }, []);

  useEffect(() => {
    loadForms();
  }, [page, categoryFilter, statusFilter, organizationFilter]);

  const loadForms = async () => {
    try {
      setLoading(true);
      const response = await getFormDefinitions({
        category: categoryFilter || undefined,
        status: (statusFilter as FormDefinitionStatus) || undefined,
        keyword: searchTerm || undefined,
        organizationId: organizationFilter || undefined,
        page,
        limit,
      });
      setForms(response.items);
      setTotal(response.total);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.loadFailed}: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    setPage(1);
    loadForms();
  };

  const handleDelete = async (form: FormDefinition) => {
    if (form.status !== 'DRAFT') {
      toast.error(t.forms.definition.onlyDraftCanDelete);
      return;
    }
    const confirmMsg = t.forms.definition.confirmDelete.replace('{name}', form.name);
    const confirmed = await confirm({ title: confirmMsg, variant: 'danger' });
    if (!confirmed) return;

    try {
      await deleteFormDefinition(form.id);
      toast.success(t.forms.messages.deleteSuccess);
      loadForms();
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.deleteFailed}: ${error.message}`);
      }
    }
  };

  const handleArchive = async (form: FormDefinition) => {
    const confirmMsg = t.forms.definition.confirmArchive.replace('{name}', form.name);
    const confirmed = await confirm({ title: confirmMsg, variant: 'danger' });
    if (!confirmed) return;
    try {
      await archiveFormDefinition(form.id);
      toast.success(t.forms.messages.formArchived);
      loadForms();
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.operationFailed}: ${error.message}`);
      }
    }
  };

  const handleToggleStatus = async (form: FormDefinition) => {
    try {
      if (form.status === 'PUBLISHED') {
        await archiveFormDefinition(form.id);
        toast.success(t.forms.messages.formArchived);
      } else if (form.status === 'DRAFT') {
        // DRAFT 状态下可能需要先发布，暂时不做处理
        toast.warning(t.forms.messages.draftCannotToggle || '草稿状态无法直接切换');
      }
      loadForms();
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.operationFailed}: ${error.message}`);
      }
    }
  };

  const getStatusBadge = (status: FormDefinitionStatus) => {
    const badges: Record<FormDefinitionStatus, { label: string; bg: string; color: string; icon: typeof CheckCircle2 }> = {
      DRAFT: { 
        label: t.forms.definition.statusLabels.DRAFT, 
        bg: 'rgba(134, 144, 156, 0.1)', 
        color: '#86909c', 
        icon: Clock 
      },
      PUBLISHED: { 
        label: t.forms.definition.statusLabels.PUBLISHED, 
        bg: 'rgba(0, 180, 42, 0.1)', 
        color: '#00b42a', 
        icon: CheckCircle2 
      },
      DISABLED: { 
        label: t.forms.definition.statusLabels.DISABLED, 
        bg: 'rgba(255, 125, 0, 0.1)', 
        color: '#ff7d00', 
        icon: PowerOff 
      },
      ARCHIVED: { 
        label: t.forms.definition.statusLabels.ARCHIVED, 
        bg: 'rgba(134, 144, 156, 0.1)', 
        color: '#86909c', 
        icon: Archive 
      },
    };
    const badge = badges[status] || badges.DRAFT;
    const Icon = badge.icon;
    return (
      <span 
        className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium"
        style={{ backgroundColor: badge.bg, color: badge.color }}
      >
        <Icon className="w-3 h-3" />
        {badge.label}
      </span>
    );
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString(locale, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  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' }}>
                <FileText className="w-5 h-5 mr-2 text-blue-600" />
                {t.forms.definition.title}
              </h1>
              
              {/* 搜索框 - 无边框背景色风格 */}
              <div className="relative">
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                  placeholder={t.forms.definition.searchPlaceholder}
                  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">{t.forms.definition.categories.all}</option>
                <option value="HR">{t.forms.definition.categories.HR}</option>
                <option value="FINANCE">{t.forms.definition.categories.FINANCE}</option>
                <option value="IT">{t.forms.definition.categories.IT}</option>
                <option value="ADMIN">{t.forms.definition.categories.ADMIN}</option>
                <option value="OTHER">{t.forms.definition.categories.OTHER}</option>
              </select>
              
              {/* 状态筛选 */}
              <select
                value={statusFilter || 'all'}
                onChange={(e) => setStatusFilter(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: '100px'
                }}
                onFocus={(e) => {
                  e.currentTarget.style.backgroundColor = '#eff0f2';
                }}
                onBlur={(e) => {
                  e.currentTarget.style.backgroundColor = '#f7f8fa';
                }}
              >
                <option value="all">{t.forms.common.allStatus}</option>
                <option value="DRAFT">{t.forms.definition.statusLabels.DRAFT}</option>
                <option value="PUBLISHED">{t.forms.definition.statusLabels.PUBLISHED}</option>
                <option value="ARCHIVED">{t.forms.definition.statusLabels.ARCHIVED}</option>
              </select>
              
              {/* 组织筛选 */}
              <select
                value={organizationFilter || 'all'}
                onChange={(e) => setOrganizationFilter(e.target.value === 'all' ? '' : e.target.value)}
                disabled={loadingOrgs}
                className="px-3 py-1.5 rounded-lg text-sm outline-none transition-all cursor-pointer"
                style={{ 
                  backgroundColor: '#f7f8fa',
                  color: '#1f2329',
                  border: 'none',
                  minWidth: '140px',
                  opacity: loadingOrgs ? 0.6 : 1
                }}
                onFocus={(e) => {
                  e.currentTarget.style.backgroundColor = '#eff0f2';
                }}
                onBlur={(e) => {
                  e.currentTarget.style.backgroundColor = '#f7f8fa';
                }}
              >
                <option value="all">{t.forms.definition.allOrganizations}</option>
                <option value="">{t.forms.definition.platformForms}</option>
                {organizations.map((org) => (
                  <option key={org.id} value={org.id}>
                    {org.name}
                  </option>
                ))}
              </select>
            </div>
            
            {/* 右侧：新建按钮 */}
            <button
              onClick={() => router.push('/forms/definitions/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" />
              {t.forms.definition.createForm}
            </button>
          </div>
        </div>
      </div>

      {/* 内容区域 - flex-1 自动占满剩余空间 */}
      <div className="flex-1 overflow-auto">
        <div className="p-6">
          {/* 表格容器 */}
          <div className="bg-white rounded-lg shadow-sm" style={{ border: '1px solid #e5e6eb' }}>
            {loading ? (
              <div className="flex items-center justify-center h-64">
                <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
              </div>
            ) : forms.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-64 gap-4">
                <div className="w-20 h-20 rounded-full flex items-center justify-center" style={{ backgroundColor: '#f7f8fa' }}>
                  <FileText className="w-10 h-10" style={{ color: '#c9cdd4' }} />
                </div>
                <div className="text-center">
                  <p className="text-base font-medium mb-1" style={{ color: '#646a73' }}>
                    {t.forms.definition.noForms}
                  </p>
                  <p className="text-sm" style={{ color: '#8f959e' }}>
                    {t.forms.definition.createFirst}
                  </p>
                </div>
                <button
                  onClick={() => router.push('/forms/definitions/new')}
                  className="px-4 py-1.5 rounded-lg text-sm font-medium flex items-center gap-2"
                  style={{ 
                    backgroundColor: '#3370ff',
                    color: '#ffffff',
                    border: 'none'
                  }}
                >
                  <Plus className="w-4 h-4" />
                  {t.forms.definition.createForm}
                </button>
              </div>
            ) : (
              <table className="w-full">
                <thead className="border-b" style={{ borderColor: '#e5e6eb', backgroundColor: '#fafafa' }}>
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium" style={{ color: '#8f959e' }}>
                      {t.forms.definition.formInfo}
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium" style={{ color: '#8f959e' }}>
                      {t.forms.definition.key}
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium" style={{ color: '#8f959e' }}>
                      {t.forms.definition.category}
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium" style={{ color: '#8f959e' }}>
                      {t.forms.definition.status}
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium" style={{ color: '#8f959e' }}>
                      {t.forms.definition.updatedAt}
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium" style={{ color: '#8f959e' }}>
                      {t.forms.definition.actions}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {forms.map((form) => (
                    <tr 
                      key={form.id} 
                      className="border-b transition-colors cursor-pointer"
                      style={{ borderColor: '#e5e6eb' }}
                      onClick={() => router.push(`/forms/definitions/${form.id}`)}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = '#fafafa';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = '#ffffff';
                      }}
                    >
                      <td className="px-6 py-4">
                        <div className="flex items-center">
                          <div className="w-10 h-10 rounded-lg flex items-center justify-center mr-3" 
                            style={{ backgroundColor: 'rgba(51, 112, 255, 0.1)' }}>
                            <FileText className="w-5 h-5 text-blue-600" />
                          </div>
                          <div>
                            <div className="text-sm font-medium" style={{ color: '#1f2329' }}>
                              {form.name}
                            </div>
                            {form.description && (
                              <div className="text-xs mt-0.5 line-clamp-1 max-w-xs" style={{ color: '#8f959e' }}>
                                {form.description}
                              </div>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm font-mono" style={{ color: '#646a73' }}>
                          {form.key}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className="text-sm" style={{ color: '#646a73' }}>
                          {form.category || '-'}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {getStatusBadge(form.status)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className="text-sm" style={{ color: '#646a73' }}>
                          {formatDate(form.updatedAt)}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
                        <div className="flex items-center justify-end gap-1">
                          <button
                            onClick={() => router.push(`/forms/definitions/${form.id}/design`)}
                            disabled={form.status === 'ARCHIVED'}
                            className="px-3 py-1 rounded text-sm flex items-center gap-1 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            style={{
                              backgroundColor: form.status === 'ARCHIVED' ? '#f7f8fa' : '#ffffff',
                              color: form.status === 'ARCHIVED' ? '#c9cdd4' : '#3370ff',
                              border: form.status === 'ARCHIVED' ? 'none' : '1px solid #e5e6eb'
                            }}
                            onMouseEnter={(e) => {
                              if (form.status !== 'ARCHIVED') {
                                e.currentTarget.style.backgroundColor = '#f7f8fa';
                              }
                            }}
                            onMouseLeave={(e) => {
                              if (form.status !== 'ARCHIVED') {
                                e.currentTarget.style.backgroundColor = '#ffffff';
                              }
                            }}
                          >
                            <Palette className="w-4 h-4" />
                            {t.forms.definition.designForm}
                          </button>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <button 
                                className="p-1.5 rounded transition-colors"
                                style={{ backgroundColor: '#ffffff' }}
                                onMouseEnter={(e) => {
                                  e.currentTarget.style.backgroundColor = '#f7f8fa';
                                }}
                                onMouseLeave={(e) => {
                                  e.currentTarget.style.backgroundColor = '#ffffff';
                                }}
                              >
                                <MoreVertical className="w-4 h-4" style={{ color: '#646a73' }} />
                              </button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end" className="z-[100] border-gray-200 bg-white text-gray-900">
                              <DropdownMenuItem onClick={() => router.push(`/forms/definitions/${form.id}`)}>
                                <Eye className="w-4 h-4 mr-2" />
                                {t.forms.definition.viewDetail}
                              </DropdownMenuItem>
                              <DropdownMenuItem 
                                onClick={() => router.push(`/forms/definitions/${form.id}/design`)}
                                disabled={form.status === 'ARCHIVED'}
                              >
                                <Palette className="w-4 h-4 mr-2" />
                                {t.forms.definition.designForm}
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => router.push(`/forms/definitions/${form.id}/versions`)}>
                                <GitBranch className="w-4 h-4 mr-2" />
                                {t.forms.definition.versionManage}
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => toast.info(t.forms.definition.cloneFeatureComingSoon)}>
                                <Copy className="w-4 h-4 mr-2" />
                                {t.forms.definition.clone}
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                              
                              {/* Archive (Published only) */}
                              {form.status === 'PUBLISHED' && (
                                <DropdownMenuItem onClick={() => handleArchive(form)}>
                                  <Archive className="w-4 h-4 mr-2" />
                                  {t.forms.definition.archive}
                                </DropdownMenuItem>
                              )}
                              
                              {/* Delete (Draft only) */}
                              {form.status === 'DRAFT' && (
                                <DropdownMenuItem
                                  onClick={() => handleDelete(form)}
                                  className="text-red-600"
                                >
                                  <Trash2 className="w-4 h-4 mr-2" />
                                  {t.forms.definition.delete}
                                </DropdownMenuItem>
                              )}
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

          {/* 分页器 */}
          {total > limit && (
            <div className="flex items-center justify-between mt-4">
              <div className="text-sm" style={{ color: '#8f959e' }}>
                显示 {((page - 1) * limit + 1)}-{Math.min(page * limit, total)} 共 {total} 条
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setPage(page - 1)}
                  disabled={page === 1}
                  className="px-3 py-1 rounded text-sm transition-colors"
                  style={{ 
                    backgroundColor: page === 1 ? '#f7f8fa' : '#ffffff',
                    color: page === 1 ? '#c9cdd4' : '#1f2329',
                    cursor: page === 1 ? 'not-allowed' : 'pointer',
                    border: '1px solid #e5e6eb'
                  }}
                  onMouseEnter={(e) => {
                    if (page !== 1) {
                      e.currentTarget.style.backgroundColor = '#f7f8fa';
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (page !== 1) {
                      e.currentTarget.style.backgroundColor = '#ffffff';
                    }
                  }}
                >
                  {t.forms.common.previousPage}
                </button>
                
                <span className="text-sm" style={{ color: '#646a73' }}>
                  {page} / {Math.ceil(total / limit)}
                </span>
                
                <button
                  onClick={() => setPage(page + 1)}
                  disabled={page >= Math.ceil(total / limit)}
                  className="px-3 py-1 rounded text-sm transition-colors"
                  style={{ 
                    backgroundColor: page >= Math.ceil(total / limit) ? '#f7f8fa' : '#ffffff',
                    color: page >= Math.ceil(total / limit) ? '#c9cdd4' : '#1f2329',
                    cursor: page >= Math.ceil(total / limit) ? 'not-allowed' : 'pointer',
                    border: '1px solid #e5e6eb'
                  }}
                  onMouseEnter={(e) => {
                    if (page < Math.ceil(total / limit)) {
                      e.currentTarget.style.backgroundColor = '#f7f8fa';
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (page < Math.ceil(total / limit)) {
                      e.currentTarget.style.backgroundColor = '#ffffff';
                    }
                  }}
                >
                  {t.forms.common.nextPage}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
