import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";

export async function loader() {
  try {
    const response = await fetch("http://localhost:8000/api/pm3/commands/history?limit=50");
    const data = await response.json();
    return json({ history: data.history || [] });
  } catch (error) {
    // Return mock data if backend unavailable
    return json({
      history: [
        {
          id: 1,
          command: "hw version",
          success: true,
          executed_at: new Date().toISOString(),
        },
        {
          id: 2,
          command: "hw status",
          success: true,
          executed_at: new Date(Date.now() - 300000).toISOString(),
        },
      ],
    });
  }
}

export default function Logs() {
  const { history } = useLoaderData<typeof loader>();

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat("en-US", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    }).format(date);
  };

  return (
    <div className="container">
      <h1 style={{ marginBottom: "var(--space-6)" }}>
        <span style={{ color: "var(--color-info)" }}>≡</span> Command Logs
      </h1>

      <div className="card">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-4)" }}>
          <h3 className="card-title" style={{ marginBottom: 0 }}>
            Command History
          </h3>
          <div style={{ display: "flex", gap: "var(--space-2)" }}>
            <button className="btn btn-secondary" disabled>
              <span>⬇</span>
              <span>Export CSV</span>
            </button>
            <button className="btn btn-danger" disabled>
              <span>🗑</span>
              <span>Clear</span>
            </button>
          </div>
        </div>

        {history.length === 0 ? (
          <div className="terminal" style={{ textAlign: "center", color: "var(--color-text-muted)" }}>
            <p>No command history yet.</p>
            <p style={{ fontSize: "0.875rem", marginTop: "var(--space-2)" }}>
              Execute commands from the{" "}
              <a href="/commands">Commands page</a>{" "}
              to see them here.
            </p>
          </div>
        ) : (
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse" }}>
              <thead>
                <tr style={{ borderBottom: "1px solid var(--color-border)" }}>
                  <th style={{ padding: "var(--space-3)", textAlign: "left", color: "var(--color-text-secondary)", fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em" }}>
                    Time
                  </th>
                  <th style={{ padding: "var(--space-3)", textAlign: "left", color: "var(--color-text-secondary)", fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em" }}>
                    Command
                  </th>
                  <th style={{ padding: "var(--space-3)", textAlign: "left", color: "var(--color-text-secondary)", fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em" }}>
                    Status
                  </th>
                </tr>
              </thead>
              <tbody>
                {history.map((entry: any, idx: number) => (
                  <tr
                    key={entry.id || idx}
                    style={{
                      borderBottom: "1px solid var(--color-border)",
                      transition: "background var(--transition-fast)",
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = "var(--color-surface-hover)";
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = "transparent";
                    }}
                  >
                    <td style={{ padding: "var(--space-3)", fontSize: "0.875rem", color: "var(--color-text-secondary)", fontFamily: "var(--font-mono)" }}>
                      {formatDate(entry.executed_at)}
                    </td>
                    <td style={{ padding: "var(--space-3)", fontFamily: "var(--font-mono)", fontSize: "0.875rem" }}>
                      <code style={{ color: "var(--color-accent)" }}>
                        {entry.command}
                      </code>
                    </td>
                    <td style={{ padding: "var(--space-3)" }}>
                      <span className={`badge ${entry.success ? "badge-success" : "badge-error"}`}>
                        <span aria-hidden="true">{entry.success ? "✓" : "✗"}</span>
                        {entry.success ? "Success" : "Failed"}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {history.length > 0 && (
          <div style={{ marginTop: "var(--space-4)", textAlign: "center", color: "var(--color-text-muted)", fontSize: "0.875rem" }}>
            Showing {history.length} recent commands
          </div>
        )}
      </div>

      <div className="card" style={{ marginTop: "var(--space-4)" }}>
        <h3 className="card-title">System Logs</h3>
        <p className="text-muted">System log viewing will be available in a future update.</p>
        <button className="btn btn-secondary" disabled>
          <span>📄</span>
          <span>View System Logs</span>
        </button>
      </div>
    </div>
  );
}
