'use client';
import { FormContext } from './context/form-context';
import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid';
import { Background, Button, LoadingSpinner } from '@repo/ui';
import type { PropsWithChildren } from 'react';
import { useContext } from 'react';

function OverlayWrapper({ children }: PropsWithChildren) {
  return (
    <Background className="absolute left-0 top-0 grid h-full w-full place-items-center bg-opacity-80 backdrop-blur-sm">
      <div className="absolute bottom-[50vh] flex flex-col items-center gap-2 md:relative md:bottom-0">
        {children}
      </div>
    </Background>
  );
}

function StateContentWrapper({ children }: PropsWithChildren) {
  return <div className="flex flex-row items-center gap-2">{children}</div>;
}

export function Overlay() {
  const { formState, setFormState } = useContext(FormContext);
  const { status, text } = formState;

  let stateContent: JSX.Element | false = false;

  if (status === 'pending') {
    stateContent = (
      <StateContentWrapper>
        {LoadingSpinner} <p className="font-medium">Загрузка...</p>
      </StateContentWrapper>
    );
  }
  if (status === 'success') {
    stateContent = (
      <StateContentWrapper>
        <CheckCircleIcon className="h-10 w-10 fill-green-500" title="OK" />
        <p className="font-medium">Данные сохранены</p>
      </StateContentWrapper>
    );
  }

  if (status === 'error') {
    stateContent = (
      <>
        <StateContentWrapper>
          <XCircleIcon className="h-10 w-10 fill-red-500" title="Error" />
          <p className="font-medium">{text}</p>
        </StateContentWrapper>{' '}
        <Button type="button" intent="text" onClick={() => setFormState({ status: 'edit' })}>
          Закрыть
        </Button>
      </>
    );
  }

  if (!stateContent) return false;

  return <OverlayWrapper>{stateContent}</OverlayWrapper>;
}
