import { useState, useMemo, type JSX } from 'react'
import { Box, Button, Grid, ListItem, List, ListItemText } from '@mui/material'
import { ListDataSkeleton } from './list-data-skeleton'
import { NoDataAlert } from '../no-data-alert/no-data-alert'
import { useSkeleton } from '../../hooks/use-skeleton'
import type { ListDataProps } from './types'
import { styles } from './styles'
import { SmartTooltip } from '../smart-tooltip/smart-tooltip'

const DEFAULT_LABELS = {
  showMore: 'Show More',
  showLess: 'Show Less',
} as const

const EMPTY_DATA: ListDataProps['data'] = []

/**
 * Displays structured data in an accessible list format with expandable views, interactive selection, tooltips, and loading states.
 *
 * @example
 * ```tsx
 * <ListDataUI
 *   data={[
 *     { id: '1', label: 'Population', value: '8.4M' },
 *     { id: '2', label: 'Median Age', value: '32 years' },
 *   ]}
 *   maxItems={3}
 *   onItemClick={(item) => setSelectedId(item.id)}
 *   selectedItemId={selectedId}
 * />
 * ```
 */
export function ListDataUI({
  data = EMPTY_DATA,
  isLoading = false,
  maxItems = 5,
  labels = DEFAULT_LABELS,
  showDivider = true,
  selectedItemId,
  tooltipProps,
  onExpand,
  onItemClick,
}: ListDataProps): JSX.Element {
  const [showAll, setShowAll] = useState(false)

  const showSkeleton = useSkeleton(isLoading)

  const items = useMemo(() => {
    return showAll ? data : data.slice(0, maxItems)
  }, [data, maxItems, showAll])

  const handleToggle = () => {
    setShowAll(!showAll)
    onExpand?.(showAll)
  }

  if (showSkeleton) {
    return <ListDataSkeleton length={maxItems} />
  }

  if (items.length === 0) {
    return <NoDataAlert />
  }

  return (
    <>
      <List id='expandable-list' role='list'>
        {items.map((item) => (
          <SmartTooltip<HTMLLIElement>
            // Default tooltip props
            followCursor={false}
            key={item.id}
            placement='top'
            arrow
            title={item.tooltipTitle}
            enterDelay={10}
            // Custom tooltip props
            {...tooltipProps}
          >
            {({ ref }) => (
              <ListItem
                ref={ref}
                role='listitem'
                sx={{
                  ...(showDivider && styles.showDivider),
                  ...(onItemClick && styles.clickable),
                  ...(selectedItemId === item.id && styles.selected),
                  ...(item.disabled && styles.disabled),
                }}
                onClick={() => {
                  if (item.disabled) return
                  onItemClick?.(item)
                }}
              >
                <Grid container alignItems='center'>
                  <Grid item xs={8}>
                    <ListItemText primary={item.label} sx={styles.label} />
                  </Grid>
                  <Grid item xs={4}>
                    <ListItemText primary={item.value} sx={styles.value} />
                  </Grid>
                </Grid>
              </ListItem>
            )}
          </SmartTooltip>
        ))}
      </List>

      {data.length > maxItems && (
        <Box my={2}>
          <Button
            onClick={handleToggle}
            variant='text'
            color='primary'
            aria-expanded={showAll}
            aria-controls='expandable-list'
          >
            {showAll ? labels.showLess : labels.showMore}
          </Button>
        </Box>
      )}
    </>
  )
}
