'use client';

import { useEffect, useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth';
import {
  ClipboardCheck,
  Eye,
  Check,
  X,
  Clock,
  FileText,
  GitBranch,
  Send,
  Layers,
  RefreshCw,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { toast } from '@/lib/toast';
import { useTranslation } from '@/hooks/useTranslation';
import {
  getPendingSnapshots,
  reviewSnapshot,
  publishSnapshot,
  getSnapshot,
  type ReleaseSnapshot,
  type PendingReviewItem,
} from '@/services/api/form-management';
import { ApiClientError } from '@/lib/api-client';
import { FormRenderer } from '@features/forms/components/FormRenderer';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import dynamic from 'next/dynamic';

// 动态导入飞书风格流程预览（时间线样式）
const LarkProcessPreview = dynamic(
  () => import('@features/approval/designer/LarkProcessPreview'),
  { 
    ssr: false,
    loading: () => (
      <div className="h-[200px] flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
      </div>
    ),
  }
);

export default function VersionReviewPage() {
  const router = useRouter();
  const { t, locale } = useTranslation();
  const [mounted, setMounted] = useState(false);
  const [items, setItems] = useState<PendingReviewItem[]>([]);
  const [filteredItems, setFilteredItems] = useState<PendingReviewItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [onlyMine, setOnlyMine] = useState(false);
  const [currentUserId, setCurrentUserId] = useState<string>('');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const limit = 20;

  // Fix hydration mismatch for Radix UI components
  useEffect(() => {
    setMounted(true);
  }, []);

  // Preview dialog
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<ReleaseSnapshot | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [previewFormData, setPreviewFormData] = useState<Record<string, unknown>>({});

  // Review dialog
  const [reviewOpen, setReviewOpen] = useState(false);
  const [reviewAction, setReviewAction] = useState<'APPROVE' | 'REJECT'>('APPROVE');
  const [reviewComment, setReviewComment] = useState('');
  const [reviewingItem, setReviewingItem] = useState<PendingReviewItem | null>(null);
  const [reviewSubmitting, setReviewSubmitting] = useState(false);

  // Publish dialog
  const [publishOpen, setPublishOpen] = useState(false);
  const [publishNote, setPublishNote] = useState('');
  const [publishingItem, setPublishingItem] = useState<PendingReviewItem | null>(null);
  const [publishing, setPublishing] = useState(false);

  // Stable submitter object for preview (avoid re-creating on each render)
  const previewSubmitter = useMemo(() => ({
    id: 'preview-user',
    name: t.forms.review.previewUser,
    departments: [
      { id: 'dept-1', name: t.forms.review.rdDept },
      { id: 'dept-2', name: t.forms.review.productDept },
    ],
  }), [locale]);

  // Preview form submit handler
  const handlePreviewSubmit = useCallback((data: Record<string, unknown>) => {
    console.log('Preview submit:', data);
    toast.success(t.forms.review.previewDataLogged);
  }, [t]);

  // 获取当前用户信息（从 AuthContext）
  const { user: currentUser } = useAuth();
  
  useEffect(() => {
    if (currentUser) {
      setCurrentUserId(currentUser.id);
    }
  }, [currentUser]);

  useEffect(() => {
    loadItems();
  }, [page]);

  // 应用筛选器
  useEffect(() => {
    let filtered = items;
    
    // 筛选"仅我的"
    if (onlyMine && currentUserId) {
      filtered = filtered.filter(item => item.submittedById === currentUserId);
    }
    
    setFilteredItems(filtered);
    setTotal(filtered.length);
  }, [items, onlyMine, currentUserId]);

  const loadItems = async () => {
    try {
      setLoading(true);
      const response = await getPendingSnapshots({
        page,
        limit,
      });
      setItems(response.items || []);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.loadFailed}: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const handlePreview = async (item: PendingReviewItem) => {
    try {
      setPreviewLoading(true);
      setPreviewOpen(true);
      setPreviewFormData({}); // Reset form data when opening preview
      const data = await getSnapshot(item.snapshotId);
      setPreviewData(data);
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.loadFailed}: ${error.message}`);
      }
      setPreviewOpen(false);
    } finally {
      setPreviewLoading(false);
    }
  };

  const openReviewDialog = (item: PendingReviewItem, action: 'APPROVE' | 'REJECT') => {
    setReviewingItem(item);
    setReviewAction(action);
    setReviewComment('');
    setReviewOpen(true);
  };

  const handleReview = async () => {
    if (!reviewingItem) return;

    try {
      setReviewSubmitting(true);
      await reviewSnapshot(reviewingItem.snapshotId, {
        action: reviewAction,
        comment: reviewComment || undefined,
      });
      
      if (reviewAction === 'APPROVE') {
        // 审核通过 = 发布（简化流程）
        // 后端已自动设置为 PUBLISHED 和默认版本，直接提示成功
        toast.success(t.forms.review.approvedAndPublished);
        setReviewOpen(false);
        loadItems();
      } else {
        toast.success(t.forms.messages.reviewRejected);
        setReviewOpen(false);
        loadItems();
      }
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.operationFailed}: ${error.message}`);
      }
    } finally {
      setReviewSubmitting(false);
    }
  };

  const handlePublish = async () => {
    if (!publishingItem) return;

    try {
      setPublishing(true);
      await publishSnapshot(publishingItem.snapshotId, {
        releaseNote: publishNote || undefined,
      });
      toast.success(t.forms.messages.publishSuccess);
      setPublishOpen(false);
      loadItems();
    } catch (error) {
      if (error instanceof ApiClientError) {
        toast.error(`${t.forms.messages.operationFailed}: ${error.message}`);
      }
    } finally {
      setPublishing(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleString(locale, {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getStatusBadge = (status: string) => {
    // 版本状态：DRAFT → PENDING_REVIEW → PUBLISHED（审核通过=发布）
    const badges: Record<string, { label: string; bg: string; color: string }> = {
      PENDING: { 
        label: t.forms.snapshotStatus.PENDING, 
        bg: 'rgba(255, 125, 0, 0.1)', 
        color: '#ff7d00' 
      },
      PENDING_REVIEW: { 
        label: t.forms.snapshotStatus.PENDING, 
        bg: 'rgba(255, 125, 0, 0.1)', 
        color: '#ff7d00' 
      },
      PUBLISHED: { 
        label: t.forms.snapshotStatus.ACTIVE, 
        bg: 'rgba(0, 180, 42, 0.1)', 
        color: '#00b42a' 
      },
      ACTIVE: { 
        label: t.forms.snapshotStatus.ACTIVE, 
        bg: 'rgba(0, 180, 42, 0.1)', 
        color: '#00b42a' 
      },
      REJECTED: { 
        label: t.forms.review.statusRejected, 
        bg: 'rgba(245, 63, 63, 0.1)', 
        color: '#f53f3f' 
      },
    };
    const badge = badges[status] || badges.PENDING;
    return (
      <span 
        className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium"
        style={{ 
          backgroundColor: badge.bg,
          color: badge.color
        }}
      >
        {badge.label}
      </span>
    );
  };

  return (
    <div className="h-full flex flex-col" style={{ backgroundColor: '#f7f8fa' }}>
      {/* 标题栏 (Title Bar) - 固定高度 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' }}>
                <ClipboardCheck className="w-5 h-5 mr-2 text-blue-600" />
                {t.forms.review.title}
              </h1>
              
              {/* "仅显示我的"筛选器 */}
              <label className="flex items-center gap-2 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={onlyMine}
                  onChange={(e) => setOnlyMine(e.target.checked)}
                  className="w-4 h-4 rounded focus:ring-2 focus:ring-blue-500"
                  style={{ 
                    accentColor: '#3370ff',
                    borderColor: '#e5e6eb'
                  }}
                />
                <span className="text-sm" style={{ color: '#646a73' }}>
                  {t.forms.review.showOnlyMine}
                </span>
              </label>
              
              {onlyMine && (
                <span 
                  className="text-xs px-2 py-0.5 rounded-full"
                  style={{ 
                    backgroundColor: 'rgba(51, 112, 255, 0.1)', 
                    color: '#3370ff' 
                  }}
                >
                  {t.forms.review.filteredCount.replace('{count}', String(filteredItems.length))}
                </span>
              )}
            </div>
            
            {/* 右侧：操作按钮 */}
            <div className="flex items-center gap-2">
              <button
                onClick={loadItems}
                disabled={loading}
                className="px-4 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-2"
                style={{ 
                  backgroundColor: '#f7f8fa',
                  color: '#1f2329',
                  border: 'none',
                  cursor: loading ? 'not-allowed' : 'pointer'
                }}
                onMouseEnter={(e) => {
                  if (!loading) e.currentTarget.style.backgroundColor = '#eff0f2';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = '#f7f8fa';
                }}
              >
                <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
                {t.forms.review.refresh}
              </button>
              <span 
                className="px-3 py-1 rounded-full text-sm font-medium"
                style={{ 
                  backgroundColor: 'rgba(255, 125, 0, 0.1)', 
                  color: '#ff7d00' 
                }}
              >
                {t.forms.review.pending}: {total}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* 内容区域 (Content Area) - flex-1 自动占满 */}
      <div className="flex-1 overflow-auto">
        <div className="p-6">
          {/* Pending Review List */}
          <div className="bg-white rounded-lg shadow-sm border" style={{ borderColor: '#e5e6eb' }}>
            {loading ? (
              // 加载状态
              <div className="flex items-center justify-center py-12">
                <div className="flex flex-col items-center gap-3">
                  <div className="w-8 h-8 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
                  <p className="text-sm" style={{ color: '#8f959e' }}>{t.forms.common.loading}</p>
                </div>
              </div>
            ) : filteredItems.length === 0 ? (
              // 空状态
              <div className="flex flex-col items-center justify-center py-12 gap-4">
                <div 
                  className="w-16 h-16 rounded-full flex items-center justify-center"
                  style={{ backgroundColor: '#f7f8fa' }}
                >
                  <ClipboardCheck className="w-8 h-8" style={{ color: '#c9cdd4' }} />
                </div>
                <div className="text-center">
                  <p className="text-base font-medium mb-1" style={{ color: '#646a73' }}>
                    {onlyMine 
                      ? t.forms.review.noMyPending
                      : t.forms.review.noItems
                    }
                  </p>
                  <p className="text-sm" style={{ color: '#8f959e' }}>
                    {onlyMine
                      ? t.forms.review.mySubmittedWillShowHere
                      : t.forms.review.noItemsDesc
                    }
                  </p>
                </div>
                {onlyMine && (
                  <button
                    onClick={() => setOnlyMine(false)}
                    className="px-4 py-1.5 rounded-lg text-sm font-medium transition-all"
                    style={{ 
                      backgroundColor: '#f7f8fa',
                      color: '#1f2329',
                      border: 'none'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.backgroundColor = '#eff0f2';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = '#f7f8fa';
                    }}
                  >
                    {t.forms.review.showAll}
                  </button>
                )}
              </div>
            ) : (
              <div className="divide-y" style={{ borderColor: '#e5e6eb' }}>
                {filteredItems.map((item) => {
                  const isMySubmission = currentUserId && item.submittedById === currentUserId;
                  
                  return (
                  <div
                    key={item.snapshotId}
                    className="px-6 py-4 transition-colors cursor-pointer"
                    style={{ 
                      borderLeft: isMySubmission ? '4px solid #3370ff' : 'none',
                      backgroundColor: isMySubmission ? 'rgba(51, 112, 255, 0.05)' : '#ffffff'
                    }}
                    onMouseEnter={(e) => {
                      if (!isMySubmission) {
                        e.currentTarget.style.backgroundColor = '#fafafa';
                      }
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.backgroundColor = isMySubmission ? 'rgba(51, 112, 255, 0.05)' : '#ffffff';
                    }}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3">
                          <div 
                            className="w-10 h-10 rounded-lg flex items-center justify-center"
                            style={{ 
                              backgroundColor: isMySubmission ? 'rgba(51, 112, 255, 0.15)' : 'rgba(51, 112, 255, 0.1)'
                            }}
                          >
                            <FileText className="w-5 h-5 text-blue-600" />
                          </div>
                          <div>
                            <h3 className="font-medium flex items-center gap-2" style={{ color: '#1f2329' }}>
                              {item.formDefinitionName}
                              {isMySubmission && (
                                <span 
                                  className="text-xs px-2 py-0.5 rounded-full font-normal"
                                  style={{ 
                                    backgroundColor: 'rgba(51, 112, 255, 0.1)', 
                                    color: '#3370ff' 
                                  }}
                                >
                                  {t.forms.review.mine}
                                </span>
                              )}
                            </h3>
                            <div className="flex items-center gap-4 mt-1 text-sm" style={{ color: '#8f959e' }}>
                              <span className="font-mono">{item.formDefinitionId.slice(-8)}</span>
                              <span className="flex items-center gap-1">
                                <GitBranch className="w-3 h-3" />
                                v{item.formVersion}
                              </span>
                            </div>
                          </div>
                        </div>
                        
                        <div className="mt-3 flex items-center gap-6 text-sm" style={{ color: '#646a73' }}>
                          <div className="flex items-center gap-1">
                            <Clock className="w-4 h-4" />
                            <span>{t.forms.review.submittedAt} {formatDate(item.submittedAt)}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <span>{t.forms.review.submittedBy}: {item.submittedBy}</span>
                          </div>
                          {getStatusBadge('PENDING')}
                        </div>

                        {item.comment && (
                          <div className="mt-3 p-3 rounded-lg text-sm" style={{ backgroundColor: '#f7f8fa', color: '#646a73' }}>
                            <span style={{ color: '#8f959e' }}>{t.forms.review.submissionNote}: </span>
                            {item.comment}
                          </div>
                        )}
                      </div>

                      <div className="flex items-center gap-2 ml-4">
                        {/* 预览按钮 */}
                        <button
                          onClick={() => handlePreview(item)}
                          className="px-3 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-2"
                          style={{ 
                            backgroundColor: '#f7f8fa',
                            color: '#1f2329',
                            border: 'none'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = '#eff0f2';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = '#f7f8fa';
                          }}
                        >
                          <Eye className="w-4 h-4" />
                          {t.forms.review.preview}
                        </button>
                        
                        {/* 驳回按钮 */}
                        <button
                          onClick={() => openReviewDialog(item, 'REJECT')}
                          className="px-3 py-1.5 rounded-lg text-sm font-medium transition-all flex items-center gap-2"
                          style={{ 
                            backgroundColor: '#f7f8fa',
                            color: '#f53f3f',
                            border: 'none'
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(245, 63, 63, 0.1)';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = '#f7f8fa';
                          }}
                        >
                          <X className="w-4 h-4" />
                          {t.forms.review.reject}
                        </button>
                        
                        {/* 通过按钮 */}
                        <button
                          onClick={() => openReviewDialog(item, 'APPROVE')}
                          className="px-3 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';
                          }}
                        >
                          <Check className="w-4 h-4" />
                          {t.forms.review.approve}
                        </button>
                      </div>
                    </div>
                  </div>
                );
                })}
              </div>
            )}
          </div>

          {/* 分页器 */}
          {total > limit && (
            <div className="flex items-center justify-between px-6 py-4 border-t" style={{ borderColor: '#e5e6eb' }}>
              {/* 左侧：总数信息 */}
              <div className="text-sm" style={{ color: '#8f959e' }}>
                {locale === 'zh' 
                  ? `显示 ${(page - 1) * limit + 1}-${Math.min(page * limit, total)} 项，共 ${total} 项`
                  : `Showing ${(page - 1) * limit + 1}-${Math.min(page * limit, total)} of ${total} items`
                }
              </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-all"
                  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 = '#fafafa';
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (page !== 1) {
                      e.currentTarget.style.backgroundColor = '#ffffff';
                    }
                  }}
                >
                  {t.forms.common.previousPage}
                </button>
                
                <span className="text-sm px-3" 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-all"
                  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 = '#fafafa';
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (page < Math.ceil(total / limit)) {
                      e.currentTarget.style.backgroundColor = '#ffffff';
                    }
                  }}
                >
                  {t.forms.common.nextPage}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Preview Dialog - 类似设计器的预览效果 */}
      <Dialog open={previewOpen} onOpenChange={setPreviewOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col p-0">
          <DialogHeader className="px-6 pt-6 pb-4 border-b">
            <DialogTitle>{t.forms.review.preview}</DialogTitle>
            <DialogDescription>
              {t.forms.review.previewFormAndProcess}
            </DialogDescription>
          </DialogHeader>
          
          {previewLoading ? (
            <div className="py-8 text-center text-gray-500">{t.forms.common.loading}</div>
          ) : previewData ? (
            <div className="flex-1 overflow-y-auto bg-gray-100 p-6">
              <div className="max-w-3xl mx-auto space-y-6">
                {/* 表单预览卡片 */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                  {/* 表单标题 */}
                  <h2 className="text-xl font-semibold text-gray-900 mb-6 text-center">
                    {previewData.formVersion?.versionName || t.forms.review.formPreview}
                  </h2>
                  
                  {previewData.formVersion?.schema ? (
                    <FormRenderer
                      schema={previewData.formVersion.schema as any}
                      uiSchema={(previewData.formVersion.uiSchema || {}) as any}
                      formData={previewFormData}
                      onChange={setPreviewFormData}
                      onSubmit={handlePreviewSubmit}
                      showSaveButton={false}
                      submitButtonText={t.forms.review.submitPreview}
                      locale={locale}
                      submitter={previewSubmitter}
                    />
                  ) : (
                    <div className="py-12 text-center text-gray-400">
                      <FileText className="w-12 h-12 mx-auto mb-3" />
                      <p>{t.forms.review.noFormSchema}</p>
                    </div>
                  )}
                </div>

                {/* 流程预览卡片 */}
                {previewData.processVersion?.model && previewData.processVersion.model.nodes?.length > 0 && (
                  <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                    <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                      <GitBranch className="w-5 h-5 text-blue-500" />
                      {t.forms.review.approvalProcessPreview}
                    </h3>
                    <div className="border border-gray-100 rounded-lg p-4 bg-gray-50/50">
                      <LarkProcessPreview
                        model={previewData.processVersion.model}
                        showInitiator={true}
                        initiatorName={t.forms.review.previewUser}
                        showEndNode={true}
                        compact={false}
                      />
                    </div>
                    <p className="text-xs text-gray-500 mt-3 text-center">
                      {t.forms.review.processAccordingToWorkflow}
                    </p>
                  </div>
                )}

                {/* 无流程配置提示 */}
                {(!previewData.processVersion?.model || !previewData.processVersion.model.nodes?.length) && (
                  <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 text-center">
                    <GitBranch className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                    <p className="text-sm text-gray-500">
                      {t.forms.review.noApprovalRequired}
                    </p>
                  </div>
                )}

                {/* 技术信息（可折叠） */}
                <details className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                  <summary className="px-6 py-4 cursor-pointer hover:bg-gray-50 flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Layers className="w-4 h-4" />
                    {t.forms.review.technicalDetails}
                  </summary>
                  <div className="px-6 pb-6 space-y-4 border-t">
                    {/* Snapshot Info */}
                    <div className="grid grid-cols-2 gap-4 pt-4">
                      <div>
                        <label className="text-xs text-gray-500">{t.forms.review.snapshotId}</label>
                        <p className="font-mono text-xs">{previewData.id}</p>
                      </div>
                      <div>
                        <label className="text-xs text-gray-500">{t.forms.definition.status}</label>
                        <p>{getStatusBadge(previewData.status)}</p>
                      </div>
                    </div>
                    
                    {/* Schema Preview */}
                    {previewData.formVersion && (
                      <div>
                        <label className="text-xs text-gray-500 mb-1 block">Schema</label>
                        <pre className="p-3 bg-gray-900 text-gray-100 rounded text-xs overflow-x-auto max-h-40">
                          {JSON.stringify(previewData.formVersion.schema, null, 2)}
                        </pre>
                      </div>
                    )}
                  </div>
                </details>
              </div>
            </div>
          ) : null}

          <DialogFooter className="px-6 py-4 border-t bg-white">
            <Button variant="outline" onClick={() => setPreviewOpen(false)}>
              {t.forms.common.close}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Review Dialog */}
      <Dialog open={reviewOpen} onOpenChange={setReviewOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {reviewAction === 'APPROVE' ? t.forms.review.approveTitle : t.forms.review.rejectTitle}
            </DialogTitle>
            <DialogDescription>
              {reviewAction === 'APPROVE'
                ? t.forms.review.approveDesc
                : t.forms.review.rejectDesc}
            </DialogDescription>
          </DialogHeader>

          {reviewingItem && (
            <div className="py-4">
              <div className="p-4 bg-gray-50 rounded-lg mb-4">
                <div className="font-medium">{reviewingItem.formDefinitionName}</div>
                <div className="text-sm text-gray-500 mt-1">
                  v{reviewingItem.formVersion}
                </div>
              </div>

              <div className="space-y-2">
                <Label>
                  {reviewAction === 'APPROVE' ? t.forms.review.reviewComment : t.forms.review.rejectReason}
                  {reviewAction === 'REJECT' && <span className="text-red-500"> *</span>}
                </Label>
                <Textarea
                  placeholder={t.forms.review.rejectReasonPlaceholder}
                  value={reviewComment}
                  onChange={(e) => setReviewComment(e.target.value)}
                  rows={3}
                />
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setReviewOpen(false)}>
              {t.forms.common.cancel}
            </Button>
            <Button
              onClick={handleReview}
              disabled={reviewSubmitting || (reviewAction === 'REJECT' && !reviewComment)}
              className={reviewAction === 'REJECT' ? 'bg-red-600 hover:bg-red-700' : ''}
            >
              {reviewSubmitting
                ? t.forms.common.processing
                : reviewAction === 'APPROVE'
                ? t.forms.review.confirmApprove
                : t.forms.review.confirmReject}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Publish Dialog */}
      <Dialog open={publishOpen} onOpenChange={setPublishOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Send className="w-5 h-5 text-green-600" />
              {t.forms.publish.title}
            </DialogTitle>
            <DialogDescription>
              {t.forms.publish.description}
            </DialogDescription>
          </DialogHeader>

          {publishingItem && (
            <div className="py-4">
              <div className="p-4 bg-green-50 border border-green-200 rounded-lg mb-4">
                <div className="font-medium text-green-800">{publishingItem.formDefinitionName}</div>
                <div className="text-sm text-green-600 mt-1">
                  {t.forms.publish.approved}
                </div>
              </div>

              <div className="space-y-2">
                <Label>{t.forms.publish.releaseNote}</Label>
                <Textarea
                  placeholder={t.forms.publish.releaseNotePlaceholder}
                  value={publishNote}
                  onChange={(e) => setPublishNote(e.target.value)}
                  rows={3}
                />
              </div>
            </div>
          )}

          <DialogFooter>
            <Button 
              variant="outline" 
              onClick={() => {
                setPublishOpen(false);
                loadItems();
              }}
            >
              {t.forms.publish.publishLater}
            </Button>
            <Button
              onClick={handlePublish}
              disabled={publishing}
              className="bg-green-600 hover:bg-green-700"
            >
              {publishing ? t.forms.publish.publishing : t.forms.publish.publishNow}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
