import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
import { StrictMode } from "react";
import { useLoaderData } from "@remix-run/react";
import App from "../App";
import { unauthenticated, authenticate } from "../shopify.server";
import { getSocialLoginConfigFromAdmin } from "../lib/shopify-metafields";

export const meta: MetaFunction = () => {
  return [
    { title: "Social Login App" },
    { name: "description", content: "Social Login Application" },
  ];
};

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const platform = url.searchParams.get("platform");
  const shop = url.searchParams.get("shop");

  // 管理画面側の認証コールバック（admin認証が必要）
  if (!platform && !shop) {
    try {
      await authenticate.admin(request);
      return null;
    } catch (error) {
      console.error("管理画面認証エラー:", error);
      return new Response("管理画面の認証に失敗しました", { status: 401 });
    }
  }

  // ソーシャルログインのコールバック処理
  if (
    platform &&
    ["google", "line", "facebook", "twitter", "apple", "instagram", "tiktok"].includes(platform)
  ) {
    return handleSocialLoginCallback(request, platform);
  }

  // 通常のソーシャルログインページの場合
  if (!shop) {
    // shopパラメータがない場合はデフォルトのストアを使用
    const defaultShop = "itbc-dev.myshopify.com";
    console.warn("Missing shop parameter, using default shop:", defaultShop);
    return json({
      config: {
        redirectUri: "",
        facebook: { enabled: false, appId: "", appSecret: "" },
        x: { enabled: false, appId: "", clientId: "", clientSecret: "" },
        google: { enabled: false, clientId: "" },
        line: { enabled: false, liffId: "", channelId: "", channelSecret: "" },
        instagram: { enabled: false, appId: "", appSecret: "" },
        apple: { enabled: false, clientId: "" },
        tiktok: { enabled: false, clientKey: "", clientSecret: "" },
      },
      platform,
      shop: defaultShop,
    });
  }

  try {
    const { admin } = await unauthenticated.admin(shop);
    const config = await getSocialLoginConfigFromAdmin(admin);
    return json({ config, platform, shop });
  } catch (error) {
    console.error("Failed to load config:", error);
    // 設定の読み込みに失敗した場合はデフォルト設定を使用
    const defaultConfig = {
      redirectUri: "",
      facebook: { enabled: false, appId: "", appSecret: "" },
      x: { enabled: false, appId: "", clientId: "", clientSecret: "" },
      google: { enabled: false, clientId: "" },
      line: { enabled: false, liffId: "", channelId: "", channelSecret: "" },
      instagram: { enabled: false, appId: "", appSecret: "" },
      apple: { enabled: false, clientId: "" },
      tiktok: { enabled: false, clientKey: "", clientSecret: "" },
    };
    return json({ config: defaultConfig, platform, shop });
  }
};

export const action = async (args: LoaderFunctionArgs) => {
  // POSTリクエストにも対応
  return loader(args);
};

export default function SocialIndex() {
  const data = useLoaderData<typeof loader>();

  // コールバック処理の場合や管理画面認証の場合はHTMLレスポンスが返されるため、そのまま返す
  if (!data || data instanceof Response) {
    return null;
  }

  const { config, platform, shop } = data;

  return (
    <StrictMode>
      <App initialConfig={config} platform={platform} shop={shop} />
    </StrictMode>
  );
}

async function handleSocialLoginCallback(request: Request, platform: string) {
  return new Response(
    `
    <!DOCTYPE html>
    <html lang="ja">
      <head>
        <meta charSet="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>${platform}認証完了</title>
        <style>
          body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          .container {
            background: white;
            padding: 2rem;
            border-radius: 1rem;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 400px;
          }
          .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4285f4;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
          .error {
            color: #d32f2f;
            background: #ffebee;
            padding: 1rem;
            border-radius: 0.5rem;
            margin: 1rem 0;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="spinner"></div>
          <h2>認証処理中...</h2>
          <p>しばらくお待ちください</p>
          <div id="error" class="error" style="display: none;"></div>
        </div>

        <script>
          (function() {
            const urlParams = new URLSearchParams(window.location.search);
            const code = urlParams.get('code');
            const error = urlParams.get('error');
            const errorDescription = urlParams.get('error_description');

            if (error) {
              document.getElementById('error').style.display = 'block';
              document.getElementById('error').textContent = errorDescription || error;
              document.querySelector('.spinner').style.display = 'none';
              document.querySelector('h2').textContent = '認証エラー';
              document.querySelector('p').textContent = '認証に失敗しました。';

              // エラーを親ウィンドウに送信
              if (window.opener) {
                window.opener.postMessage({
                  error: errorDescription || error,
                  type: 'auth_error'
                }, window.location.origin);
              }

              setTimeout(() => {
                window.close();
              }, 3000);
            } else if (code) {
              // 認証コードを親ウィンドウに送信
              if (window.opener) {
                window.opener.postMessage({
                  code: code,
                  type: 'auth_complete'
                }, window.location.origin);
              }

              // 少し待ってからウィンドウを閉じる
              setTimeout(() => {
                window.close();
              }, 1000);
            } else {
              document.getElementById('error').style.display = 'block';
              document.getElementById('error').textContent = '認証コードが取得できませんでした。';
              document.querySelector('.spinner').style.display = 'none';
              document.querySelector('h2').textContent = '認証エラー';
              document.querySelector('p').textContent = '認証に失敗しました。';

              setTimeout(() => {
                window.close();
              }, 3000);
            }
          })();
        </script>
      </body>
    </html>
  `,
    {
      headers: {
        "Content-Type": "text/html",
      },
    }
  );
}

