'use client';

import '@mantine/code-highlight/styles.css';

import {
  Badge,
  Button,
  Card,
  Code,
  Container,
  Group,
  Image,
  Tooltip,
  Stepper,
  Text,
  Input,
  Divider,
  Loader,
  Tabs,
  rem,
} from '@mantine/core';
import { useEffect, useState } from 'react';
import { CodeHighlightTabs } from '@mantine/code-highlight';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useLocalStorage } from '@mantine/hooks';
import Link from 'next/link';
import Confetti from 'react-confetti';
import { getEchoHeaders, setLocalStorageUrl } from '@/src/components/utils';
import { EdgeUrlInput } from '@/src/components/EdgeUrlInput';
import { useSegment } from '@/src/app/segment.provider';
import { IconAtom, IconTerminal2 } from '@tabler/icons-react';
import { useRouter } from 'next/navigation';

export default function HomePage() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<string | null>('automatic');
  const [readyState] = useLocalStorage({ key: 'nvReadyState', defaultValue: '' });

  const { track, setAnonymousId, getAnonymousId } = useSegment();

  const [isEchoUrlValid, setIsEchoUrlValid] = useState(false);
  const [echoUrl, setEchoUrl] = useLocalStorage({ key: 'echo_url', defaultValue: '' });
  const [echoUrlForm, setEchoUrlForm] = useState(echoUrl);
  const [showConffetti, setShowConffetti] = useState(true);
  useEffect(() => {
    if (echoUrl) {
      setEchoUrlForm(echoUrl);
    }
  }, [echoUrl]);

  useEffect(() => {
    track('Install Type Selected', {
      installType: activeTab,
    });
  }, [activeTab]);

  const { isLoading: loadingWorkflows, data: workflows } = useQuery<any[]>({
    queryKey: ['workflows'],
    enabled: !!echoUrl && !!readyState,
    refetchOnWindowFocus: 'always',
    refetchInterval: 1000,
    queryFn: () =>
      fetch('/api/workflows', {
        headers: {
          ...getEchoHeaders(),
        },
      }).then((res) => res.json()),
  });

  useEffect(() => {
    (async () => {
      const cliId = (document.getElementById('cliId-internal') as HTMLInputElement)?.value;
      const currentId = await getAnonymousId();

      if (currentId !== cliId) {
        await setAnonymousId(cliId);
      }

      track('Visit Quick Start Install Page');
    })();
  }, []);

  useEffect(() => {
    if (workflows?.length) {
      track('Quickstart Workflows Loaded');

      setShowConffetti(true);

      setTimeout(() => {
        setShowConffetti(false);
      }, 5000);
    }
  }, [workflows]);

  function onEdgeValidity(isValid: boolean) {
    setIsEchoUrlValid(isValid);

    track('Edge URL Verification', {
      valid: isValid,
    });
  }

  function onUrlChange(urlData: string) {
    setEchoUrlForm(urlData);
    setEchoUrl(urlData);
  }

  const installEchoTabs = [
    { fileName: 'npm', code: 'npm install @novu/echo', language: 'shell' },
    { fileName: 'pnpm', code: 'pnpm install @novu/echo', language: 'shell' },
    { fileName: 'yarn', code: 'yarn install @novu/echo', language: 'shell' },
  ];

  const echoHandlerTabs = [
    {
      fileName: 'app/api/echo/route.ts (NextJS)',
      code: `
import { serve } from "@novu/echo/next";
import { echo } from "../../echo/client";

export const { GET, POST, PUT } = serve({ client: echo });
  
                `,
      language: 'typescript',
    },
    {
      fileName: 'app/api/echo.ts (Express)',
      code: `
import { serve } from "@novu/echo/express";
import { echo } from "../echo/client";

app.use(express.json()); // Required for Echo POST requests
app.use(
  "/api/echo",
  serve({ client: echo })
);
  
                `,
      language: 'typescript',
    },
  ];

  function viewWorkflow(workflow) {
    if (workflow.steps[0].stepId) {
      router.push(`/workflow/${workflow.workflowId}/steps/${workflow.steps[0].stepId}`);
    }
  }

  return (
    <Container size="sm">
      <Card shadow="sm" padding="lg" radius="md" withBorder style={{ marginTop: 15 }}>
        <Card.Section>
          <Image
            src="https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-8.png"
            height={160}
            alt="Norway"
          />
        </Card.Section>

        <Group justify="space-between" mt="md" mb="xs">
          <Text fw={500}>Welcome to Novu Studio</Text>
        </Group>

        <Text size="sm" c="dimmed">
          Novu Studio is a companion app for Novu Echo. It allows you to develop your workflows
          locally, right in your IDE and preview the channel specific content in real-time.
        </Text>

        <Tabs mt={15} value={activeTab} onChange={setActiveTab}>
          <Tabs.List justify="center">
            <Tabs.Tab
              value="automatic"
              leftSection={<IconAtom style={{ width: rem(12), height: rem(12) }} />}
            >
              Automatic
            </Tabs.Tab>
            <Tabs.Tab
              value="manual"
              leftSection={<IconTerminal2 style={{ width: rem(12), height: rem(12) }} />}
            >
              Manual
            </Tabs.Tab>
          </Tabs.List>

          <Tabs.Panel value="automatic">
            <Text style={{ marginTop: 20 }}>
              To get started, you can use the `create-echo-app` with Next.js to create a new
              boilerplate app with Echo.
            </Text>
            <CodeHighlightTabs
              style={{ marginTop: 15 }}
              code={[
                {
                  fileName: 'Shell',
                  code: `npx create-echo-app@latest`,
                  language: 'shell',
                },
              ]}
            />
            <Text style={{ marginTop: 20 }}>After the initial set up, enter the folder</Text>
            <CodeHighlightTabs
              style={{ marginTop: 15 }}
              code={[
                {
                  fileName: 'Shell',
                  code: `cd my-echo-app && npm run dev`,
                  language: 'shell',
                },
              ]}
            />

            <Text style={{ marginTop: 20 }}>
              After successfully running the Echo starter, add the url in the input below, by
              default it will start on port <Code>4000</Code>.
            </Text>
          </Tabs.Panel>

          <Tabs.Panel value="manual">
            <Text style={{ marginTop: 20 }}>
              In your project directory, install the Echo SDK using your package manager.
            </Text>
            <CodeHighlightTabs
              style={{ marginTop: 20 }}
              onTabChange={(index) => {
                track('Install Echo SDK Language', {
                  installer: installEchoTabs[index].fileName,
                });
              }}
              code={installEchoTabs}
            />
            <Divider my="md" />

            <Text style={{ marginTop: 20 }}>
              After installation, create a new instance of Echo and export it from{' '}
              <Code>client.ts</Code>
            </Text>

            <CodeHighlightTabs
              style={{ marginTop: 15 }}
              code={[
                {
                  fileName: 'app/echo/client.ts',
                  code: `
import { Echo } from '@novu/echo';

export const echo = new Echo({
  /**
  * Enable this flag only during local development
  */
  devModeBypassAuthentication: process.env.NODE_ENV === 'development'
});

echo.workflow('hello-world', async ({ step }) => {
  await step.email('send-email', async (inputs) => {
    return {
      subject: "This is an email subject",
      body: "E-mail body of hello " + inputs.world
    }
  }, {
     inputSchema: {
        type: 'object', properties: { world: { type: 'string', default: 'World' }} 
     }
  });
}, { payloadSchema: { type: 'object', properties: {} }});

                `,
                  language: 'typescript',
                },
              ]}
            />

            <Divider my="md" />

            <Text style={{ marginTop: 20 }}>
              Now, we need to expose your workflows via API, so the Novu Worker Engine and Dev
              Studio can communicate with it.
            </Text>

            <CodeHighlightTabs
              style={{ marginTop: 15 }}
              onTabChange={(index) => {
                track('Echo Handler Framework Select', {
                  installer: echoHandlerTabs[index].fileName,
                });
              }}
              code={echoHandlerTabs}
            />
          </Tabs.Panel>
        </Tabs>

        <EdgeUrlInput onEdgeValidity={onEdgeValidity} onUrlChange={onUrlChange} />

        {workflows ? (
          <>
            <Divider mt={15} /> <Confetti numberOfPieces={showConffetti ? 200 : 0} />
            <Text
              style={{ marginTop: 20, marginBottom: 20 }}
              data-testid="success-screen-view-text"
            >
              Amazing! You have created your first workflow:
            </Text>
            {workflows?.map((workflow) => (
              <Link
                data-testid="onboardin-workflow-link"
                href={`/workflow/${workflow.workflowId}`}
                style={{ textDecoration: 'none', color: 'initial' }}
              >
                <Card shadow="sm" padding="sm" radius="md" withBorder mb={10}>
                  <Group justify="space-between">
                    <Text fw={500} data-testid="onboarding-workflow-label">
                      {workflow.workflowId}
                    </Text>
                  </Group>
                </Card>
              </Link>
            ))}
            <Button
              mt={15}
              disabled={!workflows?.length}
              onClick={() => {
                if (workflows?.length) {
                  viewWorkflow(workflows[0]);
                }
              }}
            >
              {!workflows?.length ? 'Waiting for workflows...' : 'View Workflow'}
            </Button>
          </>
        ) : null}
      </Card>
    </Container>
  );
}
