"use client";

import * as React from 'react';
import { useState } from 'react';
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from '@/components/ui/drawer';
import { Button, IconButton } from '@/components/ui/button';
import { Chip } from '@/components/ui/chip';
import { cn } from '@/lib/utils';
import { Gender } from '@/types/user';
import Image from 'next/image';
import { Age } from '@/services/home';

// 筛选选项类型定义
export interface FilterOptions {
  gender: Gender[]; // 多选
  age: string[]; // 多选
  type: string[]; // 多选
}

interface FilterDrawerProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  filters: FilterOptions;
  onFiltersChange: (filters: FilterOptions) => void;
  onReset: () => void;
  onConfirm: () => void;
}

// 筛选选项数据
const GENDER_OPTIONS = [
  { code: Gender.MALE, name: 'Male' },
  { code: Gender.FEMALE, name: 'Female' },
  { code: Gender.OTHER, name: 'Other' },
];

const AGE_OPTIONS = [
  { code: Age.Age1, name: '18-24' },
  { code: Age.Age2, name: '25-34' },
  { code: Age.Age3, name: '35-44' },
  { code: Age.Age4, name: '45-54' },
  { code: Age.Age5, name: '>54' },
];

const TYPE_OPTIONS = [
  { 
    code: 'R00001', 
    name: 'Original',
    image: '/images/home/icon-original.png',
    background: "linear-gradient(263deg, #62E1F2 0%, #6296F2 100%), #211A2B"
  },
  { 
    code: 'R00004', 
    name: 'Anime',
    image: '/images/home/icon-anime.png',
    background: "linear-gradient(263deg, rgba(224, 60, 230, 0.50) 0%, rgba(230, 60, 139, 0.50) 100%), #211A2B"
  },
  { 
    code: 'R00005', 
    name: 'Game',
    image: '/images/home/icon-game.png',
    background: "linear-gradient(263deg, rgba(71, 92, 255, 0.50) 0%, rgba(123, 71, 255, 0.50) 100%), #211A2B"
  },
  { 
    code: 'R00006', 
    name: 'Film&TV',
    image: '/images/home/icon-film.png',
    background: "linear-gradient(263deg, rgba(255, 100, 100, 0.50) 0%, rgba(255, 162, 100, 0.50) 100%), #211A2B"
  },
];

const FilterDrawer: React.FC<FilterDrawerProps> = ({
  open,
  onOpenChange,
  filters,
  onFiltersChange,
  onReset,
  onConfirm,
}) => {
  const [localFilters, setLocalFilters] = useState<FilterOptions>(filters);

  // 同步外部 filters 到本地状态
  React.useEffect(() => {
    if (open) {
      setLocalFilters(filters);
    }
  }, [filters, open]);

  const handleGenderToggle = (gender: string) => {
    // 多选逻辑：包含则移除，否则添加
    const genderValue = Number(gender) as Gender;
    const newGender = localFilters.gender.includes(genderValue)
      ? localFilters.gender.filter(g => g !== genderValue)
      : [...localFilters.gender, genderValue];
    setLocalFilters(prev => ({ ...prev, gender: newGender }));
  };

  const handleAgeToggle = (age: string) => {
    // 多选逻辑：包含则移除，否则添加
    const newAge = localFilters.age.includes(age)
      ? localFilters.age.filter(a => a !== age)
      : [...localFilters.age, age];
    setLocalFilters(prev => ({ ...prev, age: newAge }));
  };

  const handleTypeToggle = (type: string) => {
    const newType = localFilters.type.includes(type)
      ? localFilters.type.filter(t => t !== type)
      : [...localFilters.type, type];
    
    setLocalFilters(prev => ({ ...prev, type: newType }));
  };

  const handleReset = () => {
    const resetFilters = { gender: [], age: [], type: [] };
    setLocalFilters(resetFilters);
    onReset();
    onOpenChange(false);
  };

  const handleConfirm = () => {
    console.log('localFilters', localFilters);
    onFiltersChange(localFilters);
    onConfirm();
    onOpenChange(false);
  };

  return (
    <Drawer open={open} onOpenChange={onOpenChange} direction="right">
      <DrawerContent className="bg-background-default rounded-none">
        {/* Header */}
        <DrawerHeader className="flex items-center justify-between p-6">
          <div className="flex items-center gap-2">
            <DrawerClose asChild>
              <IconButton
                variant="ghost"
                size="small"
                className="p-2"
                iconfont="icon-arrow-right"
              />
            </DrawerClose>
            <DrawerTitle className="txt-title-m text-txt-primary-normal">
              Filter
            </DrawerTitle>
          </div>
        </DrawerHeader>

        {/* Content */}
        <div className="flex-1 px-6 pb-6 space-y-6 overflow-y-auto">
          {/* Gender Section */}
          <div className="space-y-4">
            <h3 className="txt-title-s text-txt-primary-normal">Gender</h3>
            <div className="flex flex-wrap gap-3">
              {GENDER_OPTIONS.map((option) => (
                <Chip
                  key={option.code}
                  size="small"
                  state={localFilters.gender.includes(option.code) ? 'active' : 'inactive'}
                  onClick={() => handleGenderToggle(option.code.toString())}
                  className="px-4 py-1.5"
                >
                  <span className="txt-label-m">{option.name}</span>
                </Chip>
              ))}
            </div>
          </div>

          {/* Age Section */}
          <div className="space-y-4">
            <h3 className="txt-title-s text-txt-primary-normal">Age</h3>
            <div className="flex flex-wrap gap-4">
              {AGE_OPTIONS.map((option) => (
                <Chip
                  key={option.code}
                  size="small"
                  state={localFilters.age.includes(option.code) ? 'active' : 'inactive'}
                  onClick={() => handleAgeToggle(option.code)}
                  className="px-4 py-1.5"
                >
                  <span className="txt-label-m">{option.name}</span>
                </Chip>
              ))}
            </div>
          </div>

          {/* Type Section */}
          <div className="space-y-4">
            <h3 className="txt-title-s text-txt-primary-normal">Type</h3>
            <div className="grid grid-cols-3 gap-4">
              {TYPE_OPTIONS.map((option, index) => {
                const isSelected = localFilters.type.includes(option.code);
                return (
                  <div
                    key={option.code}
                    className={cn(
                      "aspect-square rounded-lg overflow-hidden cursor-pointer transition-all bg-surface-element-normal",
                      "border border-outline-normal",
                    )}
                    onClick={() => handleTypeToggle(option.code)}
                    style={{
                      background: isSelected ? option.background : "rgba(251, 222, 255, 0.08",
                    }}
                  >
                    <div className="w-full h-full relative">
                      <div className="absolute bottom-0 left-0 right-0 h-[71px]">
                        <Image className="object-cover" src={option.image} alt={option.name} fill />
                      </div>
                      <div className="absolute left-3 top-2 txt-label-m text-txt-primary-normal">{option.name}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="p-6 bg-background-default/65 backdrop-blur-md">
          <div className="flex gap-4">
            <Button
              variant="tertiary"
              size="large"
              onClick={handleReset}
              className="flex-1"
            >
              Reset
            </Button>
            <Button
              variant="primary"
              size="large"
              onClick={handleConfirm}
              className="flex-1"
            >
              Confirm
            </Button>
          </div>
        </div>
      </DrawerContent>
    </Drawer>
  );
};

export default FilterDrawer;