import React, { useRef } from 'react';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import TableHead from '@mui/material/TableHead';
import TableCell from '@mui/material/TableCell';
import TableSortLabel, { TableSortLabelProps } from '@mui/material/TableSortLabel';
import { alpha, styled } from '@mui/system';
import { SxProps, Theme } from '@mui/material/styles';
import dayjs, { Dayjs } from 'dayjs';
import { InputAdornment, InputBase, MenuItem, TableRow } from '@mui/material';
import FontAwesome from '../fontawesome';
import { faAngleDown, faAngleUp, faMagnifyingGlass } from '@fortawesome/free-solid-svg-icons';
import { visuallyHidden } from './styles';
import CustomDatePicker from '../date-picker/customDate';
import CustomYearMonthDatePicker from '../date-picker/CustomYearMonthDatePicker';
import ConditionalComponent from './ConditionalComponent';
import StatusMenuWithoutConfirmation from '@/shared/components/table/StatusMenuWithoutConfirmation';
import { StatusChip } from '@/shared/sections/contract/styles';
import { DatePicker, DatePickerProps } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';

// ----------------------------------------------------------------------
export const StyledTableRow = styled(TableRow)<{ borderTop?: SxProps<Theme> }>(
  ({ theme, borderTop }) => ({
    '&:not(:last-child)': {
      borderBottom: `2px solid ${alpha(theme.palette.primary.main, 0.1)}`,
    },
    '& > *:first-of-type': {
      borderBottomLeftRadius: '10px',
      ...(borderTop && borderTop),
    },
    '& > *:last-child': {
      borderTopRightRadius: '10px',
      borderBottomRightRadius: '10px',
    },
  })
);

// ----------------------------------------------------------------------

type Props = {
  order?: 'asc' | 'desc';
  orderBy?: string;
  headLabel: Array<{
    id: string;
    label: string;
    align?: 'left' | 'center' | 'right' | undefined | string;
    width?: number | string;
    minWidth?: number | string;
    type?: string;
    isNotSortable?: boolean;
  }>;
  onSort?: (id: string) => void;
  filters: Record<string, { value: string; condition: string }>;
  onFilters: (key: string, value: string, condition: string) => void;
  sx?: SxProps<Theme>;
  isTrajetTable?: boolean;
  isWithoutTabs?: boolean;
};

const StyledTableCell = styled(TableCell)<{ isCheckbox?: boolean }>(({ theme, isCheckbox }) => ({
  padding: theme.spacing(isCheckbox ? 0.5 : 1),
  verticalAlign: 'top',
}));

export default function TableHeadCustom({
  order,
  orderBy,
  headLabel,
  onSort,
  filters,
  onFilters,
  sx,
  isTrajetTable,
  isWithoutTabs,
}: Props) {
  const inputRefs = useRef<Record<string, HTMLInputElement | null>>({});

  const handleInputChange = (id: string, value: string) => {
    onFilters(id, value, 'contains');
    if (inputRefs.current[id]) {
      inputRefs.current[id]?.focus();
    }
  };

  const handleSort = (id: string) => {
    if (onSort) {
      onSort(id);
    }
  };

  return (
    <TableHead>
      <StyledTableRow borderTop={isWithoutTabs ? { borderTopLeftRadius: '10px' } : undefined}>
        {headLabel.map((headCell) => (
          <StyledTableCell
            key={headCell.id}
            sortDirection={orderBy === headCell.id ? order : false}
            sx={{
              ...(sx || {}),
              ...(headCell.width ? { width: headCell.width, minWidth: headCell.minWidth } : {}),
            }}
          >
            <Box sx={{ display: 'flex', flexDirection: 'column' }}>
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <ConditionalComponent
                  isValid={!!(onSort && !headCell.isNotSortable)}
                  defaultComponent={
                    <Box
                      component="span"
                      sx={{ whiteSpace: 'nowrap', color: 'text.disabled', p: '4px' }}
                    >
                      {headCell.label}
                    </Box>
                  }
                >
                  <CustomTableSortLabel
                    active={orderBy === headCell.id}
                    direction={orderBy === headCell.id ? order : 'desc'}
                    orderBy={orderBy}
                    order={order}
                    onSort={() => handleSort(headCell.id)}
                    isTrajetTable={isTrajetTable}
                  >
                    {headCell.label}
                  </CustomTableSortLabel>
                </ConditionalComponent>
              </Box>
              <ConditionalComponent isValid={headCell.type === 'date'}>
                <CustomDatePicker
                  value={filters[headCell.id]?.value ? dayjs(filters[headCell.id].value) : null}
                  onChange={(newValue: Dayjs | null) => {
                    newValue &&
                      newValue.isValid() &&
                      onFilters(headCell.id, newValue.format('YYYY-MM-DD'), '=');
                  }}
                  onClear={() => onFilters(headCell.id, '', '')}
                />
              </ConditionalComponent>

              <ConditionalComponent
                isValid={
                  headCell.type === 'text' ||
                  headCell.type === 'status' ||
                  headCell.type === 'number'
                }
              >
                <InputBase
                  fullWidth
                  value={filters[headCell.id]?.value || ''}
                  onChange={(e) => handleInputChange(headCell.id, e.target.value)}
                  inputRef={(ref) => {
                    if (ref) inputRefs.current[headCell.id] = ref;
                  }}
                  startAdornment={
                    <InputAdornment position="start">
                      <FontAwesome
                        icon={faMagnifyingGlass}
                        width={{
                          xs: 12,
                          xl: 14,
                        }}
                        sx={{ color: 'text.secondary' }}
                      />
                    </InputAdornment>
                  }
                  inputProps={{
                    sx: { typography: 'body2' },
                  }}
                />
              </ConditionalComponent>
              <ConditionalComponent isValid={headCell.type === 'select'}>
                <StatusMenuWithoutConfirmation
                  value={filters[headCell.id]?.value || ''}
                  options={[{ label: 'Tous', value: '' }, ...((headCell as any).options ?? [])]}
                  onChange={(newValue: string) => onFilters(headCell.id, newValue, '=')}
                  sx={{ width: '140px' }}
                  chipComponent={StatusChip}
                />
              </ConditionalComponent>
              <ConditionalComponent isValid={headCell.type === 'dateRoadMap'}>
                <CustomYearMonthDatePicker
                  value={filters[headCell.id]?.value ? dayjs(filters[headCell.id].value) : null}
                  onChange={(newValue: Dayjs | null) => {
                    newValue &&
                      newValue.isValid() &&
                      onFilters(headCell.id, newValue.format('YYYY-MM'), '=');
                  }}
                  onClear={() => onFilters(headCell.id, '', '')}
                />
              </ConditionalComponent>
              <ConditionalComponent isValid={headCell.type === 'none'}>
                <></>
              </ConditionalComponent>
            </Box>
          </StyledTableCell>
        ))}
      </StyledTableRow>
    </TableHead>
  );
}

interface CustomTableSortLabelProps extends Omit<TableSortLabelProps, 'IconComponent'> {
  orderBy?: string;
  order?: 'asc' | 'desc';
  onSort: () => void;
}

export function CustomTableSortLabel({
  orderBy,
  order,
  onSort,
  children,
  isTrajetTable,
  ...props
}: CustomTableSortLabelProps & { isTrajetTable?: boolean }) {
  return (
    <TableSortLabel
      active={props.active}
      direction={props.direction}
      onClick={onSort}
      hideSortIcon
      sx={{
        whiteSpace: 'nowrap',
        '&.Mui-active': {
          color: (theme) => theme.palette.primary.main,
          backgroundColor: isTrajetTable
            ? 'transparent'
            : (theme) => alpha(theme.palette.primary.main, 0.1),
        },
        color: (theme) => (props.active ? theme.palette.primary.main : theme.palette.text.disabled),
        backgroundColor: 'transparent',
        borderRadius: '4px',
        p: '4px',
        transition: 'background-color 0.3s',
      }}
      IconComponent={() =>
        props.active ? (
          <FontAwesome
            width={{ xs: 12, xl: 14 }}
            sx={{
              color: (theme) => theme.palette.primary.main,
              pl: 0.3,
            }}
            icon={order === 'desc' ? faAngleDown : faAngleUp}
          />
        ) : null
      }
      {...props}
    >
      {children}
      {props.active ? (
        <Box sx={{ ...visuallyHidden }}>
          {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
        </Box>
      ) : null}
    </TableSortLabel>
  );
}
