'use client';

import { useState, useEffect, useCallback } from 'react';
import Container from '@mui/material/Container';
import Button from '@mui/material/Button';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Iconify from '@/shared/components/iconify';
import CustomBreadcrumbs from '@/shared/components/custom-breadcrumbs';
import Label from '@/components/label';
import RewardList from './reward-list';
import EmptyContent from '@/components/empty-content';
import { paths } from '@/routes/paths';
import { IRewardFilter, IRewardItem } from '@/contexts/types/reward';
import { useSnackbar } from 'notistack';
import { useRouter } from 'next/navigation';
import RewardActionDialog from './reward-action-dialog';
import Stack from '@mui/material/Stack';
import axiosInstancee from '@/utils/axios';
import { TablePaginationCustom } from '@/shared/components/table';


const defaultFilters = { status: 'all' };

export default function RewardListView() {
  const [rewards, setRewards] = useState<IRewardItem[]>([]);
  const [filters, setFilters] = useState(defaultFilters);
  const [notFound, setNotFound] = useState(false);
  const { enqueueSnackbar } = useSnackbar();
  const router = useRouter(); 
  const [selectedAction, setSelectedAction] = useState<{
    type: 'assign' | 'remove';
    open: boolean;
  }>({
    type: 'assign',
    open: false
  });
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(6);
  const [totalElements, setTotalElements] = useState(0);
  const [totalPages, setTotalPages] = useState(0);

  const fetchRewards = useCallback(async () => {
    const mappedStatus = filters.status !== 'all' ? filters.status : undefined;

    try {
      const response = await axiosInstancee.get('/api/projects/rewards', {
        params: { 
          status: mappedStatus,
          page,
          size: rowsPerPage,
        },
      });

      setRewards(response.data.content || []);
      setTotalElements(response.data.totalElements || 0);
      setTotalPages(Math.ceil((response.data.totalElements || 0) / rowsPerPage));
      setNotFound((response.data.content || []).length === 0);
    } catch (error) {
      console.error('Error fetching rewards:', error);
      setRewards([]);
      setTotalElements(0);
      setTotalPages(0);
      setNotFound(true);
    }
  }, [filters, page, rowsPerPage]);

  useEffect(() => {
    fetchRewards();
  }, [fetchRewards]);

  const handleFilterStatus = useCallback(
    (event: React.SyntheticEvent, newValue: string) => {
      setFilters({ status: newValue });
    },
    []
  );

  const handleDelete = async (id: string) => {
    console.log(`Deleting reward with ID: ${id}`);
    try {
      await axiosInstancee.delete(`/api/projects/rewards/${id}`);
      enqueueSnackbar('Reward deleted successfully!', { variant: 'success' });

      // Optionally refresh the page or remove the deleted reward from the list
      router.refresh(); // Refresh the current route to reflect the changes
    } catch (error) {
      console.error('Error deleting reward:', error);
      enqueueSnackbar('Failed to delete reward. Please try again.', { variant: 'error' });
    }
  };

  const handleOpenDialog = (type: 'assign' | 'remove') => {
    setSelectedAction({
      type,
      open: true
    });
  };

  const handleCloseDialog = () => {
    setSelectedAction(prev => ({ ...prev, open: false }));
  };

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newRowsPerPage = parseInt(event.target.value, 10);
    setRowsPerPage(newRowsPerPage);
    setPage(0);
    setTotalPages(Math.ceil(totalElements / newRowsPerPage));
  };

  return (
    <Container>
      <CustomBreadcrumbs
        heading="Reward List"
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          { name: 'Rewards', href: paths.dashboard.rewards.all_rewards },
          { name: 'List' },
        ]}
        action={
          <Stack direction="row" spacing={2}>
            <Button
              variant="contained"
              color="info"
              startIcon={<Iconify icon="eva:link-2-fill" />}
              onClick={() => handleOpenDialog('assign')}
            >
              Assign Reward
            </Button>
            
            <Button
              variant="contained"
              color="error"
              startIcon={<Iconify icon="eva:link-off-fill" />}
              onClick={() => handleOpenDialog('remove')}
            >
              Remove Reward
            </Button>

            <Button
              href={paths.dashboard.rewards.add_reward}
              variant="contained"
              startIcon={<Iconify icon="mingcute:add-line" />}
            >
              New Reward
            </Button>
          </Stack>
        }
      />
      <Tabs
        value={filters.status}
        onChange={handleFilterStatus}
        sx={{ mb: 3 }}
        indicatorColor="primary"
        textColor="primary"
      >
        {['all', 'PUBLISHED', 'DRAFT'].map((tab) => (
          <Tab
            key={tab}
            value={tab}
            label={tab.toLowerCase()}
            icon={
              <Label
                variant={filters.status === tab ? 'filled' : 'soft'}
                color={
                  tab === 'PUBLISHED' ? 'info' : tab === 'DRAFT' ? 'warning' : 'default'
                }
              >
                {tab}
              </Label>
            }
          />
        ))}
      </Tabs>
      {notFound ? (
        <EmptyContent title="No rewards found." />
      ) : (
        <>
          <RewardList rewards={rewards} onDelete={handleDelete} />
          <TablePaginationCustom
            count={totalElements}
            page={page}
            rowsPerPage={rowsPerPage}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
            rowsPerPageOptions={[6, 12, 25]}
            sx={{
              mt: 3,
              '& .MuiTablePagination-select': { textAlign: 'left' },
            }}
            labelDisplayedRows={({ from, to, count }) => 
              `${from}-${to} sur ${count !== -1 ? count : `plus de ${to}`}`
            }
          />
        </>
      )}
      <RewardActionDialog
        open={selectedAction.open}
        onClose={handleCloseDialog}
        type={selectedAction.type}
        title={selectedAction.type === 'assign' ? 'Assign Reward to Task' : 'Remove Reward from Task'}
      />
    </Container>
  );
}
// ----------------------------------------------------------------------

const applyFilter = ({
  inputData,
  filters,
  sortBy,
}: {
  inputData: IRewardItem[];
  filters: IRewardFilter;
  sortBy: string;
}) => {

  const { status } = filters;

  if (status !== 'all') {
    inputData = inputData.filter((project) => project.status === status);
  }


  return inputData;
};


