'use client'

import * as React from 'react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { OptionProps } from '@/lib/helper/type'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import PricePlanDetailState from '@/lib/price-plan-detail/state/price-plan-detail-state'
import { observer } from 'mobx-react-lite'

interface Props {
  options: OptionProps[],
  mainState: PricePlanDetailState
}

const UsageEventDialog = observer(({options, mainState}: Props) => {
  const [selected, setSelected] = React.useState<string[]>([])
  const [search, setSearch] = React.useState('')

  const toggleItem = (item: string) => {
    setSelected(prev =>
      prev.includes(item) ? prev.filter(i => i !== item) : [...prev, item]
    )
  }

  const filteredEvents = options.filter(event =>
    event.name.toLowerCase().includes(search.toLowerCase())
  )

  return (
    <Dialog open={mainState.getUsageEventModalIsOpen()} onOpenChange={(open) => mainState.setUsageEventModalIsOpen(open)}>
      <DialogContent className="w-[400px] max-h-[450px] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Usage Event</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <div className="flex justify-end mt-4 gap-2">
          <Button size="sm" variant="ghost" onClick={() => setSelected([])}>Cancel</Button>
          <Button size="sm" onClick={() => {
            mainState.setUsageEventModalIsOpen(false)
            mainState.setUsageEventSelected(selected)
            mainState.setFlow(1)
          }}>Save</Button>
        </div>
        <Input
          placeholder="Search..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          className="mb-2"
        />
        <div className="flex flex-col gap-2">
          {filteredEvents.length > 0 ? (
            filteredEvents.map((event, idx) => (
              <label key={idx} className="flex items-center gap-2 cursor-pointer">
                <Checkbox
                  checked={selected.includes(event.value)}
                  onCheckedChange={() => toggleItem(event.value)}
                />
                <span className="text-sm">{event.name}</span>
              </label>
            ))
          ) : (
            <span className="text-sm text-muted-foreground">No results found.</span>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
})

export default UsageEventDialog
