import { useState, useEffect } from 'react';
import { Routes, Route, useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import './App.css';

// 短链接跳转组件
function RedirectPage() {
  const { code } = useParams();
  const navigate = useNavigate();
  const [error, setError] = useState('');

  useEffect(() => {
    const redirect = async () => {
      try {
        // 调用后端API获取目标URL
        const response = await axios.get(`/api/redirect/${code}`);
        if (response.data.success) {
          // 直接跳转到目标URL，使用replace替换当前历史记录
          window.location.replace(response.data.target_url);
        }
      } catch (err) {
        setError(err.response?.data?.message || '短链接不存在');
        // 3秒后返回首页
        setTimeout(() => {
          navigate('/');
        }, 3000);
      }
    };
    
    if (code && code.length === 4) {
      redirect();
    } else {
      navigate('/');
    }
  }, [code, navigate]);

  if (error) {
    return (
      <div className="app">
        <div className="container">
          <div className="error-page">
            <div className="error-icon">❌</div>
            <h2 className="error-title">{error}</h2>
            <p className="error-text">3秒后自动返回首页...</p>
          </div>
        </div>
      </div>
    );
  }

  // 跳转中不显示任何内容
  return null;
}

// 主页面组件
function HomePage() {
  const [code, setCode] = useState('');
  const [targetUrl, setTargetUrl] = useState('');
  const [message, setMessage] = useState('');
  const [messageType, setMessageType] = useState(''); // success, error, info
  const [shortUrl, setShortUrl] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [expireOption, setExpireOption] = useState('never');
  const [backgroundImage, setBackgroundImage] = useState('');

  // 背景图片列表
  const backgroundImages = [
    '/background/image1.png',
    '/background/image2.png',
    '/background/image3.png',
    '/background/image4.png',
    '/background/image5.png',
    '/background/image6.png',
    '/background/image7.png',
    '/background/image8.png',
  ];

  // 随机选择背景图片（确保与上一张不同）
  useEffect(() => {
    const lastBackground = sessionStorage.getItem('lastBackground');
    let randomIndex;
    let selectedImage;
    
    do {
      randomIndex = Math.floor(Math.random() * backgroundImages.length);
      selectedImage = backgroundImages[randomIndex];
    } while (selectedImage === lastBackground && backgroundImages.length > 1);
    
    setBackgroundImage(selectedImage);
    sessionStorage.setItem('lastBackground', selectedImage);
  }, []);

  // 过期时间选项
  const expireOptions = [
    { value: '10min', label: '10分钟' },
    { value: '1hour', label: '1小时' },
    { value: '1day', label: '1天' },
    { value: '3days', label: '3天' },
    { value: '1month', label: '1个月' },
    { value: '1year', label: '1年' },
    { value: 'never', label: '永久' }
  ];

  // 显示消息
  const showMessage = (text, type = 'info') => {
    setMessage(text);
    setMessageType(type);
    setTimeout(() => {
      setMessage('');
      setMessageType('');
    }, 5000);
  };

  // 检查链接是否可用
  const checkCode = async (codeToCheck) => {
    if (codeToCheck.length !== 4) return;
    try {
      const response = await axios.get(`/api/check/${codeToCheck}`);
      if (response.data.exists) {
        showMessage('该链接代码已被使用', 'error');
      }
    } catch (error) {
      console.error('检查失败:', error);
    }
  };

  // 生成随机链接
  const generateRandomCode = async () => {
    setIsLoading(true);
    try {
      const response = await axios.get('/api/generate');
      if (response.data.success) {
        setCode(response.data.code);
      } else {
        showMessage('生成失败，请重试', 'error');
      }
    } catch (error) {
      showMessage('生成失败，请重试', 'error');
    } finally {
      setIsLoading(false);
    }
  };

  // 创建短链接
  const createShortLink = async (e) => {
    e.preventDefault();
    
    if (!code || code.length !== 4) {
      showMessage('请输入4位链接代码', 'error');
      return;
    }
    
    if (!targetUrl) {
      showMessage('请输入目标地址', 'error');
      return;
    }

    setIsLoading(true);
    try {
      const response = await axios.post('/api/create', {
        code: code,
        target_url: targetUrl,
        expire_option: expireOption
      });
      
      if (response.data.success) {
        setShortUrl(`${window.location.origin}/${code}`);
      }
    } catch (error) {
      if (error.response?.status === 409) {
        showMessage('该链接代码已被使用，请选择其他代码或使用随机生成', 'error');
      } else {
        showMessage(error.response?.data?.message || '创建失败，请重试', 'error');
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 重置表单
  const resetForm = () => {
    setCode('');
    setTargetUrl('');
    setShortUrl('');
    setMessage('');
    setMessageType('');
    setExpireOption('never');
  };

  // 复制短链接
  const copyToClipboard = () => {
    // 兼容性更好的复制方法
    if (navigator.clipboard && window.isSecureContext) {
      // 使用现代 Clipboard API
      navigator.clipboard.writeText(shortUrl)
        .then(() => {
        })
        .catch(() => {
          // 降级方案
          fallbackCopy();
        });
    } else {
      // 使用传统方法
      fallbackCopy();
    }
  };

  // 降级复制方案
  const fallbackCopy = () => {
    try {
      const textArea = document.createElement('textarea');
      textArea.value = shortUrl;
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      
      const successful = document.execCommand('copy');
      document.body.removeChild(textArea);
      
      if (successful) {
        showMessage('链接已复制到剪贴板', 'success');
      } else {
        showMessage('复制失败，请手动复制', 'error');
      }
    } catch (err) {
      showMessage('复制失败，请手动复制', 'error');
    }
  };

  return (
    <div className="app" style={{ backgroundImage: `url(${backgroundImage})` }}>
      <div className="container">
        <header className="header">
          <img src="/logo.png" alt="萌芽短链" className="logo" />
          <h1 className="title">萌芽短链</h1>
          <p className="subtitle">简单、快速的短链接生成工具</p>
        </header>

        {message && (
          <div className={`message message-${messageType}`}>
            {message}
          </div>
        )}

        {!shortUrl ? (
          <form onSubmit={createShortLink} className="form">
            <div className="form-group">
              <label className="label">
                短链接代码
                <span className="label-hint">（4位字母或数字，区分大小写）</span>
              </label>
              <div className="input-group">
                <span className="input-prefix">{window.location.host}/</span>
                <input
                  type="text"
                  className="input code-input"
                  value={code}
                  onChange={(e) => {
                    const value = e.target.value.slice(0, 4);
                    setCode(value);
                  }}
                  onBlur={() => code.length === 4 && checkCode(code)}
                  placeholder="Aaa3"
                  maxLength={4}
                  required
                />
              </div>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={generateRandomCode}
                disabled={isLoading}
              >
                🎲 随机生成
              </button>
            </div>

            <div className="form-group">
              <label className="label">目标地址</label>
              <input
                type="url"
                className="input"
                value={targetUrl}
                onChange={(e) => setTargetUrl(e.target.value)}
                placeholder="https://example.com"
                required
              />
            </div>

            <div className="form-group">
              <label className="label">过期时间</label>
              <select
                className="input select"
                value={expireOption}
                onChange={(e) => setExpireOption(e.target.value)}
              >
                {expireOptions.map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            <button
              type="submit"
              className="btn btn-primary"
              disabled={isLoading}
            >
              {isLoading ? '创建中...' : '创建短链接'}
            </button>
          </form>
        ) : (
          <div className="result">
            <div className="success-icon">✅</div>
            <h2 className="result-title">短链接创建成功！</h2>
            <div className="result-box">
              <div className="result-url">{shortUrl}</div>
              <button className="btn btn-copy" onClick={copyToClipboard}>
                📋 复制链接
              </button>
            </div>
            <div className="result-info">
              <p><strong>目标地址：</strong>{targetUrl}</p>
            </div>
            <button className="btn btn-secondary" onClick={resetForm}>
              ➕ 创建新的短链接
            </button>
          </div>
        )}

        <footer className="footer">
          <p>© 2025 萌芽短链 - 蜀ICP备2025151694号</p>
        </footer>
      </div>
    </div>
  );
}

// 主应用组件
function App() {
  return (
    <Routes>
      <Route path="/" element={<HomePage />} />
      <Route path="/:code" element={<RedirectPage />} />
    </Routes>
  );
}

export default App;

