import React, { useState, useEffect } from 'react';
import { publicTemplateClient } from '@/client/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/client/home/components/ui/card';
import { Button } from '@/client/home/components/ui/button';
import { Badge } from '@/client/home/components/ui/badge';
import { Loader2, Download, Eye, AlertCircle } from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/client/home/hooks/AuthProvider';
import { useNavigate } from 'react-router-dom';

interface FilePreviewProps {
  templateId: number;
  onClose?: () => void;
}

const FilePreview: React.FC<FilePreviewProps> = ({ templateId, onClose }) => {
  const [template, setTemplate] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const { user } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    fetchTemplate();
  }, [templateId]);

  const fetchTemplate = async () => {
    try {
      setLoading(true);
      const response = await publicTemplateClient[':id'].preview.$get({
        param: { id: templateId.toString() }
      });
      
      if (response.ok) {
        const data = await response.json();
        setTemplate(data.template);
        setPreviewUrl(data.previewUrl);
      } else {
        toast.error('获取模板信息失败');
      }
    } catch (error) {
      console.error('Failed to fetch template:', error);
      toast.error('获取模板信息失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = async () => {
    if (!user) {
      toast.error('请先登录');
      navigate('/login');
      return;
    }

    if (!template.isFree && !user.membership) {
      toast.error('需要购买会员才能下载');
      navigate('/pricing');
      return;
    }

    try {
      const response = await publicTemplateClient[':id'].download.$post({
        param: { id: templateId.toString() }
      });
      
      if (response.ok) {
        const data = await response.json();
        window.open(data.downloadUrl, '_blank');
        toast.success('下载已开始');
      } else if (response.status === 403) {
        toast.error('需要购买会员才能下载');
        navigate('/pricing');
      } else {
        toast.error('下载失败');
      }
    } catch (error) {
      console.error('Failed to download template:', error);
      toast.error('下载失败');
    }
  };

  const getFileIcon = (fileType: string) => {
    switch (fileType) {
      case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
        return '📝';
      case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
        return '📊';
      case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
        return '📊';
      case 'application/pdf':
        return '📄';
      default:
        return '📁';
    }
  };

  const renderPreview = () => {
    if (!previewUrl) {
      return (
        <div className="flex flex-col items-center justify-center h-96 text-gray-500">
          <AlertCircle className="w-16 h-16 mb-4" />
          <p>无法预览此文件类型</p>
          <Button onClick={handleDownload} className="mt-4">
            <Download className="w-4 h-4 mr-2" />
            直接下载
          </Button>
        </div>
      );
    }

    // 检查是否为Office文档支持的预览格式
    const isOfficeDocument = previewUrl.includes('.doc') || 
                           previewUrl.includes('.docx') || 
                           previewUrl.includes('.xls') || 
                           previewUrl.includes('.xlsx') || 
                           previewUrl.includes('.ppt') || 
                           previewUrl.includes('.pptx');

    if (isOfficeDocument) {
      return (
        <iframe
          src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(previewUrl)}`}
          width="100%"
          height="600px"
          frameBorder="0"
          title="文档预览"
        />
      );
    }

    // PDF文件预览
    if (previewUrl.includes('.pdf')) {
      return (
        <iframe
          src={previewUrl}
          width="100%"
          height="600px"
          frameBorder="0"
          title="PDF预览"
        />
      );
    }

    // 图片文件预览
    if (previewUrl.match(/\.(jpg|jpeg|png|gif|webp)$/i)) {
      return (
        <img
          src={previewUrl}
          alt={template?.title}
          className="max-w-full h-auto mx-auto"
          style={{ maxHeight: '600px' }}
        />
      );
    }

    // 默认预览
    return (
      <iframe
        src={previewUrl}
        width="100%"
        height="600px"
        frameBorder="0"
        title="文件预览"
      />
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="w-8 h-8 animate-spin" />
      </div>
    );
  }

  if (!template) {
    return (
      <div className="flex flex-col items-center justify-center h-96 text-gray-500">
        <AlertCircle className="w-16 h-16 mb-4" />
        <p>模板不存在</p>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8 px-4 max-w-6xl">
      <Card>
        <CardHeader>
          <div className="flex justify-between items-start">
            <div>
              <CardTitle className="text-2xl mb-2">{template.title}</CardTitle>
              <p className="text-gray-600">{template.description}</p>
            </div>
            <div className="flex gap-2">
              <Badge variant={template.isFree ? "default" : "secondary"}>
                {template.isFree ? "免费" : "会员专享"}
              </Badge>
              <Badge variant="outline">{template.category}</Badge>
            </div>
          </div>
        </CardHeader>
        
        <CardContent>
          <div className="mb-4 flex justify-between items-center">
            <div className="text-sm text-gray-600">
              <span>下载次数: {template.downloadCount}</span>
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                onClick={onClose}
              >
                关闭
              </Button>
              <Button
                onClick={handleDownload}
                disabled={!template.isFree && !user?.membership}
              >
                <Download className="w-4 h-4 mr-2" />
                {template.isFree ? '免费下载' : '会员下载'}
              </Button>
            </div>
          </div>
          
          <div className="border rounded-lg overflow-hidden">
            {renderPreview()}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default FilePreview;