import { PipedriveClient, err } from "../client.js";
import type { ToolDefinition, ToolResult, Deal } from "../types.js";

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_app_deal_grid",
    description: "Sortable deal grid/list with filters and search",
    inputSchema: {
      type: "object",
      properties: {
        status: { type: "string", description: "open, won, lost, or all" },
        sort: { type: "string", description: "Field to sort by" },
        limit: { type: "number", description: "Max deals to show" },
      },
    },
  },
];

function escapeHtml(s: string | undefined): string {
  return (s || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    const params: Record<string, unknown> = { limit: args.limit || 100 };
    if (args.status) params.status = args.status;
    if (args.sort) params.sort = args.sort;

    const result = await client.get<{ success: boolean; data: Deal[] }>("/deals", params);
    const deals = result.data || [];

    const html = `
      <div style="font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#0d0d1a;color:#e0e0e0;padding:24px;border-radius:16px;">
        <h2 style="margin:0 0 16px;color:#fff;">📋 Deal Grid <span style="font-size:14px;color:#888;">(${deals.length} deals)</span></h2>
        
        <div style="overflow-x:auto;">
          <table style="width:100%;border-collapse:collapse;font-size:13px;">
            <thead>
              <tr style="background:#1a1a2e;border-bottom:2px solid #333;">
                <th style="text-align:left;padding:12px;font-weight:600;">Title</th>
                <th style="text-align:center;padding:12px;font-weight:600;">Status</th>
                <th style="text-align:right;padding:12px;font-weight:600;">Value</th>
                <th style="text-align:center;padding:12px;font-weight:600;">Probability</th>
                <th style="text-align:center;padding:12px;font-weight:600;">Stage</th>
                <th style="text-align:center;padding:12px;font-weight:600;">Owner</th>
              </tr>
            </thead>
            <tbody>
              ${deals.map((d, i) => `
                <tr style="border-bottom:1px solid #222;${i % 2 === 0 ? "background:#0f0f1a;" : ""}">
                  <td style="padding:12px;">
                    <div style="font-weight:500;color:#fff;">${escapeHtml(d.title)}</div>
                    <div style="font-size:11px;color:#666;">ID: ${d.id}</div>
                  </td>
                  <td style="padding:12px;text-align:center;">
                    <span style="padding:4px 10px;border-radius:12px;font-size:11px;font-weight:500;background:${d.status === "won" ? "#1B5E20" : d.status === "lost" ? "#B71C1C" : "#1565C0"};color:#fff;">
                      ${escapeHtml(d.status)}
                    </span>
                  </td>
                  <td style="padding:12px;text-align:right;font-weight:600;color:#4CAF50;">${(d.value || 0).toLocaleString()} ${d.currency}</td>
                  <td style="padding:12px;text-align:center;color:#FFC107;">${d.probability || 0}%</td>
                  <td style="padding:12px;text-align:center;color:#888;">${d.stage_id || "—"}</td>
                  <td style="padding:12px;text-align:center;color:#888;">${d.user_id || "—"}</td>
                </tr>
              `).join("")}
            </tbody>
          </table>
        </div>
      </div>
    `;

    return {
      content: [{ type: "text", text: `Deal grid with ${deals.length} deals` }],
      structuredContent: { type: "html", html },
    };
  } catch (error) {
    return err(error);
  }
}
