import {
  ICharacterDailyTask,
  ICollectGlobalRewardRequest,
  ICollectRewardRequest,
  TaskStatus,
  TaskType,
  isMobileOrTablet,
} from '@rpg-engine/shared';
import React, { useMemo, useState } from 'react';
import { FaClipboardList, FaThumbtack } from 'react-icons/fa';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { DraggableContainer } from '../DraggableContainer';
import { Dropdown, IOptionsProps as DropdownOption } from '../Dropdown';
import { RPGUIContainerTypes } from '../RPGUI/RPGUIContainer';
import { SearchBar } from '../shared/SearchBar/SearchBar';
import { DailyTaskItem } from './DailyTaskItem';
import { GlobalDailyProgress } from './GlobalDailyProgress';
import { getTaskIcon } from './utils/dailyTasks.utils';

export interface IDailyTasksProps {
  tasks: ICharacterDailyTask[];
  onClaimReward: (task: ICollectRewardRequest) => void;
  onClaimGlobalReward: (tasks: ICollectGlobalRewardRequest) => void;
  onClose: () => void;
  scale?: number;
  itemsAtlasJSON: Record<string, any>;
  itemsAtlasIMG: string;
  iconAtlasJSON?: Record<string, any>;
  iconAtlasIMG?: string;
  globalRewardClaimed?: boolean;
}

export const DailyTasks: React.FC<IDailyTasksProps> = ({
  tasks,
  onClaimReward,
  onClaimGlobalReward,
  onClose,
  scale = 1,
  itemsAtlasJSON,
  itemsAtlasIMG,
  iconAtlasJSON,
  iconAtlasIMG,
  globalRewardClaimed = false,
}): JSX.Element | null => {
  const [localTasks] = React.useState(tasks);
  const isMobile = isMobileOrTablet();
  const [claimedTasks, setClaimedTasks] = useState<string[]>([]);
  const [globalRewardClaimedLocal, setGlobalRewardClaimedLocal] = useState(
    false
  );

  // Search and filter state
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('all');
  const [pinnedTasks, setPinnedTasks] = useLocalStorage<string[]>('dailyTasks.pinned', []);

  const handleClaimReward = (taskKey: string, taskType: TaskType) => {
    onClaimReward({
      taskKey,
      type: taskType,
    });
    setClaimedTasks(prev => [...prev, taskKey]);
  };

  const handleClaimGlobalRewards = (tasks: ICollectGlobalRewardRequest) => {
    onClaimGlobalReward(tasks);
    setGlobalRewardClaimedLocal(true);
  };

  const isTaskRewardClaimed = (taskKey: string): boolean => {
    return claimedTasks.includes(taskKey);
  };

  const togglePinTask = (taskKey: string) => {
    setPinnedTasks(prev =>
      prev.includes(taskKey)
        ? prev.filter(key => key !== taskKey)
        : [...prev, taskKey]
    );
  };

  // Filter options using Store pattern
  const statusOptions: DropdownOption[] = [
    { id: 0, value: 'all', option: 'All' },
    { id: 1, value: 'pinned', option: 'Pinned' },
    { id: 2, value: 'completed', option: 'Completed' },
    { id: 3, value: 'inprogress', option: 'In Progress' },
    { id: 4, value: 'notstarted', option: 'Not Started' },
  ];

  // Filtered tasks using InformationCenter pattern
  const filteredTasks = useMemo(() => {
    let filtered = localTasks.filter(task => {
      const matchesSearch =
        task.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        task.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        task.key.toLowerCase().includes(searchQuery.toLowerCase());

      const matchesStatus =
        selectedStatus === 'all' ||
        (selectedStatus === 'pinned' && pinnedTasks.includes(task.key)) ||
        (selectedStatus === 'completed' && task.status === TaskStatus.Completed) ||
        (selectedStatus === 'inprogress' && task.status === TaskStatus.InProgress) ||
        (selectedStatus === 'notstarted' && task.status === TaskStatus.NotStarted);

      return matchesSearch && matchesStatus;
    });

    // Sort by relevance: pinned first, then by status (in progress, completed, not started)
    return filtered.sort((a, b) => {
      const aIsPinned = pinnedTasks.includes(a.key);
      const bIsPinned = pinnedTasks.includes(b.key);

      // Pinned tasks always come first
      if (aIsPinned && !bIsPinned) return -1;
      if (!aIsPinned && bIsPinned) return 1;

      // If both are pinned or both are not pinned, sort by status priority
      const statusPriority = {
        [TaskStatus.InProgress]: 1,
        [TaskStatus.Completed]: 2,
        [TaskStatus.NotStarted]: 3,
      };

      const aPriority = statusPriority[a.status] || 4;
      const bPriority = statusPriority[b.status] || 4;

      return aPriority - bPriority;
    });
  }, [localTasks, searchQuery, selectedStatus, pinnedTasks]);

  return (
    <TasksContainer
      type={RPGUIContainerTypes.Framed}
      onCloseButton={onClose}
      cancelDrag=".tasks-container"
      scale={scale}
      width={'max(50vw, 900px)'}
      height={'min(85vh, 800px)'}
      isMobile={isMobile}
    >
      <TaskTitle isMobile={isMobile}>Daily Tasks</TaskTitle>
      <Container isMobile={isMobile}>
        <GlobalProgressFixed>
          <GlobalDailyProgress
            tasks={localTasks}
            onClaimAllRewards={handleClaimGlobalRewards}
            globalRewardClaimed={
              globalRewardClaimed || globalRewardClaimedLocal
            }
          />
        </GlobalProgressFixed>

        <SearchHeader>
          <SearchBarContainer>
            <SearchBar
              value={searchQuery}
              onChange={setSearchQuery}
              placeholder="Search tasks..."
            />
          </SearchBarContainer>
          <DropdownContainer>
            <Dropdown
              options={statusOptions}
              onChange={setSelectedStatus}
              width="100%"
            />
          </DropdownContainer>
        </SearchHeader>

        <TasksList className="tasks-container" isMobile={isMobile}>
          {filteredTasks.length > 0 ? (
            filteredTasks.map(task => (
              <TaskWrapper key={task.key}>
                <DailyTaskItem
                  task={task}
                  spriteKey={getTaskIcon(task.type, task.difficulty)}
                  onClaimReward={handleClaimReward}
                  itemsAtlasJSON={itemsAtlasJSON}
                  itemsAtlasIMG={itemsAtlasIMG}
                  iconAtlasJSON={iconAtlasJSON}
                  iconAtlasIMG={iconAtlasIMG}
                  isRewardClaimed={task.claimed || isTaskRewardClaimed(task.key)}
                  isPinned={pinnedTasks.includes(task.key)}
                />
                <PinButton
                  onClick={() => togglePinTask(task.key)}
                  isPinned={pinnedTasks.includes(task.key)}
                >
                  <FaThumbtack size={10} />
                </PinButton>
              </TaskWrapper>
            ))
          ) : (
            <EmptyState>
              <FaClipboardList size={48} />
              <p>
                {searchQuery || selectedStatus !== 'all'
                  ? 'No tasks match your criteria.'
                  : 'No daily tasks available.'}
              </p>
            </EmptyState>
          )}
        </TasksList>
      </Container>
    </TasksContainer>
  );
};

const TasksContainer = styled(DraggableContainer) <{ isMobile: boolean }>`
  margin: 0 auto;
  min-width: 50vw;

  .rpgui-container-title {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    ${props => props.isMobile ? 'padding: 8px 0;' : ''}
  }

  .rpgui-container {
    padding: 0 !important;
    overflow: hidden !important;
    background-color: rgba(30, 30, 30, 0.98) !important;
  }
`;

const Container = styled.div<{ isMobile: boolean }>`
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  box-sizing: border-box;
  background-color: transparent;
  display: flex;
  flex-direction: column;
`;

const TasksList = styled.div<{ isMobile: boolean }>`
  display: flex;
  flex-direction: column;
  gap: ${props => props.isMobile ? '8px' : '12px'};
  padding: ${props => props.isMobile ? '8px 8px 40px 8px' : '12px 12px 40px 12px'};
  overflow-y: auto;
  flex: 1;
  background-color: transparent;
  
  ${props => props.isMobile ? `
    -webkit-overflow-scrolling: touch;
    scrollbar-width: thin;
  ` : ''}
`;

const GlobalProgressFixed = styled.div`
  flex-shrink: 0;
  padding: 12px;
  background-color: transparent;
`;

const SearchHeader = styled.div`
  display: flex;
  gap: 12px; 
  justify-content: center;
  align-items: center;
  margin-left: 12px;
  margin-right: 12px;
  padding: 0.25rem;
  border-bottom: 1px solid ${uiColors.darkGray};
  background: rgba(0, 0, 0, 0.3);
`;

const SearchBarContainer = styled.div`
  flex: 3;
`;

const DropdownContainer = styled.div`
  flex: 1;
  min-width: 120px;
`;

const TaskWrapper = styled.div`
  position: relative;
  width: 100%;
`;

const PinButton = styled.button<{ isPinned: boolean }>`
  position: absolute;
  top: 8px;
  right: 32px;
  background: rgba(0, 0, 0, 0.7);
  color: ${props => props.isPinned ? uiColors.yellow : uiColors.lightGray};
  border: 1px solid ${props => props.isPinned ? uiColors.yellow : 'transparent'};
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 3px;
  transition: all 0.2s ease;
  z-index: 10;
  width: 20px;
  height: 20px;
  
  &:hover {
    color: ${uiColors.yellow};
    background: rgba(0, 0, 0, 0.9);
    border-color: ${uiColors.yellow};
  }
  
  ${props => props.isPinned && `
    transform: rotate(45deg);
  `}
`;

const EmptyState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: ${uiColors.lightGray};
  opacity: 0.7;
  gap: 16px;
  
  p {
    margin: 0;
    font-size: 0.9rem;
    line-height: 1.4;
  }
`;

const TaskTitle = styled.h2<{ isMobile: boolean }>`
  color: ${uiColors.yellow} !important;
  text-align: center;
  padding-right: 30px !important;
  font-size: ${props => props.isMobile ? '1rem' : '1.2rem'} !important;
  width: 100%;
  margin: ${props => props.isMobile ? '4px 0' : '8px 0'} !important;
  font-weight: 600;
`;


