import { isMobileOrTablet } from '@rpg-engine/shared';
import React, { useEffect, useRef } from 'react';
import {
  AiFillCaretRight,
  AiFillFilter,
  AiOutlineFilter,
} from 'react-icons/ai';
import styled from 'styled-components';
import { Dropdown } from '../../Dropdown';
import { Input } from '../../Input';
import { Portal } from '../Portal/Portal';

export interface IFilterOption {
  id: number;
  value: string;
  option: string;
}

export interface IFilterSection {
  type: 'range' | 'dropdown';
  label: string;
  key: string;
  options?: IFilterOption[];
  value?: string | [number | undefined, number | undefined];
  onChange: (value: any) => void;
}

interface IAdvancedFiltersProps {
  isOpen: boolean;
  onToggle: () => void;
  sections: IFilterSection[];
  onClearAll: () => void;
  hasActiveFilters: boolean;
  onClose?: () => void;
}

export const AdvancedFilters: React.FC<IAdvancedFiltersProps> = ({
  isOpen,
  onToggle,
  sections,
  onClearAll,
  hasActiveFilters,
  onClose,
}) => {
  const renderFilterSection = (section: IFilterSection) => {
    switch (section.type) {
      case 'range':
        const rangeValue = section.value as [
          number | undefined,
          number | undefined
        ];
        return (
          <FilterSection key={section.key}>
            <Label>{section.label}</Label>
            <RangeInputs>
              <Input
                type="number"
                min={0}
                placeholder="Min"
                value={rangeValue[0] || ''}
                onChange={e =>
                  section.onChange([
                    e.target.value ? Number(e.target.value) : undefined,
                    rangeValue[1],
                  ])
                }
              />
              <AiFillCaretRight />
              <Input
                type="number"
                min={0}
                placeholder="Max"
                value={rangeValue[1] || ''}
                onChange={e =>
                  section.onChange([
                    rangeValue[0],
                    e.target.value ? Number(e.target.value) : undefined,
                  ])
                }
              />
            </RangeInputs>
          </FilterSection>
        );

      case 'dropdown':
        return (
          <FilterSection key={section.key}>
            <Label>{section.label}</Label>
            <StyledDropdownWrapper>
              <Dropdown
                options={section.options || []}
                onChange={section.onChange}
                width="100%"
              />
            </StyledDropdownWrapper>
          </FilterSection>
        );

      default:
        return null;
    }
  };

  // Calculate button position for the portal
  const [buttonPosition, setButtonPosition] = React.useState({
    top: 0,
    left: 0,
    isMobile: false,
  });
  const buttonRef = useRef<HTMLButtonElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const isMobile = isMobileOrTablet();

  useEffect(() => {
    if (isOpen && buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect();

      if (isMobile) {
        // For mobile, position in center of screen
        setButtonPosition({
          top: window.innerHeight / 2,
          left: window.innerWidth / 2,
          isMobile: true,
        });
      } else {
        // Position below the button for larger screens
        setButtonPosition({
          top: rect.bottom + window.scrollY,
          left: rect.left + rect.width / 2 + window.scrollX,
          isMobile: false,
        });
      }
    }
  }, [isOpen, isMobile]);

  // Handle click outside to close the panel
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        isOpen &&
        panelRef.current &&
        !panelRef.current.contains(event.target as Node) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target as Node)
      ) {
        onToggle();
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen, onToggle]);

  const handleClose = () => {
    onToggle();
    if (onClose) {
      onClose();
    }
  };

  return (
    <Container>
      <FilterButton
        onClick={onToggle}
        $hasActiveFilters={hasActiveFilters}
        ref={buttonRef}
      >
        {hasActiveFilters ? (
          <AiFillFilter size={20} />
        ) : (
          <AiOutlineFilter size={20} />
        )}
        <FilterCount $visible={hasActiveFilters}>
          {
            sections.filter(section => {
              if (section.type === 'range') {
                const rangeValue = section.value as [
                  number | undefined,
                  number | undefined
                ];
                return (
                  rangeValue[0] !== undefined || rangeValue[1] !== undefined
                );
              }
              return section.value !== 'all';
            }).length
          }
        </FilterCount>
      </FilterButton>

      {isOpen && (
        <Portal>
          {isMobile && <Overlay />}
          <FiltersPanel
            ref={panelRef}
            style={{
              position: 'fixed',
              top: isMobile ? '50vh' : `${buttonPosition.top}px`,
              left: isMobile ? '50vw' : `${buttonPosition.left}px`,
              zIndex: 9999,
            }}
            $isMobile={isMobile}
          >
            <FilterHeader>
              <FilterTitle>Advanced Filters</FilterTitle>
              <CloseButton onClick={handleClose}>×</CloseButton>
            </FilterHeader>

            {sections.map(renderFilterSection)}

            {hasActiveFilters && (
              <ClearFiltersButton onClick={onClearAll}>
                Clear All Filters
              </ClearFiltersButton>
            )}
          </FiltersPanel>
        </Portal>
      )}
    </Container>
  );
};

const Container = styled.div`
  position: relative;
  margin-left: 0.5rem;
`;

const FilterButton = styled.button<{ $hasActiveFilters: boolean }>`
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  background: transparent;
  border: none;
  color: ${({ $hasActiveFilters }) =>
    $hasActiveFilters ? '#ffd700' : 'rgba(255, 255, 255, 0.8)'};
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    color: ${({ $hasActiveFilters }) =>
      $hasActiveFilters ? '#ffd700' : '#ffffff'};
  }
`;

const FilterCount = styled.div<{ $visible: boolean }>`
  position: absolute;
  top: -4px;
  right: -4px;
  background: #ffd700;
  color: #000;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  font-size: 10px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: ${({ $visible }) => ($visible ? 1 : 0)};
  transform: scale(${({ $visible }) => ($visible ? 1 : 0.5)});
  transition: all 0.2s;
`;

const FiltersPanel = styled.div<{ $isMobile?: boolean }>`
  background: #1a1a1a;
  border: 1px solid #333;
  border-radius: 6px;
  padding: ${props => (props.$isMobile ? '0.75rem' : '1rem')};
  width: ${props => (props.$isMobile ? '240px' : '280px')};
  max-width: calc(100vw - 20px);
  display: flex;
  flex-direction: column;
  gap: ${props => (props.$isMobile ? '0.75rem' : '1rem')};
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  font-family: 'Press Start 2P', cursive;
  transform: ${props =>
    props.$isMobile ? 'translate(-50%, -50%) scale(0.9)' : 'translateX(-50%)'};

  @media (max-width: 320px) {
    width: 220px;
    padding: 0.65rem;
    gap: 0.65rem;
  }

  &:before {
    content: '';
    position: absolute;
    top: -6px;
    left: 50%;
    transform: translateX(-50%) rotate(45deg);
    width: 12px;
    height: 12px;
    background: #1a1a1a;
    border-left: 1px solid #333;
    border-top: 1px solid #333;
    display: ${props => (props.$isMobile ? 'none' : 'block')};
  }
`;

const FilterHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 0.75rem;
  margin-bottom: 0.5rem;
  border-bottom: 1px solid #333;
`;

const Overlay = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 9998;
  animation: fadeIn 0.2s ease-out;

  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
`;

const FilterTitle = styled.div`
  font-weight: 600;
  color: #ffd700;
  font-size: 0.75rem;
`;

const FilterSection = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

const Label = styled.div`
  color: #999;
  font-size: 0.65rem;
  text-transform: uppercase;
  letter-spacing: 0.05em;
`;

const RangeInputs = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;

  input {
    width: 80px;
    background: #262626 !important;
    border: 1px solid #444 !important;
    border-radius: 4px !important;
    color: #ddd !important;
    font-size: 0.65rem !important;
    padding: 0.5rem !important;
    height: auto !important;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2) !important;

    &::placeholder {
      color: #666 !important;
    }

    &:focus {
      border-color: #f59e0b !important;
      outline: none !important;
    }
  }

  svg {
    color: #666;
    font-size: 0.875rem;
  }
`;

const ClearFiltersButton = styled.button`
  width: 100%;
  background: transparent;
  color: #666;
  border: none;
  padding: 0.75rem 0;
  margin-top: 0.5rem;
  cursor: pointer;
  font-size: 0.65rem;
  transition: all 0.2s;
  border-top: 1px solid #333;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  font-family: 'Press Start 2P', cursive;

  &:hover {
    color: #ffd700;
  }
`;

const CloseButton = styled.button`
  background: transparent;
  border: none;
  color: #999;
  font-size: 1.5rem;
  line-height: 1;
  cursor: pointer;
  padding: 0;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;

  &:hover {
    color: #ffd700;
  }
`;

const StyledDropdownWrapper = styled.div`
  .rpgui-dropdown-imp {
    font-size: 0.8rem;
    min-height: unset;
    padding-top: 0.3rem;
  }
`;
