'use client';

import { useState, useEffect, useCallback } from 'react';
import { Tags, Plus, RefreshCw, Pencil, Trash2, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { TenantTag, CreateTenantTagDto, UpdateTenantTagDto } from '@/domain/entities/tenant-tag';
import {
  listTenantTags,
  createTenantTag,
  updateTenantTag,
  deleteTenantTag,
} from '@/infrastructure/repositories/api-tenant-tag.repository';

/* ---------- Color picker presets ---------- */

const COLOR_PRESETS = [
  '#6366F1', '#8B5CF6', '#EC4899', '#EF4444',
  '#F97316', '#EAB308', '#22C55E', '#14B8A6',
  '#3B82F6', '#64748B',
];

/* ---------- Tag Modal ---------- */

function TagModal({
  initial,
  onSave,
  onClose,
}: {
  initial?: TenantTag;
  onSave: (dto: CreateTenantTagDto | UpdateTenantTagDto, id?: string) => Promise<void>;
  onClose: () => void;
}) {
  const [name, setName] = useState(initial?.name ?? '');
  const [color, setColor] = useState(initial?.color ?? '#6366F1');
  const [description, setDescription] = useState(initial?.description ?? '');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async () => {
    if (!name.trim()) { setError('标签名不能为空'); return; }
    setSaving(true);
    setError('');
    try {
      await onSave({ name: name.trim(), color, description: description.trim() || undefined }, initial?.id);
      onClose();
    } catch (e: any) {
      setError(e.message ?? '保存失败');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="bg-card w-full max-w-md rounded-xl shadow-xl border flex flex-col">
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-base font-semibold">{initial ? '编辑标签' : '新建标签'}</h2>
          <button onClick={onClose} className="text-muted-foreground hover:text-foreground">
            <X className="h-4 w-4" />
          </button>
        </div>

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

          <div>
            <label className="block text-xs font-medium mb-1">标签名 *</label>
            <input
              className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary"
              value={name}
              onChange={(e) => setName(e.target.value)}
              maxLength={50}
              placeholder="例如: 高价值客户"
            />
          </div>

          <div>
            <label className="block text-xs font-medium mb-1">标签颜色</label>
            <div className="flex flex-wrap gap-2 mb-2">
              {COLOR_PRESETS.map((c) => (
                <button
                  key={c}
                  type="button"
                  onClick={() => setColor(c)}
                  className={cn(
                    'w-7 h-7 rounded-full border-2 transition-all',
                    color === c ? 'border-foreground scale-110' : 'border-transparent',
                  )}
                  style={{ backgroundColor: c }}
                />
              ))}
            </div>
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="h-8 w-12 rounded border cursor-pointer"
              />
              <span className="text-sm font-mono text-muted-foreground">{color}</span>
              <span
                className="px-3 py-0.5 rounded-full text-xs font-medium text-white"
                style={{ backgroundColor: color }}
              >
                预览
              </span>
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium mb-1">描述（可选）</label>
            <textarea
              className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary resize-none"
              rows={2}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="该标签的用途说明"
            />
          </div>
        </div>

        <div className="flex justify-end gap-2 px-6 py-4 border-t">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border hover:bg-accent transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleSubmit}
            disabled={saving}
            className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
          >
            {saving ? '保存中…' : '保存'}
          </button>
        </div>
      </div>
    </div>
  );
}

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

export default function TenantTagsPage() {
  const [tags, setTags] = useState<TenantTag[]>([]);
  const [loading, setLoading] = useState(false);
  const [modal, setModal] = useState<{ mode: 'create' } | { mode: 'edit'; tag: TenantTag } | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);

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

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

  const handleSave = async (dto: CreateTenantTagDto | UpdateTenantTagDto, id?: string) => {
    if (id) {
      await updateTenantTag(id, dto as UpdateTenantTagDto);
    } else {
      await createTenantTag(dto as CreateTenantTagDto);
    }
    await load();
  };

  const handleDelete = async (tag: TenantTag) => {
    if (!confirm(`确认删除标签「${tag.name}」？删除后相关租户的标签绑定也会清除。`)) return;
    setDeleting(tag.id);
    try {
      await deleteTenantTag(tag.id);
      await load();
    } finally {
      setDeleting(null);
    }
  };

  return (
    <div className="flex-1 flex flex-col min-h-0 p-6">
      {/* header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <Tags className="h-5 w-5 text-primary" />
          <h1 className="text-xl font-semibold">租户标签管理</h1>
          <span className="text-xs text-muted-foreground ml-1">（用于精准推送分组）</span>
        </div>
        <div className="flex items-center gap-2">
          <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>
          <button
            onClick={() => setModal({ mode: 'create' })}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
          >
            <Plus className="h-3.5 w-3.5" />
            新建标签
          </button>
        </div>
      </div>

      {/* tag grid */}
      {loading && tags.length === 0 ? (
        <p className="text-muted-foreground text-sm">加载中…</p>
      ) : tags.length === 0 ? (
        <div className="flex flex-col items-center justify-center flex-1 text-muted-foreground gap-3">
          <Tags className="h-12 w-12 opacity-20" />
          <p className="text-sm">暂无标签，点击「新建标签」创建第一个标签</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {tags.map((tag) => (
            <div
              key={tag.id}
              className="bg-card border rounded-xl p-4 flex flex-col gap-3 hover:shadow-sm transition-shadow"
            >
              {/* tag header */}
              <div className="flex items-center justify-between">
                <span
                  className="px-3 py-1 rounded-full text-sm font-medium text-white"
                  style={{ backgroundColor: tag.color }}
                >
                  {tag.name}
                </span>
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => setModal({ mode: 'edit', tag })}
                    className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
                  >
                    <Pencil className="h-3.5 w-3.5" />
                  </button>
                  <button
                    onClick={() => handleDelete(tag)}
                    disabled={deleting === tag.id}
                    className="p-1.5 rounded hover:bg-red-50 text-muted-foreground hover:text-red-600 transition-colors disabled:opacity-50"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>

              {/* description */}
              {tag.description && (
                <p className="text-xs text-muted-foreground line-clamp-2">{tag.description}</p>
              )}

              {/* meta */}
              <div className="flex items-center justify-between text-xs text-muted-foreground mt-auto">
                <span>
                  {tag.tenantCount != null ? `${tag.tenantCount} 个租户` : '—'}
                </span>
                <span>{new Date(tag.createdAt).toLocaleDateString('zh-CN')}</span>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* modal */}
      {modal && (
        <TagModal
          initial={modal.mode === 'edit' ? modal.tag : undefined}
          onSave={handleSave}
          onClose={() => setModal(null)}
        />
      )}
    </div>
  );
}
