'use client';

import React from 'react';
import {
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Checkbox,
  ListItemText,
  Avatar,
  Box,
  Chip,
  SelectChangeEvent,
} from '@mui/material';
import { Child } from '@/lib/api/children';
import { GroupAdd, Person } from '@mui/icons-material';

export type ChildSelectorMode = 'single' | 'multiple' | 'all';

interface ChildSelectorProps {
  children: Child[];
  selectedChildIds: string[];
  onChange: (childIds: string[]) => void;
  mode?: ChildSelectorMode;
  showAllOption?: boolean;
  label?: string;
  disabled?: boolean;
  compact?: boolean;
  required?: boolean;
}

export default function ChildSelector({
  children,
  selectedChildIds,
  onChange,
  mode = 'single',
  showAllOption = false,
  label = 'Select Child',
  disabled = false,
  compact = false,
  required = false,
}: ChildSelectorProps) {
  const handleChange = (event: SelectChangeEvent<string | string[]>) => {
    const value = event.target.value;

    if (mode === 'single') {
      // Single selection
      onChange(typeof value === 'string' ? [value] : value);
    } else {
      // Multiple selection
      const selectedIds = typeof value === 'string' ? value.split(',') : value;

      // Handle "All" option
      if (selectedIds.includes('all')) {
        if (selectedChildIds.length === children.length) {
          // Deselect all
          onChange([]);
        } else {
          // Select all
          onChange(children.map((c) => c.id));
        }
      } else {
        onChange(selectedIds);
      }
    }
  };

  const getDisplayValue = () => {
    if (selectedChildIds.length === 0) {
      return '';
    }

    if (mode === 'single') {
      return selectedChildIds[0] || '';
    }

    // Multiple mode
    if (showAllOption && selectedChildIds.length === children.length) {
      return 'all';
    }

    return selectedChildIds;
  };

  const renderValue = (selected: string | string[]) => {
    if (!selected || (Array.isArray(selected) && selected.length === 0)) {
      return <em>None selected</em>;
    }

    if (mode === 'single') {
      const child = children.find((c) => c.id === selected);
      if (!child) return <em>None selected</em>;

      return (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Avatar
            src={child.photoUrl}
            sx={{
              width: compact ? 24 : 32,
              height: compact ? 24 : 32,
              bgcolor: child.displayColor,
            }}
          >
            {child.name[0]}
          </Avatar>
          {child.name}
        </Box>
      );
    }

    // Multiple mode
    if (showAllOption && Array.isArray(selected) && selected.includes('all')) {
      return (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
          <Chip
            icon={<GroupAdd />}
            label="All Children"
            size="small"
            sx={{ bgcolor: 'primary.light' }}
          />
        </Box>
      );
    }

    const selectedIds = Array.isArray(selected) ? selected : [selected];
    return (
      <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
        {selectedIds.map((id) => {
          const child = children.find((c) => c.id === id);
          if (!child) return null;

          return (
            <Chip
              key={id}
              avatar={
                <Avatar
                  src={child.photoUrl}
                  sx={{ bgcolor: child.displayColor }}
                >
                  {child.name[0]}
                </Avatar>
              }
              label={child.nickname || child.name}
              size="small"
              sx={{
                bgcolor: `${child.displayColor}20`,
                borderColor: child.displayColor,
                borderWidth: 1,
                borderStyle: 'solid',
              }}
            />
          );
        })}
      </Box>
    );
  };

  if (children.length === 0) {
    return (
      <FormControl fullWidth disabled>
        <InputLabel>No children available</InputLabel>
        <Select value="" label="No children available">
          <MenuItem value="">No children available</MenuItem>
        </Select>
      </FormControl>
    );
  }

  // Single child - show simplified selector
  if (children.length === 1 && mode === 'single') {
    const child = children[0];
    return (
      <FormControl fullWidth disabled={disabled}>
        <InputLabel>{label}</InputLabel>
        <Select value={child.id} label={label}>
          <MenuItem value={child.id}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Avatar
                src={child.photoUrl}
                sx={{
                  width: compact ? 24 : 32,
                  height: compact ? 24 : 32,
                  bgcolor: child.displayColor,
                }}
              >
                {child.name[0]}
              </Avatar>
              {child.name}
            </Box>
          </MenuItem>
        </Select>
      </FormControl>
    );
  }

  return (
    <FormControl fullWidth required={required} disabled={disabled}>
      <InputLabel>{label}</InputLabel>
      <Select
        value={getDisplayValue()}
        onChange={handleChange}
        label={label}
        multiple={mode === 'multiple'}
        renderValue={renderValue}
      >
        {showAllOption && mode === 'multiple' && (
          <MenuItem value="all">
            <Checkbox
              checked={selectedChildIds.length === children.length}
              indeterminate={
                selectedChildIds.length > 0 &&
                selectedChildIds.length < children.length
              }
            />
            <ListItemText primary="All Children" />
          </MenuItem>
        )}

        {children
          .sort((a, b) => a.sortOrder - b.sortOrder)
          .map((child) => (
            <MenuItem key={child.id} value={child.id}>
              {mode === 'multiple' && (
                <Checkbox checked={selectedChildIds.includes(child.id)} />
              )}
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 1,
                  flex: 1,
                }}
              >
                <Avatar
                  src={child.photoUrl}
                  sx={{
                    width: compact ? 24 : 32,
                    height: compact ? 24 : 32,
                    bgcolor: child.displayColor,
                  }}
                >
                  {child.name[0]}
                </Avatar>
                <Box sx={{ flex: 1 }}>
                  <ListItemText
                    primary={child.name}
                    secondary={child.nickname}
                  />
                </Box>
                {!compact && (
                  <Box
                    sx={{
                      width: 12,
                      height: 12,
                      borderRadius: '50%',
                      bgcolor: child.displayColor,
                    }}
                  />
                )}
              </Box>
            </MenuItem>
          ))}
      </Select>
    </FormControl>
  );
}
