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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_app_deal_dashboard",
    description: "Rich dashboard showing deal overview with won/lost ratio, revenue forecast, and statistics",
    inputSchema: {
      type: "object",
      properties: {
        user_id: { type: "number", description: "Filter by user ID" },
        pipeline_id: { type: "number", description: "Filter by pipeline ID" },
      },
    },
  },
];

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

function renderDashboard(deals: Deal[]): string {
  const openDeals = deals.filter((d) => d.status === "open");
  const wonDeals = deals.filter((d) => d.status === "won");
  const lostDeals = deals.filter((d) => d.status === "lost");
  
  const totalValue = deals.reduce((sum, d) => sum + (d.value || 0), 0);
  const wonValue = wonDeals.reduce((sum, d) => sum + (d.value || 0), 0);
  const lostValue = lostDeals.reduce((sum, d) => sum + (d.value || 0), 0);
  const openValue = openDeals.reduce((sum, d) => sum + (d.value || 0), 0);
  
  const winRate = deals.length > 0 ? ((wonDeals.length / deals.length) * 100).toFixed(1) : "0";
  const avgDealValue = deals.length > 0 ? (totalValue / deals.length).toFixed(2) : "0";
  
  const currency = deals[0]?.currency || "USD";

  return `
    <div style="font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#0d0d1a;color:#e0e0e0;padding:24px;border-radius:16px;max-width:1200px;">
      <h2 style="margin:0 0 24px;color:#fff;display:flex;align-items:center;gap:12px;">
        <span>💼</span> Deal Dashboard
      </h2>
      
      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px;">
        <div style="background:#1a1a2e;padding:20px;border-radius:12px;text-align:center;">
          <div style="font-size:32px;font-weight:600;color:#4CAF50;">${openDeals.length}</div>
          <div style="font-size:13px;color:#888;margin-top:4px;">Open Deals</div>
          <div style="font-size:11px;color:#4CAF50;margin-top:8px;">${openValue.toLocaleString()} ${currency}</div>
        </div>
        
        <div style="background:#1a1a2e;padding:20px;border-radius:12px;text-align:center;">
          <div style="font-size:32px;font-weight:600;color:#2196F3;">${wonDeals.length}</div>
          <div style="font-size:13px;color:#888;margin-top:4px;">Won Deals</div>
          <div style="font-size:11px;color:#2196F3;margin-top:8px;">${wonValue.toLocaleString()} ${currency}</div>
        </div>
        
        <div style="background:#1a1a2e;padding:20px;border-radius:12px;text-align:center;">
          <div style="font-size:32px;font-weight:600;color:#FF5722;">${lostDeals.length}</div>
          <div style="font-size:13px;color:#888;margin-top:4px;">Lost Deals</div>
          <div style="font-size:11px;color:#FF5722;margin-top:8px;">${lostValue.toLocaleString()} ${currency}</div>
        </div>
        
        <div style="background:#1a1a2e;padding:20px;border-radius:12px;text-align:center;">
          <div style="font-size:32px;font-weight:600;color:#FFC107;">${winRate}%</div>
          <div style="font-size:13px;color:#888;margin-top:4px;">Win Rate</div>
          <div style="font-size:11px;color:#FFC107;margin-top:8px;">Avg: ${avgDealValue} ${currency}</div>
        </div>
      </div>

      <h3 style="color:#ccc;margin:24px 0 12px;font-size:16px;">📊 Revenue Forecast (Open Pipeline)</h3>
      <div style="background:#1a1a2e;padding:20px;border-radius:12px;margin-bottom:24px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
          <span style="font-size:13px;color:#888;">Weighted Value (by probability)</span>
          <span style="font-size:18px;font-weight:600;color:#4CAF50;">
            ${openDeals.reduce((sum, d) => sum + (d.value || 0) * ((d.probability || 0) / 100), 0).toFixed(2)} ${currency}
          </span>
        </div>
        <div style="height:8px;background:#0d0d1a;border-radius:4px;overflow:hidden;">
          <div style="height:100%;background:linear-gradient(90deg,#4CAF50,#2196F3);width:${openDeals.length > 0 ? 100 : 0}%;transition:width 0.3s;"></div>
        </div>
      </div>

      <h3 style="color:#ccc;margin:24px 0 12px;font-size:16px;">🔥 Recent Open Deals</h3>
      <div style="display:grid;gap:8px;">
        ${openDeals.slice(0, 10).map((d) => `
          <div style="background:#1a1a2e;padding:12px 16px;border-radius:8px;display:flex;justify-content:space-between;align-items:center;">
            <div style="flex:1;">
              <span style="font-weight:500;color:#fff;">${escapeHtml(d.title)}</span>
              <span style="font-size:11px;color:#666;margin-left:8px;">Stage: ${d.stage_id || "N/A"}</span>
            </div>
            <div style="text-align:right;">
              <div style="font-weight:600;color:#4CAF50;">${(d.value || 0).toLocaleString()} ${d.currency}</div>
              <div style="font-size:11px;color:#888;">${d.probability || 0}% probability</div>
            </div>
          </div>
        `).join("")}
      </div>
    </div>
  `;
}

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

    const result = await client.get<{ success: boolean; data: Deal[] }>("/deals", params);
    const deals = result.data || [];
    
    const html = renderDashboard(deals);
    return {
      content: [{ type: "text", text: `Deal dashboard with ${deals.length} total deals` }],
      structuredContent: { type: "html", html },
    };
  } catch (error) {
    return err(error);
  }
}
