"use client"

import { useMemo, useState } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"

export type FilterValues = {
  tags: string[]
  status: string[]
  rfm: [number, number]
}

type Props = {
  open: boolean
  onOpenChange: (v: boolean) => void
  allTags: string[]
  value: FilterValues
  onApply: (v: FilterValues) => void
}

const STATUS_OPTIONS = ["活跃", "沉睡", "已封禁"] as const

export default function FilterDrawer({
  open,
  onOpenChange,
  allTags,
  value,
  onApply,
}: Props) {
  const [local, setLocal] = useState<FilterValues>(value)

  // 同步外部变更
  useMemo(() => setLocal(value), [value])

  const toggleArrayVal = (arr: string[], val: string, checked: boolean) =>
    checked ? Array.from(new Set([...arr, val])) : arr.filter((x) => x !== val)

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>筛选</DialogTitle>
        </DialogHeader>

        <div className="grid gap-5 py-2">
          <section className="space-y-2">
            <Label>用户状态</Label>
            <div className="grid grid-cols-3 gap-2">
              {STATUS_OPTIONS.map((s) => {
                const checked = local.status.includes(s)
                return (
                  <label key={s} className="flex items-center gap-2 text-sm">
                    <Checkbox
                      checked={checked}
                      onCheckedChange={(ck) =>
                        setLocal((p) => ({ ...p, status: toggleArrayVal(p.status, s, !!ck) }))
                      }
                    />
                    <span>{s}</span>
                  </label>
                )
              })}
            </div>
          </section>

          <section className="space-y-2">
            <Label>RFM 分数范围</Label>
            <div className="flex items-center gap-2">
              <Input
                type="number"
                min={0}
                max={100}
                value={local.rfm[0]}
                aria-label="RFM最小值"
                onChange={(e) =>
                  setLocal((p) => {
                    const v = Math.max(0, Math.min(100, Number(e.target.value)))
                    return { ...p, rfm: [v, Math.max(v, p.rfm[1])] }
                  })
                }
              />
              <span className="text-muted-foreground">{'—'}</span>
              <Input
                type="number"
                min={0}
                max={100}
                value={local.rfm[1]}
                aria-label="RFM最大值"
                onChange={(e) =>
                  setLocal((p) => {
                    const v = Math.max(0, Math.min(100, Number(e.target.value)))
                    return { ...p, rfm: [Math.min(p.rfm[0], v), v] }
                  })
                }
              />
            </div>
          </section>

          <section className="space-y-2">
            <Label>标签</Label>
            <div className="grid grid-cols-2 gap-2 max-h-48 overflow-auto pr-1">
              {allTags.length === 0 && (
                <div className="text-sm text-muted-foreground col-span-2">暂无标签</div>
              )}
              {allTags.map((t) => {
                const checked = local.tags.includes(t)
                return (
                  <label key={t} className="flex items-center gap-2 text-sm">
                    <Checkbox
                      checked={checked}
                      onCheckedChange={(ck) =>
                        setLocal((p) => ({ ...p, tags: toggleArrayVal(p.tags, t, !!ck) }))
                      }
                    />
                    <span className="truncate">{t}</span>
                  </label>
                )
              })}
            </div>
          </section>
        </div>

        <div className="flex justify-end gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button
            onClick={() => {
              onApply(local)
              onOpenChange(false)
            }}
          >
            应用筛选
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
