import { useState } from 'react';
import QRCode from 'qrcode';
import { createLink, type ClientBrowser, type GeoRule } from '../api';
import {
  BROWSER_OPTIONS,
  DEVICE_OPTIONS,
  buildClientRule,
} from '../clientRuleHelpers';
import { buildIpRule } from '../ipRuleHelpers';

const TTL_OPTIONS = [
  { label: '永久有效', value: '' },
  { label: '1 小时', value: '3600' },
  { label: '6 小时', value: '21600' },
  { label: '1 天', value: '86400' },
  { label: '3 天', value: '259200' },
  { label: '7 天', value: '604800' },
  { label: '30 天', value: '2592000' },
  { label: '自定义天数', value: 'custom' },
];

// Preset geo rules shown in the dropdown
const GEO_OPTIONS = [
  { label: '无限制', value: '' },
  { label: '仅允许中国大陆访问', value: 'allow_cn' },
  { label: '屏蔽中国大陆访问', value: 'block_cn' },
  { label: '仅允许中国大陆 + 港澳台', value: 'allow_cntw' },
  { label: '自定义…', value: 'custom' },
];

function buildGeoRule(preset: string, custom: string): GeoRule | null {
  switch (preset) {
    case 'allow_cn':   return { mode: 'allow', countries: ['CN'] };
    case 'block_cn':   return { mode: 'block', countries: ['CN'] };
    case 'allow_cntw': return { mode: 'allow', countries: ['CN', 'TW', 'HK', 'MO'] };
    case 'custom': {
      const raw = custom.toUpperCase().split(/[\s,]+/).filter(c => /^[A-Z]{2}$/.test(c));
      if (!raw.length) return null;
      return { mode: 'block', countries: raw };
    }
    default: return null;
  }
}

interface CreatedLink {
  code: string;
  url: string;
  target_url: string;
  /** PNG data URL; missing if 浏览器生成失败 */
  qrDataUrl?: string;
}

type CreateFormProps = { isAdmin?: boolean };

export default function CreateForm({ isAdmin = false }: CreateFormProps) {
  const [targetUrl, setTargetUrl] = useState('');
  const [customCode, setCustomCode] = useState('');
  const [ttl, setTtl] = useState('');
  const [customDays, setCustomDays] = useState('');
  const [maxClicks, setMaxClicks] = useState('');
  const [password, setPassword] = useState('');
  const [geoPreset, setGeoPreset] = useState('');
  const [geoCustomMode, setGeoCustomMode] = useState<'allow' | 'block'>('block');
  const [geoCustom, setGeoCustom] = useState('');
  const [clientDevice, setClientDevice] = useState('');
  const [clientBrowsers, setClientBrowsers] = useState<Set<ClientBrowser>>(() => new Set());
  const [ipMode, setIpMode] = useState<'' | 'allow' | 'block'>('');
  const [ipText, setIpText] = useState('');
  const [loading, setLoading] = useState(false);
  const [created, setCreated] = useState<CreatedLink | null>(null);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setCreated(null);

    const url = targetUrl.trim();
    if (!url) { setError('请输入目标 URL'); return; }

    let ttlSeconds: number | null = null;
    if (ttl === 'custom') {
      const days = parseFloat(customDays);
      if (isNaN(days) || days <= 0) { setError('请输入有效的自定义天数'); return; }
      ttlSeconds = Math.round(days * 86400);
    } else if (ttl) {
      ttlSeconds = parseInt(ttl, 10);
    }

    const maxClicksNum = maxClicks ? parseInt(maxClicks, 10) : null;
    if (maxClicks && (isNaN(maxClicksNum!) || maxClicksNum! < 1)) {
      setError('请输入有效的访问次数限制'); return;
    }

    let geoRule: GeoRule | null = buildGeoRule(geoPreset, geoCustom);
    if (geoPreset === 'custom' && geoRule) {
      geoRule.mode = geoCustomMode;
    }

    const clientRule = buildClientRule(clientDevice, clientBrowsers);
    const ipRule = buildIpRule(ipMode, ipText);

    setLoading(true);
    try {
      const result = await createLink({
        target_url: url,
        ...(isAdmin && customCode.trim() ? { custom_code: customCode.trim() } : {}),
        ttl_seconds: ttlSeconds,
        max_clicks: maxClicksNum,
        password: password.trim() || null,
        geo_rule: geoRule,
        client_rule: clientRule,
        ip_rule: ipRule,
      });
      let qrDataUrl: string | undefined;
      try {
        qrDataUrl = await QRCode.toDataURL(result.url, {
          width: 200,
          margin: 1,
          errorCorrectionLevel: 'M',
          color: { dark: '#0a0a0a', light: '#ffffff' },
        });
      } catch {
        // 仍展示短链
      }
      setCreated({ ...result, qrDataUrl });
      setTargetUrl('');
      setCustomCode('');
      setPassword('');
      setMaxClicks('');
      setTtl('');
      setCustomDays('');
      setGeoPreset('');
      setGeoCustom('');
      setClientDevice('');
      setClientBrowsers(new Set());
      setIpMode('');
      setIpText('');
    } catch (err) {
      setError(String(err));
    } finally {
      setLoading(false);
    }
  };

  const handleCopy = () => {
    if (!created) return;
    navigator.clipboard.writeText(created.url).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const qrDownloadName = (code: string) => {
    const safe = code.replace(/[^\w.\-]+/g, '_').replace(/^_+|_+$/g, '') || 'link';
    return `sproutlink-${safe}.png`;
  };

  return (
    <div className="paper">
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label className="form-label" htmlFor="target_url">URL</label>
          <input
            id="target_url"
            type="url"
            placeholder="https://"
            value={targetUrl}
            onChange={e => setTargetUrl(e.target.value)}
            required
          />
        </div>

        {isAdmin && (
          <div className="form-group">
            <label className="form-label" htmlFor="custom_code">短码</label>
            <input
              id="custom_code"
              type="text"
              inputMode="text"
              autoComplete="off"
              spellCheck={false}
              placeholder="可空，自定义（管理员）"
              value={customCode}
              onChange={e => setCustomCode(e.target.value)}
            />
          </div>
        )}

        <div className="form-row">
          <div className="form-group">
            <label className="form-label" htmlFor="ttl">期限</label>
            <select id="ttl" value={ttl} onChange={e => setTtl(e.target.value)}>
              {TTL_OPTIONS.map(o => (
                <option key={o.value} value={o.value}>{o.label}</option>
              ))}
            </select>
            {ttl === 'custom' && (
              <input
                type="number" min="0.01" step="any" placeholder="天"
                value={customDays} onChange={e => setCustomDays(e.target.value)}
                style={{ marginTop: '0.4rem' }}
              />
            )}
          </div>
          <div className="form-group">
            <label className="form-label" htmlFor="max_clicks">点击上限</label>
            <input
              id="max_clicks" type="number" min="1" step="1"
              placeholder="空为不限"
              value={maxClicks} onChange={e => setMaxClicks(e.target.value)}
            />
          </div>
        </div>

        <div className="form-group">
          <label className="form-label" htmlFor="geo_preset">地区</label>
          <select id="geo_preset" value={geoPreset} onChange={e => setGeoPreset(e.target.value)}>
            {GEO_OPTIONS.map(o => (
              <option key={o.value} value={o.value}>{o.label}</option>
            ))}
          </select>
          {geoPreset === 'custom' && (
            <div style={{ marginTop: '0.5rem', display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
              <select
                value={geoCustomMode}
                onChange={e => setGeoCustomMode(e.target.value as 'allow' | 'block')}
                style={{ width: 'auto', flexShrink: 0 }}
              >
                <option value="block">排除</option>
                <option value="allow">仅</option>
              </select>
              <input
                type="text"
                placeholder="ISO，如 US,GB"
                value={geoCustom}
                onChange={e => setGeoCustom(e.target.value)}
                style={{ flex: 1, minWidth: 200 }}
              />
            </div>
          )}
        </div>

        <div className="form-group">
          <label className="form-label" htmlFor="client_device">设备</label>
          <select
            id="client_device"
            value={clientDevice}
            onChange={e => setClientDevice(e.target.value)}
          >
            {DEVICE_OPTIONS.map(o => (
              <option key={o.value} value={o.value}>{o.label}</option>
            ))}
          </select>
        </div>
        <div className="form-group">
          <span className="form-label" style={{ display: 'block', marginBottom: '0.35rem' }}>浏览器</span>
          <div
            className="browser-checkboxes"
            style={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: '0.5rem 1rem',
              fontSize: '0.82rem',
            }}
          >
            {BROWSER_OPTIONS.map(o => (
              <label
                key={o.id}
                style={{ display: 'inline-flex', alignItems: 'center', gap: '0.3rem', cursor: 'pointer' }}
              >
                <input
                  type="checkbox"
                  style={{ width: 'auto' }}
                  checked={clientBrowsers.has(o.id)}
                  onChange={e => {
                    setClientBrowsers(prev => {
                      const n = new Set(prev);
                      if (e.target.checked) n.add(o.id);
                      else n.delete(o.id);
                      return n;
                    });
                  }}
                />
                {o.label}
              </label>
            ))}
          </div>
        </div>

        <div className="form-group">
          <label className="form-label" htmlFor="ip_mode">IP</label>
          <select
            id="ip_mode"
            value={ipMode}
            onChange={e => setIpMode(e.target.value as '' | 'allow' | 'block')}
          >
            <option value="">不限</option>
            <option value="allow">白名单</option>
            <option value="block">黑名单</option>
          </select>
          {ipMode && (
            <textarea
              value={ipText}
              onChange={e => setIpText(e.target.value)}
              placeholder="IP / CIDR，每行或逗号"
              rows={3}
              style={{ marginTop: '0.45rem', fontFamily: 'ui-monospace, monospace', fontSize: '0.82rem' }}
            />
          )}
        </div>

        <div className="form-group">
          <label className="form-label" htmlFor="password">密码</label>
          <input
            id="password" type="password"
            placeholder="可空"
            value={password} onChange={e => setPassword(e.target.value)}
            autoComplete="new-password"
          />
        </div>

        <button type="submit" className="btn-primary" disabled={loading} style={{ width: '100%' }}>
          {loading ? '生成中…' : '生成短链'}
        </button>
      </form>

      {error && <div className="error-msg">{error}</div>}

      {created && (
        <div className="result-box">
          <div className="result-box-body">
            {created.qrDataUrl && (
              <div className="result-qr">
                <img className="result-qr-img" src={created.qrDataUrl} alt="" />
                <a
                  className="btn-ghost result-qr-download"
                  href={created.qrDataUrl}
                  download={qrDownloadName(created.code)}
                >
                  下载二维码
                </a>
              </div>
            )}
            <div className="result-text">
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', flexWrap: 'wrap' }}>
                <a className="result-url" href={created.url} target="_blank" rel="noopener noreferrer">
                  {created.url}
                </a>
                <button className="btn-ghost" onClick={handleCopy} style={{ flexShrink: 0 }}>
                  {copied ? '已复制' : '复制链接'}
                </button>
              </div>
              <p className="result-meta">→ {created.target_url}</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
