import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Button,
  Card,
  Container,
  Grid,
  Stack,
  Avatar,
  Tabs,
  Tab,
  TextField,
  InputAdornment,
  ListItemText,
} from '@mui/material';
import IconButton from '@mui/material/IconButton';
import Iconify from '@/shared/components/iconify';
import { useSettingsContext } from '@/shared/components/settings';
import { paths } from '@/routes/paths';
import AppWelcome from './app-welcome';
import { WinnerIllustration } from '@/shared/assets/illustrations';
import EmptyContent from '@/components/empty-content';
import Label from '@/components/label';
import { useRouter } from '@/hooks';
import axios from 'axios';
import isEqual from 'lodash/isEqual';
import Link from 'next/link';
import { IRewardItem, IWinnerFilter } from '@/contexts/types/reward';
import axiosInstancee from '@/utils/axios';

const defaultFilters = {
  Reward: 'All',
  name: '',
};

interface Winner {
  id: number;
  name: string;
  rewarded: boolean;
  rewardId: number;
  rewardTitle: string;
  mark: number;
  avatarUrl?: string;
}

export default function RewardWinnerDetails() {
  const settings = useSettingsContext();
  const [filters, setFilters] = useState(defaultFilters);
  const [data, setData] = useState<Winner[]>([]);
  const [loading, setLoading] = useState(false);

  const router = useRouter();

  const fetchWinners = useCallback(async () => {
    setLoading(true);
    try {
      const params = {
        rewardStatus: filters.Reward !== 'All' ? filters.Reward : null,
        name: filters.name || null,
      };
      const response = await axiosInstancee.get('/api/projects/winners', { params });
      
      const winners = Array.isArray(response.data) ? response.data : response.data.content || [];
      setData(winners);
    } catch (error) {
      console.error('Failed to fetch winners:', error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

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

  const handleFilters = useCallback((name: keyof IWinnerFilter, value: string) => {
    setFilters((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  }, []);

  const handleFilterReward = (_event: React.SyntheticEvent, newValue: string) => handleFilters('Reward', newValue);

  const handleFilterName = (event: React.ChangeEvent<HTMLInputElement>) => handleFilters('name', event.target.value);

  const canReset = !isEqual(defaultFilters, filters);
  const notFound = !data.length && canReset;

  const filteredData = useCallback(() => {
    let filtered = [...data];

    if (filters.Reward === 'Rewarded') {
      filtered = filtered.filter((winner) => winner.rewarded === true);
    } else if (filters.Reward === 'Reward') {
      filtered = filtered.filter((winner) => winner.rewarded === false);
    }

    if (filters.name) {
      const searchTerm = filters.name.toLowerCase().trim();
      filtered = filtered.filter((winner) => 
        winner.name?.toLowerCase().includes(searchTerm) || 
        winner.rewardTitle?.toLowerCase().includes(searchTerm)
      );
    }

    return filtered;
  }, [data, filters]);

  return (
    <Container maxWidth={settings.themeStretch ? false : 'lg'}>
      <Grid xs={12} md={4}>
        <AppWelcome
          title="Welcome back 👋 Admin"
          description="Here are the winners in all rewards. You can see if the employee has received a reward or not."
          img={<WinnerIllustration />}
          action={
            <Button
              variant="contained"
              color="primary"
              onClick={() => router.push(paths.dashboard.rewards.all_rewards)}
            >
              Go To Rewards
            </Button>
          }
        />
      </Grid>

      <Stack spacing={{ xs: 1, md: 10 }} direction={{ xs: 'column', md: 'row' }} alignItems={{ xs: 'center', md: 'flex-end' }} sx={{ width: 1 }}>
        <Tabs value={filters.Reward} onChange={handleFilterReward} sx={{ mt: 1 }}>
          {['All', 'Rewarded', 'Reward'].map((tab) => (
            <Tab
              key={tab}
              value={tab}
              label={tab}
              icon={
                <Label
                  variant={tab === 'All' || tab === 'Reward' ? 'filled' : 'soft'}
                  color={tab === 'Rewarded' ? 'success' : 'default'}
                >
                  {tab === 'All' && data.length}
                  {tab === 'Rewarded' && data.filter((winner) => winner.rewarded).length}
                  {tab === 'Reward' && data.filter((winner) => !winner.rewarded).length}
                </Label>
              }
              sx={{ textTransform: 'capitalize', mt: 2 }}
            />
          ))}
        </Tabs>

        <Stack spacing={1} direction="row" alignItems="center" justifyContent="flex-end" flexGrow={1}>
          <TextField
            value={filters.name}
            onChange={handleFilterName}
            placeholder="Search by name or reward..."
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
                </InputAdornment>
              ),
            }}
            sx={{ width: { xs: 1, md: 180 } }}
          />
        </Stack>
      </Stack>

      {notFound && <EmptyContent filled title="No Data" sx={{ py: 10 }} />}

      <Box sx={{ mt: 4 }} gap={3} display="grid" gridTemplateColumns={{ xs: 'repeat(1, 1fr)', sm: 'repeat(1, 1fr)', md: 'repeat(2, 1fr)' }}>
        {filteredData().map((winner) => (
          <WinnerItem key={winner.id} winner={winner} onRewardUpdated={fetchWinners} />
        ))}
      </Box>
    </Container>
  );
}

function WinnerItem({ winner, onRewardUpdated }: { winner: Winner; onRewardUpdated: () => void }) {
  const [rewarded, setRewarded] = useState(winner.rewarded);

  console.log(`Winner ID: ${winner.id}, Initial Rewarded State: ${winner.rewarded}`);

  const toggleReward = async () => {
    try {
      console.log(`Toggling reward state for Winner ID: ${winner.id}`);
  
      // Check if rewardId is present
      if (!winner.rewardId) {
        console.error('Missing rewardId in winner object.');
        return;
      }
  
      const newRewardedState = !rewarded; // Toggle the current state
  
      const response = await axiosInstancee.put(
        `/api/projects/${winner.id}/assign-reward`,
        null,
        {
          params: {
            rewardId: winner.rewardId, // Ensure rewardId is sent
            mark: winner.mark || 0, // Pass mark or a default value
            rewarded: newRewardedState, // New state to toggle
          },
        }
      );
  
      console.log('API Response:', response.data);
  
      // Update the state after a successful response
      if (response.data?.rewarded !== undefined) {
        setRewarded(response.data.rewarded);
      }
  
      // Notify parent to refresh the list
      if (onRewardUpdated) onRewardUpdated();
    } catch (error) {
      console.error(`Error toggling reward for Winner ID: ${winner.id}`, error);
    }
  };

  return (
    <Stack component={Card} direction="row" spacing={2} sx={{ p: 2 }}>
      <Avatar alt={winner.name} src={winner.avatarUrl} sx={{ width: 48, height: 48 }} />

      <Stack spacing={7} flexGrow={1}>
        <ListItemText
          primary={winner.name}
          secondary={
            <>
              <Stack direction="row" alignItems="center" spacing={1}>
                <IconButton size="small" color="info" sx={{ borderRadius: 1 }}>
                  <Iconify icon="material-symbols:bookmarks" width={20} />
                </IconButton>
                {winner.mark} Marks
              </Stack>
              <Stack direction="row" alignItems="center" spacing={1}>
                <IconButton size="small" color="success" sx={{ borderRadius: 1 }}>
                  <Iconify icon="material-symbols:rewarded-ads" width={23} />
                </IconButton>
                <Link href={paths.dashboard.rewards.reward_details(String(winner.rewardId))}>
                  {winner.rewardTitle}
                </Link>
              </Stack>
            </>
          }
        />
      </Stack>

      <Button
        size="small"
        variant={rewarded ? 'text' : 'outlined'}
        color={rewarded ? 'success' : 'inherit'}
        onClick={toggleReward}
      >
        {rewarded ? 'Rewarded' : 'Reward'}
      </Button>
    </Stack>
  );
}
