'use client';

import * as Yup from 'yup';
import { Controller, useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useMemo, useState, useEffect } from 'react';

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Switch from '@mui/material/Switch';
import Grid from '@mui/material/Unstable_Grid2';
import CardHeader from '@mui/material/CardHeader';
import Typography from '@mui/material/Typography';
import LoadingButton from '@mui/lab/LoadingButton';

import { paths } from '@/routes/paths';

import { useSnackbar } from '@/components/snackbar';

import FormProvider, {
  RHFTextField,
  RHFRadioGroup,
  RHFEditor,
} from '@/shared/components/hook-form';

import { DatePicker } from '@mui/x-date-pickers';
import { LocalizationProvider } from '@/locales';

import axios from 'axios';
import { useRouter } from 'next/navigation';
import axiosInstancee from '@/utils/axios';
import { IRewardItem } from '@/contexts/types/reward';


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

type FormValuesProps = {
  name: string;
  description: string;
  startDate: Date;
  endDate: Date | null;
  rule: string;
  status: string;
};

export default function RewardNewEditForm({ currentReward }: Props) {
  const { enqueueSnackbar } = useSnackbar();
const router = useRouter();
  const [isPublished, setIsPublished] = useState(currentReward?.status === 'Published');

  const RewardSchema = Yup.object().shape({
    name: Yup.string().required('Name is required'),
    description: Yup.string().required('Description is required'),
    startDate: Yup.date().required('Start date is required'),
    endDate: Yup.date().nullable(),
    rule: Yup.string().required('Rule is required'),
    status: Yup.string().required(),
  }) as Yup.ObjectSchema<FormValuesProps>;

  const defaultValues = useMemo(() => ({
    name: currentReward?.title || '',
    description: currentReward?.description || '',
    startDate: currentReward?.startDate
      ? new Date(currentReward.startDate)
      : new Date(), 
    endDate: currentReward?.endDate
      ? new Date(currentReward.endDate)
      : null, 
    rule: currentReward?.rule || 'FIX_THE_THRESHOLD',
    status: currentReward?.status || 'Draft',
  }), [currentReward]);
  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(RewardSchema),
    defaultValues,
  });

  const {
    reset,
    watch,
    setValue,
    control,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  useEffect(() => {
    setValue('status', isPublished ? 'Published' : 'Draft');
  }, [isPublished, setValue]);

  const getUserEmail = () => {
    const user = localStorage.getItem('user');
    if (user) {
      const parsedUser = JSON.parse(user);
      return parsedUser?.email || null;
    }
    return null;
  };

  const createReward = async (data: any) => {
    const userEmail = getUserEmail();
    if (!userEmail) {
      throw new Error('User email not found. Aborting request.');
    }

    const payload = {
      ...data,
      title: data.name,
      responsibleEmail: userEmail,
      status: data.status?.toUpperCase(),
    };

    const response = await axiosInstancee.post('/api/projects/rewards', payload);
    return response.data;
  };

  const updateReward = async (id: number, data: any) => {
    const payload = {
      ...data,
      title: data.name,
      status: data.status?.toUpperCase(),
    };

    const response = await axiosInstancee.put(`/api/projects/rewards/${id}`, payload);
    return response.data;
  };

  const onSubmit = handleSubmit(async (data) => {
    try {
      const apiCall = currentReward
        ? () => updateReward(Number(currentReward.id), data)
        : () => createReward(data);

      await apiCall();
      enqueueSnackbar(currentReward ? 'Reward updated successfully!' : 'Reward created successfully!');
      router.push(paths.dashboard.rewards.all_rewards);
    } catch (error) {
      enqueueSnackbar('Failed to save reward. Please try again.', { variant: 'error' });
    }
  });

  return (
    <LocalizationProvider>
      <FormProvider methods={methods} onSubmit={onSubmit}>
        <Grid container spacing={3}>
          {/* Reward Details */}
          <Grid xs={12}>
            <Card>
              <CardHeader title="Reward Details" />
              <Stack spacing={3} sx={{ p: 3 }}>
                <RHFTextField name="name" label="Reward Name" />
                <RHFEditor name="description" />
                <Controller
                  name="startDate"
                  control={control}
                  render={({ field }) => (
                    <DatePicker
                      label="Start Date"
                      value={field.value}
                      onChange={(newValue) => field.onChange(newValue)}
                    />
                  )}
                />
                <Controller
                  name="endDate"
                  control={control}
                  render={({ field }) => (
                    <DatePicker
                      label="End Date"
                      value={field.value}
                      onChange={(newValue) => field.onChange(newValue)}
                    />
                  )}
                />
                <RHFRadioGroup
                  name="rule"
                  label="Rule"
                  options={[
                    { label: 'Fix the Threshold', value: 'FIX_THE_THRESHOLD' },
                    { label: 'The Highest of Grades', value: 'THE_HIGHEST_OF_GRADES' },
                  ]}
                />
              </Stack>
            </Card>
          </Grid>

          {/* Status and Submit */}
          <Grid xs={12}>
            <Card sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', p: 3 }}>
              <Stack direction="row" alignItems="center">
                <Switch
                  checked={isPublished}
                  onChange={(event) => setIsPublished(event.target.checked)}
                />
                <Typography>{isPublished ? 'Published' : 'Draft'}</Typography>
              </Stack>
              <LoadingButton type="submit" variant="contained" loading={isSubmitting}>
                {currentReward ? 'Save Changes' : 'Create Reward'}
              </LoadingButton>
            </Card>
          </Grid>
        </Grid>
      </FormProvider>
    </LocalizationProvider>
  );
}