import { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import { useGlobal } from 'hooks/useGlobal';
import { useIsMobile } from 'hooks/useIsMobile';
import { useDashboardState } from 'state/useDashboardState';
import type { LayoutNode, ProjectType } from 'officerdev';
import {
  WorkspaceView,
  SELECTED_PROJECT,
  CREATING_PROJECT,
  EDITING_PROJECT,
  NEW_PROJ_NAME,
  NEW_PROJ_DESC,
  NEW_PROJ_TEMPLATE,
  NEW_PROJ_TYPE,
  NEW_PROJ_HAS_BACKEND,
  NEW_PROJ_HAS_AUTH,
} from 'officerdev';
import { generateSlug } from 'helpers/slug';
import { defaultLayout } from './defaultLayout';

export const ProjectListScreen = () => {
  const workspace = useDashboardState<LayoutNode>('screens/projects', defaultLayout);
  const isMobile = useIsMobile();
  const [selected, setSelected] = useGlobal<string | null>(SELECTED_PROJECT, null);
  const [creating] = useGlobal<boolean>(CREATING_PROJECT, false);
  const mobilePanelId = isMobile && (selected || creating) ? 'proj-home-right' : undefined;

  return (
    <div className="h-full w-full">
      <WorkspaceView
        workspace={workspace}
        locked
        mobilePanelId={mobilePanelId}
        onMobilePanelChange={(id) => {
          if (!id) setSelected(null);
        }}
      />
    </div>
  );
};

export const NewProjectRedirect = () => {
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const [, setName] = useGlobal<string>(NEW_PROJ_NAME, '');
  const [, setDescription] = useGlobal<string>(NEW_PROJ_DESC, '');
  const [, setTemplateIdx] = useGlobal<number>(NEW_PROJ_TEMPLATE, 0);
  const [, setCreating] = useGlobal<boolean>(CREATING_PROJECT, false);
  const [, setEditing] = useGlobal<string | null>(EDITING_PROJECT, null);
  const [, setSelected] = useGlobal<string | null>(SELECTED_PROJECT, null);
  const [, setProjectType] = useGlobal<ProjectType>(NEW_PROJ_TYPE, 'app');
  const [, setHasBackend] = useGlobal<boolean>(NEW_PROJ_HAS_BACKEND, false);
  const [, setHasAuth] = useGlobal<boolean>(NEW_PROJ_HAS_AUTH, false);

  useEffect(() => {
    setSelected(null);
    setEditing(null);
    setName(params.get('name') || generateSlug());
    setDescription('');
    setTemplateIdx(0);
    setProjectType('app');
    setHasBackend(false);
    setHasAuth(false);
    setCreating(true);
    navigate('/projects', { replace: true });
  }, []);

  return null;
};
