import { useEffect, useMemo, useState } from "react";
import { api, ApiError } from "../api";
import type { Brand } from "../types";
import { Tag, Pencil, Plus, Trash2, GitMerge, Search } from "lucide-react";

type EditState = { id: string; name: string };
type MergeState = { source: Brand; targetId: string };

export default function BrandsPage() {
  const [rows, setRows] = useState<Brand[]>([]);
  const [error, setError] = useState("");
  const [query, setQuery] = useState("");
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState("");
  const [edit, setEdit] = useState<EditState | null>(null);
  const [merge, setMerge] = useState<MergeState | null>(null);
  const [busy, setBusy] = useState(false);

  async function load() {
    setError("");
    try {
      const res = await api.listBrands();
      setRows(res.items);
    } catch (e) {
      setError(e instanceof ApiError ? e.message : "加载失败");
    }
  }

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

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((b) => b.name.toLowerCase().includes(q));
  }, [rows, query]);

  function fail(e: unknown, fallback: string) {
    setError(e instanceof ApiError ? e.message : fallback);
  }

  async function create() {
    if (!newName.trim()) return;
    setBusy(true);
    setError("");
    try {
      await api.createBrand(newName.trim());
      setNewName("");
      setCreating(false);
      await load();
    } catch (e) {
      fail(e, "新建失败");
    } finally {
      setBusy(false);
    }
  }

  async function saveEdit() {
    if (!edit || !edit.name.trim()) return;
    setBusy(true);
    setError("");
    try {
      await api.updateBrand(edit.id, edit.name.trim());
      setEdit(null);
      await load();
    } catch (e) {
      fail(e, "保存失败");
    } finally {
      setBusy(false);
    }
  }

  async function remove(b: Brand) {
    if (!confirm(`确认删除品牌「${b.name}」？`)) return;
    setError("");
    try {
      await api.deleteBrand(b.id);
      await load();
    } catch (e) {
      fail(e, "删除失败");
    }
  }

  async function doMerge() {
    if (!merge || !merge.targetId) return;
    const target = rows.find((b) => b.id === merge.targetId);
    if (
      !confirm(
        `将「${merge.source.name}」的 ${merge.source.product_count} 个商品并入「${target?.name}」，并删除「${merge.source.name}」？`,
      )
    )
      return;
    setBusy(true);
    setError("");
    try {
      await api.mergeBrands(merge.source.id, merge.targetId);
      setMerge(null);
      await load();
    } catch (e) {
      fail(e, "合并失败");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="mx-auto max-w-4xl">
      <div className="flex items-center justify-between mb-4">
        <div>
          <h2 className="text-lg font-semibold text-gray-800 flex items-center gap-2">
            <Tag className="h-5 w-5 text-emerald-600" /> 品牌管理
          </h2>
          <p className="text-sm text-gray-500 mt-1">
            维护品牌名录。可重命名、删除未被引用的品牌，或将重复品牌合并到一起。
          </p>
        </div>
        <button
          onClick={() => {
            setCreating(true);
            setNewName("");
          }}
          className="px-4 py-2 rounded-lg bg-emerald-600 text-white text-sm font-medium hover:bg-emerald-700 flex items-center gap-1.5"
        >
          <Plus className="h-4 w-4" /> 新建品牌
        </button>
      </div>

      {error && (
        <div className="mb-3 bg-red-50 text-red-700 text-sm rounded px-4 py-2">{error}</div>
      )}

      <div className="mb-3 relative w-72">
        <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-400" />
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="筛选品牌名"
          className="w-full rounded border border-gray-300 py-2 pl-8 pr-3 text-sm focus:border-emerald-500 focus:outline-none"
        />
      </div>

      {creating && (
        <div className="mb-4 bg-white border rounded-lg p-5">
          <h3 className="font-medium text-gray-700 mb-3">新建品牌</h3>
          <div className="flex items-end gap-2">
            <label className="block flex-1">
              <span className="text-xs text-gray-500">品牌名称 *</span>
              <input
                autoFocus
                className="w-full border rounded-md px-3 py-2 text-sm mt-1"
                value={newName}
                onChange={(e) => setNewName(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && create()}
                placeholder="例如：可口可乐"
              />
            </label>
            <button
              onClick={create}
              disabled={busy}
              className="px-4 py-2 rounded bg-emerald-600 text-white text-sm hover:bg-emerald-700 disabled:opacity-60"
            >
              保存
            </button>
            <button
              onClick={() => setCreating(false)}
              className="px-4 py-2 rounded border text-sm text-gray-600"
            >
              取消
            </button>
          </div>
        </div>
      )}

      {merge && (
        <div className="mb-4 bg-white border rounded-lg p-5">
          <h3 className="font-medium text-gray-700 mb-3 flex items-center gap-1.5">
            <GitMerge className="h-4 w-4 text-emerald-600" /> 合并品牌
          </h3>
          <p className="text-sm text-gray-500 mb-3">
            把「{merge.source.name}」（{merge.source.product_count} 个商品）合并到下面选择的品牌，源品牌将被删除。
          </p>
          <div className="flex items-end gap-2">
            <label className="block flex-1">
              <span className="text-xs text-gray-500">合并到</span>
              <select
                className="w-full border rounded-md px-3 py-2 text-sm mt-1 bg-white"
                value={merge.targetId}
                onChange={(e) => setMerge({ ...merge, targetId: e.target.value })}
              >
                <option value="">（请选择目标品牌）</option>
                {rows
                  .filter((b) => b.id !== merge.source.id)
                  .map((b) => (
                    <option key={b.id} value={b.id}>
                      {b.name}（{b.product_count}）
                    </option>
                  ))}
              </select>
            </label>
            <button
              onClick={doMerge}
              disabled={busy || !merge.targetId}
              className="px-4 py-2 rounded bg-emerald-600 text-white text-sm hover:bg-emerald-700 disabled:opacity-60"
            >
              合并
            </button>
            <button
              onClick={() => setMerge(null)}
              className="px-4 py-2 rounded border text-sm text-gray-600"
            >
              取消
            </button>
          </div>
        </div>
      )}

      <div className="bg-white border rounded-lg overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-gray-500 text-left">
            <tr>
              <th className="px-4 py-2 font-medium">品牌</th>
              <th className="px-4 py-2 font-medium">商品数</th>
              <th className="px-4 py-2 font-medium"></th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.length === 0 ? (
              <tr>
                <td colSpan={3} className="px-4 py-8 text-center text-gray-400">
                  {rows.length === 0 ? "暂无品牌" : "无匹配品牌"}
                </td>
              </tr>
            ) : (
              filtered.map((b) => (
                <tr key={b.id} className="hover:bg-gray-50">
                  <td className="px-4 py-2 text-gray-800">
                    {edit && edit.id === b.id ? (
                      <input
                        autoFocus
                        className="border rounded px-2 py-1 text-sm w-64"
                        value={edit.name}
                        onChange={(e) => setEdit({ ...edit, name: e.target.value })}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") saveEdit();
                          if (e.key === "Escape") setEdit(null);
                        }}
                      />
                    ) : (
                      <span className="font-medium">{b.name}</span>
                    )}
                  </td>
                  <td className="px-4 py-2 text-gray-600">{b.product_count}</td>
                  <td className="px-4 py-2 text-right whitespace-nowrap">
                    {edit && edit.id === b.id ? (
                      <>
                        <button
                          onClick={saveEdit}
                          disabled={busy}
                          className="text-emerald-600 hover:text-emerald-700 text-xs mr-3"
                        >
                          保存
                        </button>
                        <button
                          onClick={() => setEdit(null)}
                          className="text-gray-400 hover:text-gray-600 text-xs"
                        >
                          取消
                        </button>
                      </>
                    ) : (
                      <>
                        <button
                          onClick={() => setEdit({ id: b.id, name: b.name })}
                          className="text-gray-400 hover:text-emerald-600 mr-3"
                          title="重命名"
                        >
                          <Pencil className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => setMerge({ source: b, targetId: "" })}
                          className="text-gray-400 hover:text-emerald-600 mr-3"
                          title="合并到其它品牌"
                        >
                          <GitMerge className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => remove(b)}
                          className="text-gray-400 hover:text-red-600"
                          title="删除"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
