'use client';

import { useState, useEffect, useCallback } from 'react';
import { Users2, RefreshCw, Trash2, X, ChevronRight, Upload } from 'lucide-react';
import { cn } from '@/lib/utils';

interface SegmentInfo {
  segmentKey: string;
  memberCount: number;
  syncedAt: string | null;
}

interface SegmentMember {
  tenantId: string;
  syncedAt: string;
}

function getAuthHeaders(): HeadersInit {
  const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
  return { Authorization: `Bearer ${token ?? ''}`, 'Content-Type': 'application/json' };
}

const BASE = '/api/proxy/api/v1/notifications/segments';

async function listSegments(): Promise<SegmentInfo[]> {
  const res = await fetch(BASE, { headers: getAuthHeaders() });
  if (!res.ok) throw new Error(`${res.status}`);
  return res.json();
}

async function getSegmentMembers(key: string, limit = 50, offset = 0): Promise<{ items: SegmentMember[]; total: number }> {
  const res = await fetch(`${BASE}/${key}/members?limit=${limit}&offset=${offset}`, { headers: getAuthHeaders() });
  if (!res.ok) throw new Error(`${res.status}`);
  return res.json();
}

async function syncSegment(key: string, tenantIds: string[]): Promise<void> {
  const res = await fetch(`${BASE}/${key}/sync`, {
    method: 'POST', headers: getAuthHeaders(), body: JSON.stringify({ tenantIds }),
  });
  if (!res.ok) throw new Error(`${res.status}`);
}

async function addToSegment(key: string, tenantIds: string[]): Promise<void> {
  const res = await fetch(`${BASE}/${key}/add`, {
    method: 'POST', headers: getAuthHeaders(), body: JSON.stringify({ tenantIds }),
  });
  if (!res.ok) throw new Error(`${res.status}`);
}

async function removeFromSegment(key: string, tenantIds: string[]): Promise<void> {
  const res = await fetch(`${BASE}/${key}/remove`, {
    method: 'POST', headers: getAuthHeaders(), body: JSON.stringify({ tenantIds }),
  });
  if (!res.ok) throw new Error(`${res.status}`);
}

async function deleteSegment(key: string): Promise<void> {
  const res = await fetch(`${BASE}/${key}`, { method: 'DELETE', headers: getAuthHeaders() });
  if (!res.ok) throw new Error(`${res.status}`);
}

/* ---------- Segment detail panel ---------- */

function SegmentDetail({
  segmentKey,
  onClose,
  onRefresh,
}: {
  segmentKey: string;
  onClose: () => void;
  onRefresh: () => void;
}) {
  const [members, setMembers] = useState<SegmentMember[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [offset, setOffset] = useState(0);
  const limit = 50;

  const [addRaw, setAddRaw] = useState('');
  const [syncRaw, setSyncRaw] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const loadMembers = useCallback(async () => {
    setLoading(true);
    try {
      const result = await getSegmentMembers(segmentKey, limit, offset);
      setMembers(result.items);
      setTotal(result.total);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, [segmentKey, offset]);

  useEffect(() => { loadMembers(); }, [loadMembers]);

  const handleAdd = async () => {
    const ids = addRaw.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean);
    if (!ids.length) return;
    setSaving(true); setError('');
    try {
      await addToSegment(segmentKey, ids);
      setAddRaw('');
      await loadMembers();
      onRefresh();
    } catch (e: any) {
      setError(e.message);
    } finally { setSaving(false); }
  };

  const handleSync = async () => {
    const ids = syncRaw.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean);
    if (!confirm(`确认用 ${ids.length} 个租户 ID 替换「${segmentKey}」的全部成员？`)) return;
    setSaving(true); setError('');
    try {
      await syncSegment(segmentKey, ids);
      setSyncRaw('');
      await loadMembers();
      onRefresh();
    } catch (e: any) {
      setError(e.message);
    } finally { setSaving(false); }
  };

  const handleRemove = async (tenantId: string) => {
    await removeFromSegment(segmentKey, [tenantId]);
    await loadMembers();
    onRefresh();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/40 p-4">
      <div className="bg-card w-full max-w-2xl rounded-xl shadow-xl border flex flex-col max-h-[85vh]">
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <div>
            <h2 className="text-base font-semibold font-mono">{segmentKey}</h2>
            <p className="text-xs text-muted-foreground">共 {total} 个成员租户</p>
          </div>
          <button onClick={onClose} className="text-muted-foreground hover:text-foreground"><X className="h-4 w-4" /></button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
          {error && <p className="text-sm text-red-500">{error}</p>}

          {/* Add tenants */}
          <div>
            <label className="block text-xs font-medium mb-1">新增租户（每行一个 ID）</label>
            <textarea
              className="w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-primary resize-none"
              rows={3} value={addRaw} onChange={(e) => setAddRaw(e.target.value)}
              placeholder="tenant-uuid-1&#10;tenant-uuid-2"
            />
            <button onClick={handleAdd} disabled={saving || !addRaw.trim()}
              className="mt-2 flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors">
              添加成员
            </button>
          </div>

          {/* Bulk sync */}
          <div className="border rounded-lg p-3 bg-muted/30">
            <div className="flex items-center gap-1.5 mb-1">
              <Upload className="h-3.5 w-3.5 text-muted-foreground" />
              <label className="text-xs font-medium">全量替换（ETL 同步）</label>
            </div>
            <textarea
              className="w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-primary resize-none"
              rows={3} value={syncRaw} onChange={(e) => setSyncRaw(e.target.value)}
              placeholder="全量租户 ID，将替换现有成员"
            />
            <button onClick={handleSync} disabled={saving || !syncRaw.trim()}
              className="mt-2 flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md bg-orange-600 text-white hover:bg-orange-700 disabled:opacity-50 transition-colors">
              全量替换
            </button>
          </div>

          {/* Members list */}
          <div>
            <p className="text-xs font-medium mb-2 text-muted-foreground">当前成员 ({total})</p>
            <div className="border rounded-lg divide-y max-h-60 overflow-y-auto">
              {loading ? (
                <p className="text-center py-4 text-sm text-muted-foreground">加载中…</p>
              ) : members.length === 0 ? (
                <p className="text-center py-4 text-sm text-muted-foreground">暂无成员</p>
              ) : (
                members.map((m) => (
                  <div key={m.tenantId} className="flex items-center justify-between px-3 py-2 hover:bg-muted/30">
                    <span className="text-xs font-mono text-muted-foreground">{m.tenantId}</span>
                    <div className="flex items-center gap-2">
                      <span className="text-xs text-muted-foreground">
                        {new Date(m.syncedAt).toLocaleDateString('zh-CN')}
                      </span>
                      <button onClick={() => handleRemove(m.tenantId)}
                        className="p-1 rounded hover:bg-red-50 text-muted-foreground hover:text-red-600 transition-colors">
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  </div>
                ))
              )}
            </div>
            {total > limit && (
              <div className="flex gap-2 mt-2">
                <button disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - limit))}
                  className="px-3 py-1 text-xs rounded border hover:bg-accent disabled:opacity-40">上一页</button>
                <button disabled={offset + limit >= total} onClick={() => setOffset(offset + limit)}
                  className="px-3 py-1 text-xs rounded border hover:bg-accent disabled:opacity-40">下一页</button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Main page ---------- */

export default function SegmentsPage() {
  const [segments, setSegments] = useState<SegmentInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try { setSegments(await listSegments()); }
    catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  const handleDelete = async (key: string) => {
    if (!confirm(`确认删除人群包「${key}」？`)) return;
    setDeleting(key);
    try { await deleteSegment(key); await load(); }
    finally { setDeleting(null); }
  };

  return (
    <div className="flex-1 flex flex-col min-h-0 p-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <Users2 className="h-5 w-5 text-primary" />
          <h1 className="text-xl font-semibold">人群包管理</h1>
          <span className="text-xs text-muted-foreground ml-1">（BY_SEGMENT 精准推送）</span>
        </div>
        <button onClick={load} disabled={loading}
          className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border hover:bg-accent transition-colors">
          <RefreshCw className={cn('h-3.5 w-3.5', loading && 'animate-spin')} />刷新
        </button>
      </div>

      {/* Description */}
      <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-950/30 rounded-lg text-xs text-blue-700 dark:text-blue-300">
        <strong>说明：</strong>人群包是一组租户 ID 集合，可用于「按人群包」精准推送通知。
        可通过 API 或此界面手动管理，也可由外部 ETL 作业定期同步。
        在通知表单中，选择「按人群包」并输入对应的 segment key 即可定向推送。
      </div>

      {loading && segments.length === 0 ? (
        <p className="text-muted-foreground text-sm">加载中…</p>
      ) : segments.length === 0 ? (
        <div className="flex flex-col items-center justify-center flex-1 text-muted-foreground gap-3">
          <Users2 className="h-12 w-12 opacity-20" />
          <p className="text-sm">暂无人群包。点击某个分组名称或通过 API 的 <code>/sync</code> 接口创建。</p>
          <p className="text-xs">例：<code>POST /api/v1/notifications/segments/trial_ending_soon/sync</code></p>
        </div>
      ) : (
        <div className="flex-1 min-h-0 overflow-auto rounded-lg border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 sticky top-0">
              <tr>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">Segment Key</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">成员数</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">最近同步</th>
                <th className="text-right px-4 py-3 font-medium text-muted-foreground">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {segments.map((seg) => (
                <tr key={seg.segmentKey} className="hover:bg-muted/30 transition-colors">
                  <td className="px-4 py-3 font-mono text-sm font-medium">{seg.segmentKey}</td>
                  <td className="px-4 py-3">
                    <span className="px-2 py-0.5 rounded bg-primary/10 text-primary text-xs font-medium">
                      {seg.memberCount.toLocaleString()} 租户
                    </span>
                  </td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">
                    {seg.syncedAt ? new Date(seg.syncedAt).toLocaleString('zh-CN', { dateStyle: 'short', timeStyle: 'short' }) : '—'}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-1">
                      <button onClick={() => setSelectedKey(seg.segmentKey)}
                        className="flex items-center gap-1 px-2 py-1 rounded text-xs hover:bg-accent text-muted-foreground hover:text-foreground transition-colors">
                        管理 <ChevronRight className="h-3 w-3" />
                      </button>
                      <button onClick={() => handleDelete(seg.segmentKey)} disabled={deleting === seg.segmentKey}
                        className="p-1.5 rounded hover:bg-red-50 text-muted-foreground hover:text-red-600 transition-colors disabled:opacity-50">
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedKey && (
        <SegmentDetail
          segmentKey={selectedKey}
          onClose={() => setSelectedKey(null)}
          onRefresh={load}
        />
      )}
    </div>
  );
}
