/**
 * Withdrawal Audit Reports System
 * Generate audit reports for withdrawals with filtering and export
 */

export interface WithdrawalRecord {
  id: string;
  playerId: number;
  playerName: string;
  playerEmail: string;
  amount: number;
  currency: "SC" | "GC";
  method: "bank_transfer" | "square_payout" | "check";
  status: "pending" | "approved" | "processing" | "completed" | "rejected" | "failed";
  requestedAt: Date;
  approvedAt?: Date;
  approvedBy?: number;
  completedAt?: Date;
  failureReason?: string;
  fee?: number;
  netAmount?: number;
  bankDetails?: {
    accountHolderName: string;
    accountNumber: string;
    routingNumber: string;
    bankName: string;
  };
}

export interface WithdrawalAuditReport {
  reportId: string;
  generatedAt: Date;
  generatedBy: number;
  filters: {
    startDate?: Date;
    endDate?: Date;
    status?: string[];
    currency?: string[];
    method?: string[];
    playerId?: number;
  };
  summary: {
    totalWithdrawals: number;
    totalAmount: number;
    totalFees: number;
    netAmount: number;
    byStatus: Record<string, number>;
    byMethod: Record<string, number>;
    byCurrency: Record<string, number>;
    averageWithdrawalAmount: number;
    medianWithdrawalAmount: number;
    minWithdrawalAmount: number;
    maxWithdrawalAmount: number;
  };
  details: WithdrawalRecord[];
}

/**
 * Generate withdrawal audit report
 */
export function generateWithdrawalAuditReport(
  withdrawals: WithdrawalRecord[],
  filters: {
    startDate?: Date;
    endDate?: Date;
    status?: string[];
    currency?: string[];
    method?: string[];
    playerId?: number;
  },
  adminId: number
): WithdrawalAuditReport {
  // Filter withdrawals
  let filtered = withdrawals;

  if (filters.startDate) {
    filtered = filtered.filter((w) => w.requestedAt >= filters.startDate!);
  }

  if (filters.endDate) {
    filtered = filtered.filter((w) => w.requestedAt <= filters.endDate!);
  }

  if (filters.status && filters.status.length > 0) {
    filtered = filtered.filter((w) => filters.status!.includes(w.status));
  }

  if (filters.currency && filters.currency.length > 0) {
    filtered = filtered.filter((w) => filters.currency!.includes(w.currency));
  }

  if (filters.method && filters.method.length > 0) {
    filtered = filtered.filter((w) => filters.method!.includes(w.method));
  }

  if (filters.playerId) {
    filtered = filtered.filter((w) => w.playerId === filters.playerId);
  }

  // Calculate summary statistics
  const amounts = filtered.map((w) => w.amount).sort((a, b) => a - b);
  const totalAmount = amounts.reduce((sum, a) => sum + a, 0);
  const totalFees = filtered.reduce((sum, w) => sum + (w.fee || 0), 0);
  const netAmount = totalAmount - totalFees;

  const byStatus: Record<string, number> = {};
  const byMethod: Record<string, number> = {};
  const byCurrency: Record<string, number> = {};

  filtered.forEach((w) => {
    byStatus[w.status] = (byStatus[w.status] || 0) + 1;
    byMethod[w.method] = (byMethod[w.method] || 0) + 1;
    byCurrency[w.currency] = (byCurrency[w.currency] || 0) + 1;
  });

  const medianAmount =
    amounts.length > 0
      ? amounts.length % 2 === 0
        ? (amounts[amounts.length / 2 - 1] + amounts[amounts.length / 2]) / 2
        : amounts[Math.floor(amounts.length / 2)]
      : 0;

  const report: WithdrawalAuditReport = {
    reportId: `report_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
    generatedAt: new Date(),
    generatedBy: adminId,
    filters,
    summary: {
      totalWithdrawals: filtered.length,
      totalAmount,
      totalFees,
      netAmount,
      byStatus,
      byMethod,
      byCurrency,
      averageWithdrawalAmount: filtered.length > 0 ? totalAmount / filtered.length : 0,
      medianWithdrawalAmount: medianAmount,
      minWithdrawalAmount: amounts.length > 0 ? amounts[0] : 0,
      maxWithdrawalAmount: amounts.length > 0 ? amounts[amounts.length - 1] : 0,
    },
    details: filtered,
  };

  return report;
}

/**
 * Export report as CSV
 */
export function exportReportAsCSV(report: WithdrawalAuditReport): string {
  const headers = [
    "ID",
    "Player ID",
    "Player Name",
    "Email",
    "Amount",
    "Currency",
    "Method",
    "Status",
    "Requested At",
    "Approved At",
    "Completed At",
    "Fee",
    "Net Amount",
  ];

  const rows = report.details.map((w) => [
    w.id,
    w.playerId,
    w.playerName,
    w.playerEmail,
    w.amount,
    w.currency,
    w.method,
    w.status,
    w.requestedAt.toISOString(),
    w.approvedAt?.toISOString() || "N/A",
    w.completedAt?.toISOString() || "N/A",
    w.fee || "N/A",
    w.netAmount || "N/A",
  ]);

  // Add summary section
  const summaryRows = [
    [],
    ["SUMMARY"],
    ["Total Withdrawals", report.summary.totalWithdrawals],
    ["Total Amount", report.summary.totalAmount],
    ["Total Fees", report.summary.totalFees],
    ["Net Amount", report.summary.netAmount],
    ["Average Amount", report.summary.averageWithdrawalAmount.toFixed(2)],
    ["Median Amount", report.summary.medianWithdrawalAmount.toFixed(2)],
    ["Min Amount", report.summary.minWithdrawalAmount],
    ["Max Amount", report.summary.maxWithdrawalAmount],
  ];

  const csv = [
    headers.join(","),
    ...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
    ...summaryRows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
  ].join("\n");

  return csv;
}

/**
 * Export report as JSON
 */
export function exportReportAsJSON(report: WithdrawalAuditReport): string {
  return JSON.stringify(report, null, 2);
}

/**
 * Generate HTML report
 */
export function generateHTMLReport(report: WithdrawalAuditReport): string {
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>Withdrawal Audit Report</title>
      <style>
        body {
          font-family: Arial, sans-serif;
          margin: 20px;
          background-color: #f5f5f5;
        }
        .container {
          max-width: 1200px;
          margin: 0 auto;
          background-color: white;
          padding: 20px;
          border-radius: 8px;
          box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
          color: #333;
          border-bottom: 2px solid #f59e0b;
          padding-bottom: 10px;
        }
        h2 {
          color: #555;
          margin-top: 30px;
        }
        .report-info {
          background-color: #f9fafb;
          padding: 15px;
          border-radius: 4px;
          margin-bottom: 20px;
        }
        .report-info p {
          margin: 5px 0;
          color: #666;
        }
        .summary-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 15px;
          margin: 20px 0;
        }
        .summary-card {
          background-color: #f0f9ff;
          border-left: 4px solid #f59e0b;
          padding: 15px;
          border-radius: 4px;
        }
        .summary-card h3 {
          margin: 0 0 10px 0;
          color: #666;
          font-size: 12px;
          text-transform: uppercase;
        }
        .summary-card .value {
          font-size: 24px;
          font-weight: bold;
          color: #333;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          margin: 20px 0;
        }
        th {
          background-color: #f59e0b;
          color: white;
          padding: 12px;
          text-align: left;
          font-weight: bold;
        }
        td {
          padding: 10px 12px;
          border-bottom: 1px solid #e5e7eb;
        }
        tr:nth-child(even) {
          background-color: #f9fafb;
        }
        tr:hover {
          background-color: #f3f4f6;
        }
        .status-badge {
          display: inline-block;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          font-weight: bold;
        }
        .status-pending {
          background-color: #fef3c7;
          color: #92400e;
        }
        .status-approved {
          background-color: #dbeafe;
          color: #1e40af;
        }
        .status-completed {
          background-color: #dcfce7;
          color: #15803d;
        }
        .status-rejected {
          background-color: #fee2e2;
          color: #991b1b;
        }
        .footer {
          margin-top: 30px;
          padding-top: 20px;
          border-top: 1px solid #e5e7eb;
          color: #666;
          font-size: 12px;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <h1>Withdrawal Audit Report</h1>
        
        <div class="report-info">
          <p><strong>Report ID:</strong> ${report.reportId}</p>
          <p><strong>Generated:</strong> ${report.generatedAt.toLocaleString()}</p>
          <p><strong>Generated By:</strong> Admin #${report.generatedBy}</p>
        </div>

        <h2>Summary</h2>
        <div class="summary-grid">
          <div class="summary-card">
            <h3>Total Withdrawals</h3>
            <div class="value">${report.summary.totalWithdrawals}</div>
          </div>
          <div class="summary-card">
            <h3>Total Amount</h3>
            <div class="value">$${report.summary.totalAmount.toLocaleString("en-US", { maximumFractionDigits: 2 })}</div>
          </div>
          <div class="summary-card">
            <h3>Total Fees</h3>
            <div class="value">$${report.summary.totalFees.toLocaleString("en-US", { maximumFractionDigits: 2 })}</div>
          </div>
          <div class="summary-card">
            <h3>Net Amount</h3>
            <div class="value">$${report.summary.netAmount.toLocaleString("en-US", { maximumFractionDigits: 2 })}</div>
          </div>
          <div class="summary-card">
            <h3>Average Amount</h3>
            <div class="value">$${report.summary.averageWithdrawalAmount.toLocaleString("en-US", { maximumFractionDigits: 2 })}</div>
          </div>
          <div class="summary-card">
            <h3>Median Amount</h3>
            <div class="value">$${report.summary.medianWithdrawalAmount.toLocaleString("en-US", { maximumFractionDigits: 2 })}</div>
          </div>
        </div>

        <h2>Withdrawal Details</h2>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Player</th>
              <th>Amount</th>
              <th>Method</th>
              <th>Status</th>
              <th>Requested</th>
              <th>Completed</th>
            </tr>
          </thead>
          <tbody>
            ${report.details
              .map(
                (w) => `
              <tr>
                <td>${w.id}</td>
                <td>${w.playerName}<br><small>${w.playerEmail}</small></td>
                <td>${w.amount} ${w.currency}</td>
                <td>${w.method}</td>
                <td><span class="status-badge status-${w.status}">${w.status}</span></td>
                <td>${w.requestedAt.toLocaleDateString()}</td>
                <td>${w.completedAt ? w.completedAt.toLocaleDateString() : "N/A"}</td>
              </tr>
            `
              )
              .join("")}
          </tbody>
        </table>

        <div class="footer">
          <p>This report was automatically generated by CoinKrazy Admin System.</p>
          <p>For questions or concerns, please contact the admin support team.</p>
        </div>
      </div>
    </body>
    </html>
  `;

  return html;
}

/**
 * Generate PDF report (requires external library)
 */
export async function generatePDFReport(report: WithdrawalAuditReport): Promise<Buffer> {
  // This would require a PDF library like pdfkit or puppeteer
  // For now, return a placeholder
  const htmlContent = generateHTMLReport(report);

  // TODO: Use puppeteer or similar to convert HTML to PDF
  return Buffer.from(htmlContent);
}

/**
 * Get report filename
 */
export function getReportFilename(format: "csv" | "json" | "html" | "pdf"): string {
  const date = new Date().toISOString().split("T")[0];
  const timestamp = Date.now();
  return `withdrawal_audit_${date}_${timestamp}.${format}`;
}
