import { useEffect, useState } from 'react';
import { Card, CardContent } from '@/client/components/ui/card';
import { Alert, AlertDescription } from '@/client/components/ui/alert';
import { Button } from '@/client/components/ui/button';
import { Loader2, AlertCircle, FileText } from 'lucide-react';
import mammoth from 'mammoth';

interface WordViewerProps {
  file: File | null;
  fileUrl?: string;
}

export default function WordViewer({ file, fileUrl }: WordViewerProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [previewHtml, setPreviewHtml] = useState<string>('');
  const [wordContent, setWordContent] = useState<string>('');
  const [documentInfo, setDocumentInfo] = useState<any>(null);

  const readWordFile = async (file: File) => {
    setIsLoading(true);
    setError(null);
    
    try {
      const arrayBuffer = await file.arrayBuffer();
      
      // 使用 mammoth.js 解析 DOCX 文件
      const result = await mammoth.convertToHtml(
        { arrayBuffer },
        {
          styleMap: [
            "p[style-name='Heading 1'] => h1:fresh",
            "p[style-name='Heading 2'] => h2:fresh",
            "p[style-name='Heading 3'] => h3:fresh",
            "p[style-name='Heading 4'] => h4:fresh",
            "p[style-name='Heading 5'] => h5:fresh",
            "p[style-name='Heading 6'] => h6:fresh",
            "p => p:fresh"
          ],
          includeDefaultStyleMap: true
        }
      );
      
      // 获取文档信息
      const info = await mammoth.extractRawText({ arrayBuffer });
      
      setPreviewHtml(result.value);
      setWordContent(info.value);
      
      // 提取文档元数据
      setDocumentInfo({
        name: file.name,
        size: file.size,
        type: file.type,
        lastModified: file.lastModifiedDate,
        wordCount: info.value.split(/\s+/).filter(word => word.length > 0).length,
        characterCount: info.value.length
      });
      
    } catch (err) {
      console.error('Word parsing error:', err);
      
      if (file.type === 'application/msword') {
        setError('不支持旧的 .doc 格式，请使用 .docx 格式的Word文档');
      } else if (file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        setError('不支持的文件格式，请选择 .docx 格式的Word文档');
      } else {
        setError('文件解析失败，请检查文件是否损坏');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const loadFromUrl = async (url: string) => {
    setIsLoading(true);
    setError(null);
    
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error('无法加载文件');
      
      const arrayBuffer = await response.arrayBuffer();
      
      const result = await mammoth.convertToHtml(
        { arrayBuffer },
        {
          styleMap: [
            "p[style-name='Heading 1'] => h1:fresh",
            "p[style-name='Heading 2'] => h2:fresh",
            "p[style-name='Heading 3'] => h3:fresh",
            "p[style-name='Heading 4'] => h4:fresh",
            "p[style-name='Heading 5'] => h5:fresh",
            "p[style-name='Heading 6'] => h6:fresh",
            "p => p:fresh"
          ],
          includeDefaultStyleMap: true
        }
      );
      
      const info = await mammoth.extractRawText({ arrayBuffer });
      
      setPreviewHtml(result.value);
      setWordContent(info.value);
      
    } catch (err) {
      setError('文件加载失败，请检查网络连接和文件权限');
      console.error('URL loading error:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  useEffect(() => {
    if (file) {
      readWordFile(file);
    } else if (fileUrl) {
      loadFromUrl(fileUrl);
    }
  }, [file, fileUrl]);

  if (!file && !fileUrl) {
    return (
      <Card>
        <CardContent className="pt-6">
          <div className="text-center py-12">
            <FileText className="h-16 w-16 mx-auto mb-4 text-muted-foreground" />
            <p className="text-muted-foreground">请选择Word文件进行预览</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (isLoading) {
    return (
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <span className="ml-2">正在解析文档...</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card>
        <CardContent className="pt-6">
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
          <div className="mt-4">
            <Button variant="outline" onClick={() => setError(null)}>
              重试
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardContent className="pt-6">
        <div className="word-viewer-container">
          <style jsx>{`
            .word-viewer-container {
              max-width: 100%;
              overflow-x: auto;
            }
            .word-content {
              font-family: 'Times New Roman', serif;
              line-height: 1.6;
              color: #1f2937;
            }
            .word-content h1 {
              font-size: 2rem;
              font-weight: bold;
              margin: 1.5rem 0 1rem 0;
              color: #111827;
            }
            .word-content h2 {
              font-size: 1.75rem;
              font-weight: bold;
              margin: 1.5rem 0 0.75rem 0;
              color: #111827;
            }
            .word-content h3 {
              font-size: 1.5rem;
              font-weight: bold;
              margin: 1.25rem 0 0.75rem 0;
              color: #111827;
            }
            .word-content h4 {
              font-size: 1.25rem;
              font-weight: bold;
              margin: 1rem 0 0.5rem 0;
              color: #111827;
            }
            .word-content h5 {
              font-size: 1.125rem;
              font-weight: bold;
              margin: 1rem 0 0.5rem 0;
              color: #111827;
            }
            .word-content h6 {
              font-size: 1rem;
              font-weight: bold;
              margin: 0.75rem 0 0.5rem 0;
              color: #111827;
            }
            .word-content p {
              margin-bottom: 0.75rem;
            }
            .word-content ul, .word-content ol {
              margin: 0.5rem 0 0.5rem 2rem;
            }
            .word-content li {
              margin-bottom: 0.25rem;
            }
            .word-content table {
              width: 100%;
              border-collapse: collapse;
              margin: 1rem 0;
            }
            .word-content th, .word-content td {
              border: 1px solid #d1d5db;
              padding: 0.5rem;
              text-align: left;
            }
            .word-content th {
              background-color: #f9fafb;
              font-weight: bold;
            }
            .document-info {
              background-color: #f9fafb;
              border: 1px solid #e5e7eb;
              border-radius: 0.5rem;
              padding: 1rem;
              margin-bottom: 1rem;
            }
            .document-info h4 {
              font-weight: bold;
              margin-bottom: 0.5rem;
            }
            .document-info p {
              margin: 0.25rem 0;
              font-size: 0.875rem;
            }
          `}</style>
          
          {documentInfo && (
            <div className="document-info">
              <h4>文档信息</h4>
              <p><strong>文件名:</strong> {documentInfo.name}</p>
              <p><strong>大小:</strong> {formatFileSize(documentInfo.size)}</p>
              <p><strong>类型:</strong> {documentInfo.type}</p>
              <p><strong>字数:</strong> {documentInfo.wordCount}</p>
              <p><strong>字符数:</strong> {documentInfo.characterCount}</p>
              {documentInfo.lastModified && (
                <p><strong>修改时间:</strong> {documentInfo.lastModified.toLocaleString()}</p>
              )}
            </div>
          )}
          
          <div 
            className="word-content"
            dangerouslySetInnerHTML={{ __html: previewHtml }} 
          />
          
          {wordContent && (
            <details className="mt-4">
              <summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
                查看纯文本内容
              </summary>
              <div className="mt-2 p-4 bg-muted rounded-lg">
                <pre className="text-sm whitespace-pre-wrap font-mono">{wordContent}</pre>
              </div>
            </details>
          )}
        </div>
      </CardContent>
    </Card>
  );
}