'use client';

import React, { useEffect, useMemo, useState } from 'react';

import 'reactflow/dist/style.css';
import { Loader, SegmentedControl, Skeleton } from '@mantine/core';
import { useQuery } from '@tanstack/react-query';
import { PreviewComponent } from '@/src/components/PreviewComponent/PreviewComponent';
import { CodeComponent } from '@/src/components/CodeComponent/CodeComponent';
import { TestComponent } from '@/src/components/TestComponent/TestComponent';
import { InputManager } from '@/src/components/InputsManager';
import { getEchoHeaders } from '@/src/components/utils';

export default function HomePage({ params }: { params: { workflowId: string; stepId: string } }) {
  const [variableData, setVariableData] = useState<any>({});
  const [loading, setLoading] = useState(true);
  const { isLoading: loadingWorkflow, data: workflow } = useQuery({
    queryKey: ['workflow', params.workflowId],
    queryFn: () =>
      fetch(`/api/workflows/${params.workflowId}`, {
        method: 'GET',
        headers: { ...getEchoHeaders() },
      }).then((res) => res.json()),
  });

  useEffect(() => {
    if (loading) {
      setLoading(false);
    }
  }, [workflow]);
  const { isLoading: loadingPreview, data: preview } = useQuery({
    queryKey: ['preview', params.workflowId, params.stepId, variableData],
    refetchOnWindowFocus: 'always',
    refetchIntervalInBackground: false,
    refetchInterval: 1000,

    queryFn: async ({ queryKey }) => {
      const inputs = queryKey[3];

      return fetch(`/api/workflows/${params.workflowId}/preview/${params.stepId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getEchoHeaders(),
        },
        body: JSON.stringify({
          inputs,
        }),
      })
        .then((res) => res.json())
        .then((res) => res.outputs);
    },
  });

  const [mode, setMode] = useState('Preview');

  async function onSubmit(data: any) {
    setVariableData(data.formData);
  }

  function onVariableModeChange(data: any) {
    setVariableData(data.formData);
  }

  const step = workflow?.steps.find((item) => item.stepId === params.stepId);

  return (
    <div style={{ width: '100%', height: '100vh', display: 'flex' }}>
      <div style={{ padding: 20, width: '100%' }}>
        <div
          style={{
            width: '100%',
            alignItems: 'center',
            display: 'flex',
            justifyContent: 'center',
            marginBottom: 30,
          }}
        >
          <SegmentedControl value={mode} data={['Preview', 'Code', 'Test']} onChange={setMode} />
        </div>

        {mode === 'Preview' ? (
          <PreviewComponent loading={loading} step={step} preview={preview} />
        ) : null}
        {mode === 'Code' ? <CodeComponent code={step.code} format /> : null}
        {mode === 'Test' ? (
          <TestComponent step={step} onSubmit={onSubmit} onChange={onVariableModeChange} />
        ) : null}
      </div>

      <div style={{ width: 350, minWidth: 350, paddingLeft: 30, paddingRight: 30 }}>
        <h2 style={{ marginTop: 25 }}>Step Inputs</h2>

        {loading || !step ? (
          <Skeleton visible style={{ marginBottom: 10 }}>
            <div style={{ height: '440px' }} />
          </Skeleton>
        ) : (
          <InputManager
            schema={step?.inputs?.schema || {}}
            onSubmit={onSubmit}
            onChange={onVariableModeChange}
          />
        )}
      </div>
    </div>
  );
}
