import { json } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { useLoaderData, Form, Link } from "@remix-run/react";
import { requireUserSession } from "~/lib/session.server";
import { githubApp } from "~/lib/github-app.server";

export async function loader({ request }: LoaderFunctionArgs) {
  const userSession = await requireUserSession(request);
  
  // Get additional user auth info from our store
  const userAuth = githubApp.getUserAuth(userSession.login);
  
  return json({
    user: userSession,
    userAuth,
    allAuths: githubApp.getAllUserAuths(), // For debugging
  });
}

export default function Dashboard() {
  const { user, userAuth, allAuths } = useLoaderData<typeof loader>();

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        <div className="bg-white rounded-lg shadow-md p-6">
          <div className="flex items-center justify-between mb-6">
            <h1 className="text-2xl font-bold text-gray-900">
              GitHub App Dashboard
            </h1>
            <Form method="post" action="/auth/logout">
              <button
                type="submit"
                className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium"
              >
                Logout
              </button>
            </Form>
          </div>

          <div className="grid md:grid-cols-2 gap-6">
            {/* User Info */}
            <div className="bg-gray-50 rounded-lg p-4">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">
                User Information
              </h2>
              <div className="flex items-center mb-4">
                {user.avatar_url && (
                  <img
                    src={user.avatar_url}
                    alt={user.login}
                    className="w-12 h-12 rounded-full mr-4"
                  />
                )}
                <div>
                  <p className="font-medium text-gray-900">{user.name || user.login}</p>
                  <p className="text-gray-600">@{user.login}</p>
                  {user.email && (
                    <p className="text-gray-600 text-sm">{user.email}</p>
                  )}
                </div>
              </div>
            </div>

            {/* Auth Info */}
            <div className="bg-gray-50 rounded-lg p-4">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">
                Authentication Status
              </h2>
              <div className="space-y-2">
                <p className="text-sm">
                  <span className="font-medium">Status:</span>{' '}
                  <span className="text-green-600">✅ Authenticated</span>
                </p>
                <p className="text-sm">
                  <span className="font-medium">User ID:</span> {user.userId}
                </p>
                {userAuth && (
                  <>
                    <p className="text-sm">
                      <span className="font-medium">Authenticated At:</span>{' '}
                      {new Date(userAuth.authenticated_at).toLocaleString()}
                    </p>
                    {userAuth.state && (
                      <p className="text-sm">
                        <span className="font-medium">State:</span> {userAuth.state}
                      </p>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>

          {/* Debug Info */}
          <div className="mt-8 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <h3 className="text-lg font-semibold text-yellow-800 mb-2">
              Debug Information
            </h3>
            <p className="text-sm text-yellow-700 mb-2">
              All authenticated users ({allAuths.length}):
            </p>
            <div className="bg-white rounded border p-3 max-h-48 overflow-y-auto">
              <pre className="text-xs text-gray-600">
                {JSON.stringify(allAuths, null, 2)}
              </pre>
            </div>
          </div>

          {/* Usage Instructions */}
          <div className="mt-8 bg-blue-50 border border-blue-200 rounded-lg p-4">
            <h3 className="text-lg font-semibold text-blue-800 mb-2">
              Next Steps
            </h3>
            <div className="text-sm text-blue-700 space-y-2">
              <p>✅ User authentication is working!</p>
              <p>
                🔧 Now you can use the authenticated user identity when GitHub
                triggers your app webhooks
              </p>
              <p>
                📝 The user's authentication info is stored and can be retrieved
                using: <code className="bg-blue-100 px-1 rounded">githubApp.getUserAuth('{user.login}')</code>
              </p>
              <p>
                🔗 You can create an authenticated Octokit instance using:{' '}
                <code className="bg-blue-100 px-1 rounded">githubApp.getUserOctokit('{user.login}')</code>
              </p>
              <div className="mt-4">
                <Link
                  to="/install"
                  className="inline-flex items-center px-4 py-2 border border-blue-300 text-sm font-medium rounded-md text-blue-700 bg-white hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  📦 Install GitHub App on Repositories
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
