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, 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 ConditionalComponent from './ConditionalComponent';

// ----------------------------------------------------------------------
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>
            </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>
  );
}

