import { useAppBridge } from "@saleor/app-sdk/app-bridge";
import { Box, Text, Button, CircularProgress } from "@saleor/macaw-ui";
import { NextPage } from "next";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";

const IndexPage: NextPage = () => {
  const { appBridgeState } = useAppBridge();
  const router = useRouter();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    // If inside Saleor Dashboard, redirect to dashboard
    if (appBridgeState?.ready) {
      router.push("/dashboard");
    }
  }, [appBridgeState?.ready, router]);

  if (!mounted) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
        <CircularProgress />
      </Box>
    );
  }

  // If inside Saleor Dashboard, show loading while redirecting
  if (appBridgeState?.ready) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
        <CircularProgress />
      </Box>
    );
  }

  // Standalone landing page
  return (
    <Box padding={8} maxWidth={800} margin="0 auto">
      <Text size={11} as="h1" marginBottom={4}>
        Core Extensions
      </Text>
      <Text size={6} color="textSecondary" marginBottom={8}>
        Email automation for ManoonOils
      </Text>

      <Box 
        as="div" 
        backgroundColor="surfaceNeutralPlain" 
        padding={8} 
        borderRadius={4}
        marginBottom={8}
      >
        <Text size={7} marginBottom={4}>
          Features
        </Text>
        <Box as="ul" display="flex" flexDirection="column" gap={2}>
          <li>✉️ Automated order confirmation emails</li>
          <li>📦 Shipping notification emails</li>
          <li>❌ Order cancellation emails</li>
          <li>🔔 Admin notifications for all orders</li>
          <li>🎨 Styled HTML email templates</li>
        </Box>
      </Box>

      <Box display="flex" flexDirection="column" gap={4}>
        <Text>
          This app connects Saleor to N8N for automated email workflows using Resend.
        </Text>

        <Box display="flex" gap={4} marginTop={4}>
          <Button
            variant="primary"
            onClick={() => {
              window.open("https://dashboard.manoonoils.com/apps", "_blank");
            }}
          >
            Open in Saleor Dashboard
          </Button>
          
          <Button
            variant="secondary"
            onClick={() => {
              router.push("/dashboard");
            }}
          >
            View Dashboard
          </Button>
        </Box>
      </Box>
    </Box>
  );
};

export default IndexPage;
