'use client';

import React, { useEffect, useMemo, useState } from 'react';
import ReactFlow, { Background, BackgroundVariant } from 'reactflow';

import 'reactflow/dist/style.css';
import { useQuery } from '@tanstack/react-query';
import { Loader } from '@mantine/core';
import { NodeStep } from '@/src/components/Node/Node';
import { getEchoHeaders } from '@/src/components/utils';

const initialEdges = [{ id: 'e1-2', source: '1', target: '2' }];

export default function HomePage({ params }: { params: { workflowId: string } }) {
  const { isLoading, data: workflow } = useQuery({
    queryKey: ['workflow', params.workflowId],
    queryFn: () =>
      fetch(`/api/workflows/${params.workflowId}`, {
        headers: {
          ...getEchoHeaders(),
        },
      }).then((res) => res.json()),
  });
  const nodeTypes = useMemo(() => ({ textUpdater: NodeStep }), []);

  const initialNodes = workflow?.steps.map((step, i) => ({
    id: step.stepId,
    type: 'textUpdater',
    position: { x: 0, y: 0 + i * 70 },
    data: { ...step, workflow },
  })) || [
    {
      id: 'loader-1',
      type: 'textUpdater',
      position: { x: 0, y: 100 },
      data: {},
    },
    {
      id: 'loader-2',
      type: 'textUpdater',
      position: { x: 0, y: 180 },
      data: {},
    },
    {
      id: 'loader-3',
      type: 'textUpdater',
      position: { x: 0, y: 260 },
      data: {},
    },
  ];

  return (
    <div style={{ width: '100%', height: '100vh' }}>
      <ReactFlow nodeTypes={nodeTypes} fitView nodes={initialNodes} edges={initialEdges}>
        <Background size={1} gap={10} variant={BackgroundVariant.Dots} color="#13131A" />
      </ReactFlow>
    </div>
  );
}
