/**
 * Feedback Button Component
 * Provides a user-friendly interface for reporting problems
 * 
 * Features:
 * - Report problem button
 * - Modal dialog for user description
 * - Automatic error log attachment
 * - Screenshot capture
 * - Recent actions history
 * - Error context collection
 */

'use client';

import React, { useState } from 'react';
import { MessageSquare, Send, X, AlertCircle, Copy } from 'lucide-react';
import { errorReporter, type UserAction } from '@/lib/utils/errorReporter';
import { errorRecovery } from '@/lib/utils/errorRecovery';

/**
 * Feedback form data
 */
interface FeedbackData {
  description: string;
  includeScreenshot: boolean;
  includeErrorLogs: boolean;
  includeUserActions: boolean;
  email?: string;
}

/**
 * Feedback Button Props
 */
interface FeedbackButtonProps {
  className?: string;
  variant?: 'button' | 'icon' | 'text';
  size?: 'sm' | 'md' | 'lg';
  position?: 'fixed' | 'relative';
  canvasId?: string;
  projectId?: string;
}

/**
 * Feedback Button Component
 */
export function FeedbackButton({
  className = '',
  variant = 'button',
  size = 'md',
  position = 'fixed',
  canvasId,
  projectId,
}: FeedbackButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [trackingId, setTrackingId] = useState<string | null>(null);
  
  const [formData, setFormData] = useState<FeedbackData>({
    description: '',
    includeScreenshot: true,
    includeErrorLogs: true,
    includeUserActions: true,
    email: '',
  });

  /**
   * Handle form submission
   */
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.description.trim()) {
      setSubmitError('请输入问题描述');
      return;
    }

    setIsSubmitting(true);
    setSubmitError(null);

    try {
      // Collect error logs if requested
      let errorLogs: any[] = [];
      if (formData.includeErrorLogs) {
        const recoveryData = errorRecovery.getRecoveryInfo();
        if (recoveryData) {
          errorLogs.push({
            type: 'recovery',
            data: recoveryData,
          });
        }
      }

      // Collect user actions if requested
      let userActions: UserAction[] = [];
      if (formData.includeUserActions) {
        userActions = errorReporter.getRecentActions(20);
      }

      // Capture screenshot if requested
      let screenshot: string | undefined;
      if (formData.includeScreenshot) {
        try {
          // Dynamically import html2canvas to capture screenshot
          const html2canvas = (await import('html2canvas')).default;
          const canvas = await html2canvas(document.body, {
            scale: 0.5, // Reduce size for smaller file
            logging: false,
            useCORS: true, // Allow cross-origin images
            allowTaint: false,
            backgroundColor: '#ffffff',
          });
          screenshot = canvas.toDataURL('image/jpeg', 0.7); // Compress to JPEG
        } catch (error) {
          console.warn('[FeedbackButton] Failed to capture screenshot:', error);
          // Continue without screenshot - not critical
        }
      }

      // Create a feedback error to report
      const feedbackError = new Error(`User Feedback: ${formData.description}`);
      feedbackError.name = 'UserFeedback';

      // Report the feedback as an error with metadata
      const errorId = await errorReporter.report(
        feedbackError,
        {
          canvasId,
          projectId,
          operation: 'user-feedback',
          feedbackType: 'problem-report',
          userDescription: formData.description,
          userEmail: formData.email || undefined,
          errorLogs: formData.includeErrorLogs ? errorLogs : undefined,
          userActions: formData.includeUserActions ? userActions : undefined,
          screenshot: screenshot,
          includeScreenshot: formData.includeScreenshot,
          timestamp: Date.now(),
        }
      );

      if (errorId) {
        setSubmitSuccess(true);
        setTrackingId(errorId);
        
        // Reset form after 2 seconds
        setTimeout(() => {
          setIsOpen(false);
          setSubmitSuccess(false);
          setTrackingId(null);
          setFormData({
            description: '',
            includeScreenshot: true,
            includeErrorLogs: true,
            includeUserActions: true,
            email: '',
          });
        }, 2000);
      } else {
        setSubmitError('无法提交反馈，请检查是否已启用错误报告');
      }
    } catch (error) {
      console.error('[FeedbackButton] Failed to submit feedback:', error);
      setSubmitError('提交失败，请稍后重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  /**
   * Handle modal close
   */
  const handleClose = () => {
    if (!isSubmitting) {
      setIsOpen(false);
      setSubmitError(null);
      setSubmitSuccess(false);
      setTrackingId(null);
    }
  };
  
  /**
   * Copy tracking ID to clipboard
   */
  const handleCopyTrackingId = async () => {
    if (trackingId) {
      try {
        await navigator.clipboard.writeText(trackingId);
        // Could show a toast notification here
      } catch (error) {
        console.error('[FeedbackButton] Failed to copy tracking ID:', error);
      }
    }
  };

  /**
   * Render button based on variant
   */
  const renderButton = () => {
    const baseClasses = 'inline-flex items-center justify-center gap-2 transition-colors';
    const sizeClasses = {
      sm: 'px-2 py-1 text-xs',
      md: 'px-3 py-2 text-sm',
      lg: 'px-4 py-3 text-base',
    };
    const variantClasses = {
      button: 'bg-blue-600 hover:bg-blue-700 text-white rounded-lg shadow-sm',
      icon: 'bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-full p-2',
      text: 'text-blue-600 hover:text-blue-700 hover:underline',
    };

    const buttonClasses = `${baseClasses} ${sizeClasses[size]} ${variantClasses[variant]} ${className}`;

    return (
      <button
        onClick={() => setIsOpen(true)}
        className={buttonClasses}
        title="报告问题"
        aria-label="报告问题"
      >
        <MessageSquare className="w-4 h-4" />
        {variant === 'button' && <span>报告问题</span>}
      </button>
    );
  };

  return (
    <>
      {/* Feedback Button */}
      <div className={position === 'fixed' ? 'fixed bottom-4 right-4 z-50' : ''}>
        {renderButton()}
      </div>

      {/* Feedback Modal */}
      {isOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-hidden flex flex-col">
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b">
              <div className="flex items-center gap-2">
                <MessageSquare className="w-5 h-5 text-blue-600" />
                <h2 className="text-lg font-semibold">报告问题</h2>
              </div>
              <button
                onClick={handleClose}
                disabled={isSubmitting}
                className="p-1 hover:bg-gray-100 rounded transition-colors disabled:opacity-50"
                aria-label="关闭"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-4">
              {submitSuccess ? (
                // Success Message
                <div className="flex flex-col items-center justify-center py-8 text-center">
                  <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
                    <svg className="w-8 h-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                  </div>
                  <h3 className="text-xl font-semibold text-gray-900 mb-2">反馈已提交</h3>
                  <p className="text-gray-600 mb-4">感谢您的反馈，我们会尽快处理</p>
                  
                  {/* Tracking ID */}
                  {trackingId && (
                    <div className="w-full max-w-md bg-gray-50 border border-gray-200 rounded-lg p-4 mt-2">
                      <p className="text-sm font-medium text-gray-700 mb-2">反馈追踪 ID</p>
                      <div className="flex items-center gap-2">
                        <code className="flex-1 px-3 py-2 bg-white border border-gray-300 rounded text-sm font-mono text-gray-800 overflow-x-auto">
                          {trackingId}
                        </code>
                        <button
                          onClick={handleCopyTrackingId}
                          className="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors text-sm whitespace-nowrap flex items-center gap-1"
                          title="复制追踪 ID"
                        >
                          <Copy className="w-4 h-4" />
                          <span>复制</span>
                        </button>
                      </div>
                      <p className="text-xs text-gray-500 mt-2">
                        请保存此 ID 以便追踪反馈处理进度
                      </p>
                    </div>
                  )}
                </div>
              ) : (
                // Feedback Form
                <form onSubmit={handleSubmit} className="space-y-4">
                  {/* Description */}
                  <div>
                    <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">
                      问题描述 <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      id="description"
                      value={formData.description}
                      onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                      placeholder="请详细描述您遇到的问题..."
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                      rows={6}
                      required
                      disabled={isSubmitting}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      请尽可能详细地描述问题，包括您执行的操作和期望的结果
                    </p>
                  </div>

                  {/* Email (Optional) */}
                  <div>
                    <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
                      邮箱地址（可选）
                    </label>
                    <input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                      placeholder="your@email.com"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      disabled={isSubmitting}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      如果您希望我们回复，请留下邮箱地址
                    </p>
                  </div>

                  {/* Options */}
                  <div className="space-y-2">
                    <p className="text-sm font-medium text-gray-700">附加信息</p>
                    
                    <label className="flex items-start gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.includeScreenshot}
                        onChange={(e) => setFormData({ ...formData, includeScreenshot: e.target.checked })}
                        className="mt-1"
                        disabled={isSubmitting}
                      />
                      <div>
                        <span className="text-sm text-gray-700">包含屏幕截图</span>
                        <p className="text-xs text-gray-500">自动捕获当前页面截图</p>
                      </div>
                    </label>

                    <label className="flex items-start gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.includeErrorLogs}
                        onChange={(e) => setFormData({ ...formData, includeErrorLogs: e.target.checked })}
                        className="mt-1"
                        disabled={isSubmitting}
                      />
                      <div>
                        <span className="text-sm text-gray-700">包含错误日志</span>
                        <p className="text-xs text-gray-500">包含最近的错误信息（如果有）</p>
                      </div>
                    </label>

                    <label className="flex items-start gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.includeUserActions}
                        onChange={(e) => setFormData({ ...formData, includeUserActions: e.target.checked })}
                        className="mt-1"
                        disabled={isSubmitting}
                      />
                      <div>
                        <span className="text-sm text-gray-700">包含操作历史</span>
                        <p className="text-xs text-gray-500">包含最近的用户操作记录</p>
                      </div>
                    </label>
                  </div>

                  {/* Privacy Notice */}
                  <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                    <div className="flex gap-2">
                      <AlertCircle className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                      <div className="text-xs text-blue-800">
                        <p className="font-medium mb-1">隐私说明</p>
                        <p>
                          您的反馈将被发送到我们的服务器用于问题诊断。
                          我们不会收集任何个人敏感信息。
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Error Message */}
                  {submitError && (
                    <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                      <div className="flex gap-2">
                        <AlertCircle className="w-4 h-4 text-red-600 flex-shrink-0 mt-0.5" />
                        <p className="text-sm text-red-800">{submitError}</p>
                      </div>
                    </div>
                  )}

                  {/* Actions */}
                  <div className="flex gap-3 pt-2">
                    <button
                      type="button"
                      onClick={handleClose}
                      disabled={isSubmitting}
                      className="flex-1 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50"
                    >
                      取消
                    </button>
                    <button
                      type="submit"
                      disabled={isSubmitting || !formData.description.trim()}
                      className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                    >
                      {isSubmitting ? (
                        <>
                          <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                          <span>提交中...</span>
                        </>
                      ) : (
                        <>
                          <Send className="w-4 h-4" />
                          <span>提交反馈</span>
                        </>
                      )}
                    </button>
                  </div>
                </form>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

/**
 * Export default
 */
export default FeedbackButton;
