'use client';
import React, { useEffect, useState } from 'react';
import { Button } from 'antd';
import { useRouter } from 'next/navigation';
import LaunchPage from './components/Launch';
import ProjectPage from './components/Project';
import { hasPermission } from '@/utills/helper';
import { PERMISSIONS } from '@/utills/constant';
import { PlusOutlined } from '@ant-design/icons';

import { useSession } from 'next-auth/react';
import SwitchComponent from '../../components/form/Switch/index';
import { useSearchParams } from 'next/navigation';

const IndexPage: React.FC = () => {
  const searchParams = useSearchParams();
  const showProjectsParam = searchParams.get('Projects');
  const [showProjects, setShowProjects] = useState(showProjectsParam === '1');
  const router = useRouter();

  const { data: session } = useSession();
  const user = session?.user;
  const isProjectEditable = hasPermission(user, PERMISSIONS.PROJECT_CREATE.name);
  const isLaunchEditable = hasPermission(user, PERMISSIONS.LAUNCH_CREATE.name);

  useEffect(() => {
    setShowProjects(showProjectsParam === '1');
  }, [showProjectsParam]);

  const handleSwitchChange = (checked: boolean): void => {
    setShowProjects(checked);
    const queryParamValue = checked ? '1' : '0';
    router.push(`/launches?Projects=${queryParamValue}`);
  };

  return (
    <div>
      <div className="launches-header">
        <div className="launches-header-left">
          <h1>Launches</h1>
          {hasPermission(user, PERMISSIONS.PROJECT_VIEW.name) && (
            <>
              <SwitchComponent
                checkedChildren="Projects"
                unCheckedChildren="Launches"
                checked={showProjects}
                onChange={handleSwitchChange}
                defaultChecked={false}
              />
              <h1>Projects</h1>
            </>
          )}
        </div>
        <div className="launches-header-right">
          {isLaunchEditable && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                router.push('/launches/add-launch');
              }}>
                            Create New Launch
            </Button>
          )}
          {/* {isProjectEditable && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                router.push('/launches/add-projects');
              }}>
                            Create New Project
            </Button>
          )} */}
        </div>
      </div>
      {showProjects ? (
        <ProjectPage key="projects" isEditable={isProjectEditable} />
      ) : (
        <LaunchPage key="launches" isEditable={isLaunchEditable} />
      )}
    </div>
  );
};

export default IndexPage;
