import { useState } from 'react';
import { updateLink, type ClientBrowser, type LinkItem, type GeoRule } from '../api';
import {
  BROWSER_OPTIONS,
  DEVICE_OPTIONS,
  buildClientRule,
  parseClientRuleJson,
} from '../clientRuleHelpers';
import { buildIpRule, parseIpRuleText } from '../ipRuleHelpers';

interface EditDrawerProps {
  item: LinkItem;
  onSave: () => void;
  onClose: () => void;
}

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

function ruleToPreset(rule: GeoRule | null): string {
  if (!rule) return '';
  const key = rule.countries.slice().sort().join(',');
  if (rule.mode === 'allow' && key === 'CN') return 'allow_cn';
  if (rule.mode === 'block' && key === 'CN') return 'block_cn';
  if (rule.mode === 'allow' && key === 'CN,HK,MO,TW') return 'allow_cntw';
  return 'custom';
}

function buildGeoRule(preset: string, customMode: 'allow' | 'block', customText: 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 = customText.toUpperCase().split(/[\s,]+/).filter(c => /^[A-Z]{2}$/.test(c));
      if (!raw.length) return null;
      return { mode: customMode, countries: raw };
    }
    default: return null;
  }
}

export default function EditDrawer({ item, onSave, onClose }: EditDrawerProps) {
  const [targetUrl, setTargetUrl] = useState(item.target_url);
  const [expiresAt, setExpiresAt] = useState<string>(
    item.expires_at ? new Date(item.expires_at * 1000).toISOString().slice(0, 16) : ''
  );
  const [maxClicks, setMaxClicks] = useState<string>(
    item.max_clicks !== null ? String(item.max_clicks) : ''
  );
  const [newPassword, setNewPassword] = useState('');
  const [clearPassword, setClearPassword] = useState(false);

  // Geo state
  const existingRule: GeoRule | null = item.geo_rule ? JSON.parse(item.geo_rule) : null;
  const initPreset = ruleToPreset(existingRule);
  const [geoPreset, setGeoPreset] = useState(initPreset);
  const [geoCustomMode, setGeoCustomMode] = useState<'allow' | 'block'>(existingRule?.mode ?? 'block');
  const [geoCustom, setGeoCustom] = useState(
    initPreset === 'custom' && existingRule ? existingRule.countries.join(', ') : ''
  );

  const initClient = parseClientRuleJson(item.client_rule);
  const [clientDevice, setClientDevice] = useState(initClient.device);
  const [clientBrowsers, setClientBrowsers] = useState<Set<ClientBrowser>>(() => new Set(initClient.selected));

  const initIp = parseIpRuleText(item.ip_rule);
  const [ipMode, setIpMode] = useState<'' | 'allow' | 'block'>(initIp.mode);
  const [ipText, setIpText] = useState(initIp.text);

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!targetUrl.trim()) { setError('目标链接不能为空'); return; }
    try { new URL(targetUrl.trim()); } catch { setError('请输入有效的 URL'); return; }

    setLoading(true);
    setError('');
    try {
      const geoRule = buildGeoRule(geoPreset, geoCustomMode, geoCustom);
      const clientRule = buildClientRule(clientDevice, clientBrowsers);
      const ipRule = buildIpRule(ipMode, ipText);
      const payload: Parameters<typeof updateLink>[1] = {
        target_url: targetUrl.trim(),
        expires_at: expiresAt ? Math.floor(new Date(expiresAt).getTime() / 1000) : null,
        max_clicks: maxClicks ? parseInt(maxClicks, 10) : null,
        geo_rule: geoRule,
        client_rule: clientRule,
        ip_rule: ipRule,
      };
      if (clearPassword) payload.clear_password = true;
      else if (newPassword) payload.password = newPassword;

      await updateLink(item.code, payload);
      onSave();
    } catch (e) {
      setError(String(e));
      setLoading(false);
    }
  };

  return (
    <div className="edit-drawer">
      <div className="edit-drawer-title">
        <span>编辑 <code style={{ color: 'var(--ink)', fontSize: '0.95em' }}>{item.code}</code></span>
        <button onClick={onClose}
          style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', fontSize: '1.1rem', borderRadius: 0, padding: '0 0.25rem' }}>
          ✕
        </button>
      </div>

      <form onSubmit={handleSave}>
        {/* Target URL */}
        <div className="form-group">
          <label className="form-label">URL</label>
          <input type="url" value={targetUrl} onChange={e => setTargetUrl(e.target.value)} required />
        </div>

        <div className="form-row">
          <div className="form-group">
            <label className="form-label">到期</label>
            <input type="datetime-local" value={expiresAt} onChange={e => setExpiresAt(e.target.value)} />
          </div>
          <div className="form-group">
            <label className="form-label">点击上限</label>
            <input 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">地区</label>
          <select 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="国家码，逗号分隔，如 US,GB"
                value={geoCustom} onChange={e => setGeoCustom(e.target.value)} style={{ flex: 1, minWidth: 160 }} />
            </div>
          )}
        </div>

        <div className="form-group">
          <label className="form-label">设备</label>
          <select 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 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">IP</label>
          <select 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，最多 200 条"
              rows={4}
              style={{ marginTop: '0.45rem', fontFamily: 'ui-monospace, monospace', fontSize: '0.86rem' }}
            />
          )}
        </div>

        <div className="form-group">
          <label className="form-label">密码</label>
          <input type="password" placeholder={item.has_password ? '新密码' : '可空'}
            value={newPassword}
            onChange={e => { setNewPassword(e.target.value); if (e.target.value) setClearPassword(false); }}
            disabled={clearPassword} autoComplete="new-password" />
          {item.has_password && (
            <label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', marginTop: '0.35rem', fontSize: '0.8rem', cursor: 'pointer', color: 'var(--muted)' }}>
              <input type="checkbox" style={{ width: 'auto' }} checked={clearPassword}
                onChange={e => { setClearPassword(e.target.checked); if (e.target.checked) setNewPassword(''); }} />
              清除密码
            </label>
          )}
        </div>

        {error && <div className="error-msg" style={{ marginBottom: '0.75rem' }}>{error}</div>}

        <div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'flex-end' }}>
          <button type="button" className="btn-ghost" onClick={onClose} disabled={loading}>取消</button>
          <button type="submit" className="btn-primary" disabled={loading}>
            {loading ? '保存中…' : '保存'}
          </button>
        </div>
      </form>
    </div>
  );
}
