import { useEffect, useState } from "react";
import {
  getApiActivity,
  getApiActivityStats,
  type ApiRequestEntry,
  type ApiActivityStats,
  type FileUploadInfo,
  type ResponseSummary,
} from "../../api/adminApi";

export default function AdminActivity() {
  const [requests, setRequests] = useState<ApiRequestEntry[]>([]);
  const [stats, setStats] = useState<ApiActivityStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [statsLoading, setStatsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);

  // Expanded row
  const [expandedId, setExpandedId] = useState<number | null>(null);

  // Filters
  const [methodFilter, setMethodFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [pathFilter, setPathFilter] = useState("");
  const [usernameFilter, setUsernameFilter] = useState("");
  const [limit, setLimit] = useState(50);
  const [offset, setOffset] = useState(0);

  // View mode
  const [viewMode, setViewMode] = useState<"list" | "stats">("list");

  useEffect(() => {
    loadActivity();
  }, [methodFilter, statusFilter, pathFilter, usernameFilter, limit, offset]);

  useEffect(() => {
    if (viewMode === "stats") {
      loadStats();
    }
  }, [viewMode]);

  async function loadActivity() {
    setLoading(true);
    setError(null);
    try {
      const data = await getApiActivity({
        method: methodFilter || undefined,
        statusCategory: (statusFilter as "2xx" | "3xx" | "4xx" | "5xx") || undefined,
        path: pathFilter || undefined,
        username: usernameFilter || undefined,
        limit,
        offset,
      });
      setRequests(data.requests);
      setTotal(data.total);
    } catch (err: any) {
      setError(err.message || "Failed to load API activity");
    } finally {
      setLoading(false);
    }
  }

  async function loadStats() {
    setStatsLoading(true);
    try {
      const data = await getApiActivityStats();
      setStats(data.stats);
    } catch (err: any) {
      console.error("Failed to load stats:", err);
    } finally {
      setStatsLoading(false);
    }
  }

  function getMethodColor(method: string): string {
    switch (method.toUpperCase()) {
      case "GET": return "bf-method-get";
      case "POST": return "bf-method-post";
      case "PUT": return "bf-method-put";
      case "DELETE": return "bf-method-delete";
      case "PATCH": return "bf-method-patch";
      default: return "bf-method-default";
    }
  }

  function getStatusColor(status: number | null): string {
    if (!status) return "bf-status-unknown";
    if (status >= 200 && status < 300) return "bf-status-success";
    if (status >= 300 && status < 400) return "bf-status-redirect";
    if (status >= 400 && status < 500) return "bf-status-client-error";
    if (status >= 500) return "bf-status-server-error";
    return "bf-status-unknown";
  }

  function formatResponseTime(ms: number | null): string {
    if (!ms) return "-";
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(2)}s`;
  }

  function formatBytes(bytes: number | null): string {
    if (!bytes) return "-";
    if (bytes < 1024) return `${bytes}B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
  }

  function parseJson<T>(str: string | null): T | null {
    if (!str) return null;
    try {
      return JSON.parse(str) as T;
    } catch {
      return null;
    }
  }

  function toggleExpand(id: number) {
    setExpandedId(expandedId === id ? null : id);
  }

  const totalPages = Math.ceil(total / limit);
  const currentPage = Math.floor(offset / limit) + 1;

  // Render request parameters
  function renderRequestParams(params: Record<string, any> | null) {
    if (!params || Object.keys(params).length === 0) return null;
    return (
      <div className="bf-activity-params">
        <h4>Request Parameters</h4>
        <div className="bf-params-grid">
          {Object.entries(params).map(([key, value]) => (
            <div key={key} className="bf-param-item">
              <span className="bf-param-key">{key}</span>
              <span className="bf-param-value">
                {typeof value === 'object' ? JSON.stringify(value) : String(value)}
              </span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Render file uploads
  function renderFileUploads(files: FileUploadInfo[] | null) {
    if (!files || files.length === 0) return null;
    return (
      <div className="bf-activity-files">
        <h4>File Uploads</h4>
        {files.map((file, idx) => (
          <div key={idx} className="bf-file-item">
            <span className="bf-file-icon">📁</span>
            <div className="bf-file-details">
              <span className="bf-file-name">{file.originalname}</span>
              <span className="bf-file-meta">
                {file.mimetype} • {formatBytes(file.size)}
                {file.filename && <> → <code>{file.filename}</code></>}
              </span>
            </div>
          </div>
        ))}
      </div>
    );
  }

  // Render response summary
  function renderResponseSummary(summary: ResponseSummary | null, statusCode: number | null) {
    if (!summary || Object.keys(summary).length === 0) return null;
    
    return (
      <div className="bf-activity-response">
        <h4>Response Summary</h4>
        <div className="bf-response-items">
          {summary.success !== undefined && (
            <div className={`bf-response-item ${summary.success ? 'bf-res-success' : 'bf-res-error'}`}>
              <span className="bf-res-icon">{summary.success ? '✓' : '✗'}</span>
              <span>{summary.success ? 'Success' : 'Failed'}</span>
            </div>
          )}
          
          {summary.message && (
            <div className="bf-response-item bf-res-message">
              <span className="bf-res-label">Message:</span>
              <span>{summary.message}</span>
            </div>
          )}
          
          {summary.error && (
            <div className="bf-response-item bf-res-error">
              <span className="bf-res-label">Error:</span>
              <span>{summary.error}</span>
            </div>
          )}
          
          {summary.caseId && (
            <div className="bf-response-item">
              <span className="bf-res-label">Case ID:</span>
              <code className="bf-res-code">{summary.caseId}</code>
            </div>
          )}
          
          {summary.status && (
            <div className="bf-response-item">
              <span className="bf-res-label">Status:</span>
              <span className="bf-res-badge">{summary.status}</span>
            </div>
          )}
          
          {summary.tokenGenerated && (
            <div className="bf-response-item bf-res-success">
              <span className="bf-res-icon">🔑</span>
              <span>Auth token generated</span>
            </div>
          )}
          
          {summary.username && (
            <div className="bf-response-item">
              <span className="bf-res-label">User:</span>
              <span>{summary.username}</span>
            </div>
          )}
          
          {summary.rigoType && (
            <div className="bf-response-item bf-res-highlight">
              <span className="bf-res-label">Rigo Type:</span>
              <span className="bf-res-badge bf-rigo-badge">{summary.rigoType}</span>
            </div>
          )}
          
          {summary.cobbAngles && (
            <div className="bf-response-item">
              <span className="bf-res-label">Cobb Angles:</span>
              <span className="bf-cobb-angles">
                {summary.cobbAngles.PT !== undefined && <span>PT: {summary.cobbAngles.PT.toFixed(1)}°</span>}
                {summary.cobbAngles.MT !== undefined && <span>MT: {summary.cobbAngles.MT.toFixed(1)}°</span>}
                {summary.cobbAngles.TL !== undefined && <span>TL: {summary.cobbAngles.TL.toFixed(1)}°</span>}
              </span>
            </div>
          )}
          
          {summary.vertebraeDetected && (
            <div className="bf-response-item">
              <span className="bf-res-label">Vertebrae:</span>
              <span>{summary.vertebraeDetected} detected</span>
            </div>
          )}
          
          {summary.landmarksCount && (
            <div className="bf-response-item">
              <span className="bf-res-label">Landmarks:</span>
              <span>{summary.landmarksCount}</span>
            </div>
          )}
          
          {summary.bracesGenerated && (
            <div className="bf-response-item bf-res-highlight">
              <span className="bf-res-icon">🦴</span>
              <span>Braces: </span>
              {summary.bracesGenerated.regular && <span className="bf-brace-tag regular">Regular</span>}
              {summary.bracesGenerated.vase && <span className="bf-brace-tag vase">Vase</span>}
            </div>
          )}
          
          {summary.braceGenerated && (
            <div className="bf-response-item bf-res-highlight">
              <span className="bf-res-icon">🦴</span>
              <span>Brace generated</span>
              {summary.braceVertices && <span className="bf-res-small">({summary.braceVertices.toLocaleString()} vertices)</span>}
            </div>
          )}
          
          {summary.filesGenerated && summary.filesGenerated.length > 0 && (
            <div className="bf-response-item">
              <span className="bf-res-label">Files:</span>
              <span className="bf-file-tags">
                {summary.filesGenerated.map(f => (
                  <span key={f} className="bf-file-tag">{f}</span>
                ))}
              </span>
            </div>
          )}
          
          {summary.outputUrl && (
            <div className="bf-response-item">
              <span className="bf-res-label">Output:</span>
              <code className="bf-res-code">{summary.outputUrl}</code>
            </div>
          )}
          
          {summary.bodyScanUploaded && (
            <div className="bf-response-item bf-res-success">
              <span className="bf-res-icon">📷</span>
              <span>Body scan uploaded</span>
            </div>
          )}
          
          {summary.measurementsExtracted && (
            <div className="bf-response-item bf-res-success">
              <span className="bf-res-icon">📏</span>
              <span>Measurements extracted</span>
            </div>
          )}
          
          {summary.casesCount !== undefined && (
            <div className="bf-response-item">
              <span className="bf-res-label">Cases:</span>
              <span>{summary.casesCount} returned</span>
            </div>
          )}
          
          {summary.usersCount !== undefined && (
            <div className="bf-response-item">
              <span className="bf-res-label">Users:</span>
              <span>{summary.usersCount} returned</span>
            </div>
          )}
          
          {summary.total !== undefined && !summary.casesCount && !summary.usersCount && (
            <div className="bf-response-item">
              <span className="bf-res-label">Total:</span>
              <span>{summary.total}</span>
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="bf-admin-page">
      <div className="bf-admin-header">
        <div>
          <h1>API Activity</h1>
          <p className="bf-admin-subtitle">
            Track all HTTP API requests made by users
          </p>
        </div>
        <div className="bf-admin-header-actions">
          <div className="bf-admin-view-toggle">
            <button
              className={`bf-toggle-btn ${viewMode === "list" ? "active" : ""}`}
              onClick={() => setViewMode("list")}
            >
              Request Log
            </button>
            <button
              className={`bf-toggle-btn ${viewMode === "stats" ? "active" : ""}`}
              onClick={() => setViewMode("stats")}
            >
              Statistics
            </button>
          </div>
          <button className="btn" onClick={loadActivity} disabled={loading}>
            Refresh
          </button>
        </div>
      </div>

      {viewMode === "stats" ? (
        // Statistics View
        <div className="bf-admin-stats-section">
          {statsLoading ? (
            <div className="bf-admin-loading">Loading statistics...</div>
          ) : stats ? (
            <>
              {/* Summary Cards */}
              <div className="bf-admin-stats-grid">
                <div className="bf-admin-stat-card">
                  <div className="bf-admin-stat-value">{stats.total.toLocaleString()}</div>
                  <div className="bf-admin-stat-label">Total Requests</div>
                </div>
                <div className="bf-admin-stat-card">
                  <div className="bf-admin-stat-value">{stats.responseTime.avg}ms</div>
                  <div className="bf-admin-stat-label">Avg Response Time</div>
                </div>
                <div className="bf-admin-stat-card bf-stat-warning">
                  <div className="bf-admin-stat-value">{stats.errorRate}%</div>
                  <div className="bf-admin-stat-label">Error Rate</div>
                </div>
                <div className="bf-admin-stat-card">
                  <div className="bf-admin-stat-value">{stats.topUsers.length}</div>
                  <div className="bf-admin-stat-label">Active Users</div>
                </div>
              </div>

              {/* Method Distribution */}
              <div className="bf-admin-card">
                <h3>Requests by Method</h3>
                <div className="bf-admin-method-distribution">
                  {Object.entries(stats.byMethod).map(([method, count]) => (
                    <div key={method} className="bf-method-bar-container">
                      <span className={`bf-method-label ${getMethodColor(method)}`}>
                        {method}
                      </span>
                      <div className="bf-method-bar-wrapper">
                        <div
                          className={`bf-method-bar ${getMethodColor(method)}`}
                          style={{
                            width: `${(count / stats.total) * 100}%`,
                          }}
                        />
                      </div>
                      <span className="bf-method-count">{count.toLocaleString()}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Status Distribution */}
              <div className="bf-admin-card">
                <h3>Requests by Status</h3>
                <div className="bf-admin-status-distribution">
                  {Object.entries(stats.byStatusCategory).map(([category, count]) => (
                    <div key={category} className="bf-status-item">
                      <span className={`bf-status-label ${
                        category.includes("2xx") ? "bf-status-success" :
                        category.includes("4xx") ? "bf-status-client-error" :
                        category.includes("5xx") ? "bf-status-server-error" :
                        "bf-status-redirect"
                      }`}>
                        {category}
                      </span>
                      <span className="bf-status-count">{count.toLocaleString()}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Top Endpoints */}
              <div className="bf-admin-card">
                <h3>Top Endpoints</h3>
                <table className="bf-admin-table">
                  <thead>
                    <tr>
                      <th>Method</th>
                      <th>Path</th>
                      <th>Requests</th>
                      <th>Avg Time</th>
                    </tr>
                  </thead>
                  <tbody>
                    {stats.topEndpoints.slice(0, 10).map((endpoint, idx) => (
                      <tr key={idx}>
                        <td>
                          <span className={`bf-method-badge ${getMethodColor(endpoint.method)}`}>
                            {endpoint.method}
                          </span>
                        </td>
                        <td className="bf-endpoint-path">{endpoint.path}</td>
                        <td>{endpoint.count.toLocaleString()}</td>
                        <td>{Math.round(endpoint.avg_response_time || 0)}ms</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Top Users */}
              <div className="bf-admin-card">
                <h3>Most Active Users</h3>
                <table className="bf-admin-table">
                  <thead>
                    <tr>
                      <th>User</th>
                      <th>Requests</th>
                    </tr>
                  </thead>
                  <tbody>
                    {stats.topUsers.map((user, idx) => (
                      <tr key={idx}>
                        <td>{user.username || "Anonymous"}</td>
                        <td>{user.count.toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          ) : (
            <div className="bf-admin-empty-state">
              <p>No statistics available</p>
            </div>
          )}
        </div>
      ) : (
        // List View
        <>
          {/* Filters */}
          <div className="bf-admin-filters">
            <select
              value={methodFilter}
              onChange={(e) => { setMethodFilter(e.target.value); setOffset(0); }}
              className="bf-admin-filter-select"
            >
              <option value="">All Methods</option>
              <option value="GET">GET</option>
              <option value="POST">POST</option>
              <option value="PUT">PUT</option>
              <option value="DELETE">DELETE</option>
              <option value="PATCH">PATCH</option>
            </select>

            <select
              value={statusFilter}
              onChange={(e) => { setStatusFilter(e.target.value); setOffset(0); }}
              className="bf-admin-filter-select"
            >
              <option value="">All Status</option>
              <option value="2xx">2xx Success</option>
              <option value="3xx">3xx Redirect</option>
              <option value="4xx">4xx Client Error</option>
              <option value="5xx">5xx Server Error</option>
            </select>

            <input
              type="text"
              placeholder="Filter by path..."
              value={pathFilter}
              onChange={(e) => { setPathFilter(e.target.value); setOffset(0); }}
              className="bf-admin-filter-input"
            />

            <input
              type="text"
              placeholder="Filter by user..."
              value={usernameFilter}
              onChange={(e) => { setUsernameFilter(e.target.value); setOffset(0); }}
              className="bf-admin-filter-input"
            />

            <select
              value={limit}
              onChange={(e) => { setLimit(parseInt(e.target.value)); setOffset(0); }}
              className="bf-admin-filter-select"
            >
              <option value="25">25 per page</option>
              <option value="50">50 per page</option>
              <option value="100">100 per page</option>
            </select>
          </div>

          {error && <div className="bf-admin-error">{error}</div>}

          {loading ? (
            <div className="bf-admin-loading">Loading API activity...</div>
          ) : requests.length > 0 ? (
            <>
              <div className="bf-admin-card">
                <div className="bf-activity-list">
                  {requests.map((req) => {
                    const queryParams = parseJson<Record<string, any>>(req.query_params);
                    const requestParams = parseJson<Record<string, any>>(req.request_params);
                    const fileUploads = parseJson<FileUploadInfo[]>(req.file_uploads);
                    const responseSummary = parseJson<ResponseSummary>(req.response_summary);
                    const isExpanded = expandedId === req.id;
                    const hasDetails = requestParams || fileUploads || responseSummary || queryParams;
                    
                    return (
                      <div 
                        key={req.id} 
                        className={`bf-activity-row ${isExpanded ? 'expanded' : ''} ${hasDetails ? 'has-details' : ''}`}
                      >
                        <div 
                          className="bf-activity-main"
                          onClick={() => hasDetails && toggleExpand(req.id)}
                        >
                          <div className="bf-activity-left">
                            <span className={`bf-method-badge ${getMethodColor(req.method)}`}>
                              {req.method}
                            </span>
                            <span className="bf-activity-path">
                              {req.path}
                              {queryParams && Object.keys(queryParams).length > 0 && (
                                <span className="bf-query-indicator" title={JSON.stringify(queryParams, null, 2)}>
                                  ?{Object.keys(queryParams).length}
                                </span>
                              )}
                            </span>
                          </div>
                          <div className="bf-activity-center">
                            <span className="bf-activity-user">
                              {req.username || <span className="bf-anonymous">anonymous</span>}
                            </span>
                            <span className={`bf-status-badge ${getStatusColor(req.status_code)}`}>
                              {req.status_code || "-"}
                            </span>
                            <span className="bf-activity-time-value">
                              {formatResponseTime(req.response_time_ms)}
                            </span>
                          </div>
                          <div className="bf-activity-right">
                            <span className="bf-activity-timestamp">
                              {new Date(req.created_at).toLocaleString()}
                            </span>
                            {hasDetails && (
                              <span className={`bf-expand-icon ${isExpanded ? 'expanded' : ''}`}>
                                ▼
                              </span>
                            )}
                          </div>
                        </div>
                        
                        {isExpanded && hasDetails && (
                          <div className="bf-activity-details">
                            {queryParams && Object.keys(queryParams).length > 0 && (
                              <div className="bf-activity-params">
                                <h4>Query Parameters</h4>
                                <div className="bf-params-grid">
                                  {Object.entries(queryParams).map(([key, value]) => (
                                    <div key={key} className="bf-param-item">
                                      <span className="bf-param-key">{key}</span>
                                      <span className="bf-param-value">{String(value)}</span>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                            
                            {renderRequestParams(requestParams)}
                            {renderFileUploads(fileUploads)}
                            {renderResponseSummary(responseSummary, req.status_code)}
                            
                            <div className="bf-activity-meta-details">
                              <span>IP: {req.ip_address || 'unknown'}</span>
                              <span>Request: {formatBytes(req.request_body_size)}</span>
                              <span>Response: {formatBytes(req.response_body_size)}</span>
                            </div>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Pagination */}
              <div className="bf-admin-pagination">
                <span className="bf-pagination-info">
                  Showing {offset + 1} - {Math.min(offset + limit, total)} of {total.toLocaleString()} requests
                </span>
                <div className="bf-pagination-controls">
                  <button
                    className="bf-pagination-btn"
                    disabled={offset === 0}
                    onClick={() => setOffset(Math.max(0, offset - limit))}
                  >
                    Previous
                  </button>
                  <span className="bf-pagination-page">
                    Page {currentPage} of {totalPages}
                  </span>
                  <button
                    className="bf-pagination-btn"
                    disabled={offset + limit >= total}
                    onClick={() => setOffset(offset + limit)}
                  >
                    Next
                  </button>
                </div>
              </div>
            </>
          ) : (
            <div className="bf-admin-empty-state">
              <p>No API activity recorded yet</p>
              <p className="bf-admin-empty-hint">
                API requests will appear here as users interact with the system
              </p>
            </div>
          )}
        </>
      )}
    </div>
  );
}
