'use client';

import Container from '@mui/material/Container';
import { useSearchParams } from 'next/navigation'; // Use this for query parameters
import { useEffect, useState } from 'react';
import axios from 'axios';

import { paths } from '@/routes/paths';
import { useSettingsContext } from '@/shared/components/settings';
import CustomBreadcrumbs from '@/shared/components/custom-breadcrumbs';
import RewardNewEditForm from './reward-new-edit-form';
import axiosInstancee from '@/utils/axios';
import { IRewardItem } from '@/contexts/types/reward';

// ----------------------------------------------------------------------

type Props = {
  currentReward?: IRewardItem | null;
};

export default function RewardCreateView() {
  const settings = useSettingsContext();
  const searchParams = useSearchParams(); // Access search parameters
  const id = searchParams.get('id'); // Extract 'id' from the query parameters

  const [currentReward, setCurrentReward] = useState<IRewardItem | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchReward = async () => {
      if (id) {
        setLoading(true);
        try {
          const response = await axiosInstancee.get(`/api/projects/rewards/${id}`);
          setCurrentReward(response.data); // Set the fetched reward data
        } catch (error: unknown) {
          console.error('Error fetching reward:', error instanceof Error ? error.message : 'Unknown error');
        } finally {
          setLoading(false);
        }
      }
    };

    fetchReward();
  }, [id]);

  // Render loading or the form
  if (loading) {
    return <div>Loading...</div>; // Replace with a proper loading spinner if necessary
  }

  return (
    <Container maxWidth={settings.themeStretch ? false : 'lg'}>
      <CustomBreadcrumbs
        heading={currentReward ? 'Edit Reward' : 'Create a new reward'} // Dynamically update heading
        links={[
          {
            name: 'Dashboard',
            href: paths.dashboard.root,
          },
          {
            name: 'Reward',
            href: paths.dashboard.rewards.root,
          },
          { name: currentReward ? 'Edit reward' : 'New reward' }, // Dynamically update breadcrumb
        ]}
        sx={{
          mb: { xs: 3, md: 5 },
        }}
      />

      {/* Pass `currentReward` as a prop to RewardNewEditForm */}
      <RewardNewEditForm currentReward={currentReward} />
    </Container>
  );
}