'use client'

import type React from 'react'
import { useCallback, useState } from 'react'
import { useIsMobile } from '../../hooks'
import { cn } from '../../utils'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandList,
} from '../Command'
import { inputVariants } from '../Input'
import {
  LegacyCombobox,
  LegacyComboboxContent,
  LegacyComboboxTrigger,
  LegacyComboboxValue,
  LegacyComboboxIcon,
  OptionRow,
  type LegacyComboboxProps,
} from '../LegacyCombobox'
import { MobileMenuSheetContent } from '../PageHeader/MobileMenuSheetContent'
import { Sheet, SheetTrigger, SheetClose } from '../Sheet/sheet'
import { typographyVariants } from '../Typography'

type WalletNetworkOption = {
  value: string
  label: string
  iconUrl?: string
  Icon?: React.ReactElement
}

export interface WalletNetworkSelectorProps
  extends Pick<
    LegacyComboboxProps,
    'size' | 'placeholder' | 'defaultOpen' | 'value' | 'onValueChange'
  > {
  className?: string
  options: WalletNetworkOption[]
  disabled?: boolean
}

export function WalletNetworkSelector({
  options,
  value,
  onValueChange,
  placeholder = 'Select network',
  className,
  defaultOpen,
  size = 'default',
  disabled = false,
  ...props
}: WalletNetworkSelectorProps) {
  const isMobile = useIsMobile()
  const [mobileOpen, setMobileOpen] = useState(false)

  const handleValueChange = useCallback(
    (newValue: string) => {
      onValueChange?.(newValue)
      if (isMobile) {
        setMobileOpen(false)
      }
    },
    [isMobile, onValueChange],
  )

  return (
    <LegacyCombobox
      size={size}
      value={value}
      onValueChange={handleValueChange}
      placeholder={placeholder}
      defaultOpen={defaultOpen}
      disabled={disabled}
      {...props}
    >
      {isMobile ? (
        <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
          <SheetTrigger asChild>
            <button
              type="button"
              disabled={disabled}
              className={cn(
                inputVariants({ size }),
                typographyVariants({
                  variant: size === 'default' ? 'body-s' : 'body-xs',
                }),
                'w-fit items-center border-none bg-muted pr-4 disabled:cursor-not-allowed disabled:opacity-50',
                '[&_[data-slot=combobox-value][data-placeholder=true]]:pl-1',
                className,
              )}
            >
              <LegacyComboboxValue placeholder={placeholder} hideText />
              <LegacyComboboxIcon className="flex h-3 w-3 items-center justify-center text-muted-foreground [&_path]:stroke-[3px] [&_svg]:block" />
            </button>
          </SheetTrigger>
          <MobileMenuSheetContent
            className={cn(
              typographyVariants({ variant: 'body-s', color: 'muted' }),
              'p-0',
            )}
          >
            <Command className="w-full">
              <CommandInput
                placeholder="Search..."
                className={cn(
                  size === 'sm' ? 'py-2' : 'py-3',
                  typographyVariants({
                    variant: size === 'sm' ? 'body-xs' : 'body-s',
                  }),
                )}
              />
              <CommandList>
                <CommandEmpty>No results found.</CommandEmpty>
                <CommandGroup>
                  {options.map(({ value, label, iconUrl, Icon }) => (
                    <SheetClose asChild key={value}>
                      <OptionRow value={value}>
                        {Icon ??
                          (iconUrl && (
                            <img
                              className="h-6 w-6 rounded-md"
                              width={24}
                              height={24}
                              src={iconUrl}
                              alt={label || 'Network Icon'}
                            />
                          ))}
                        {label}
                      </OptionRow>
                    </SheetClose>
                  ))}
                </CommandGroup>
              </CommandList>
            </Command>
          </MobileMenuSheetContent>
        </Sheet>
      ) : (
        <>
          <LegacyComboboxTrigger
            hideIcon
            className={cn(
              'w-fit items-center border-none bg-muted pr-4',
              '[&_[data-slot=combobox-value][data-placeholder=true]]:pl-1',
              className,
            )}
          >
            <LegacyComboboxValue placeholder={placeholder} hideText />
            <LegacyComboboxIcon className="flex h-3 w-3 items-center justify-center text-muted-foreground [&_path]:stroke-[3px] [&_svg]:block" />
          </LegacyComboboxTrigger>
          <LegacyComboboxContent>
            {options.map(({ value, label, iconUrl, Icon }) => (
              <OptionRow key={value} value={value}>
                {Icon ??
                  (iconUrl && (
                    <img
                      className="h-6 w-6 rounded-md"
                      width={24}
                      height={24}
                      src={iconUrl}
                      alt={label || 'Network Icon'}
                    />
                  ))}
                {label}
              </OptionRow>
            ))}
          </LegacyComboboxContent>
        </>
      )}
    </LegacyCombobox>
  )
}

WalletNetworkSelector.displayName = 'WalletNetworkSelector'
