'use client';

import React, { useCallback, useMemo } from 'react';
import { Button, MenuItem, IconButton, Grid, Box, InputAdornment, Typography } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';
import FontAwesome from '@/shared/components/fontawesome';
import { faFilter, faXmark } from '@fortawesome/free-solid-svg-icons';
import { lightColor, StyledSelect, StyledTextField } from './styles';
import { _CONTRACT_STATUS, _OPTION_ACTIF } from '@/shared/_mock/_Contrat';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import SvgColor from '@/shared/components/svg-color';
import { useTableFilter } from '@/hooks/use-table-filter';
import { Column } from '../column-selector/types';
import CustomDatePicker from '../date-picker/customDate';
import dayjs, { Dayjs } from 'dayjs';
import { _CIRCUIT_STATUS } from '@/shared/_mock/_circuit';
import { iconButtonStyles, StyledMenuItem, WhiteIconButtonStyle } from '@/shared/theme/css';
import { TableType } from '@/shared/types/common';
import { _BINARY_Qst, _TRAJET_TYPE } from '@/shared/_mock/_trajets';
import { _SENS_AR } from '@/shared/_mock';
import { _TRAJET_ETAT } from '../../_mock/_trajets';
import { _OPTION_DEMANDE } from '@/shared/sections/absence/utils/form-fields-absence';
import { APPOINTMENT_STATUS } from '@/shared/_mock/_appointment';
import { ZONES } from '@/shared/sections/establishment/vacance/utils/form-fields-vacance';
import { _TEAM_STATUS } from '@/shared/_mock/_equipes';
import { _AGENT_STATUS } from '@/shared/_mock/_agent';
import { ROLE_STATUS } from '@/shared/_mock/_roles';
import { _EXPORT_OPTION_STATUT } from '@/shared/_mock/_export';

interface TableFilterProps {
  onFilters: (key: string, value: string, condition: string) => void;
  onResetFilters: () => void;
  initialColumns: { id: string; label: string; type?: string, options?: { value: string; label: string }[] }[];
  type: string;
  isChild?: boolean;
}

interface FilterRow {
  id: string;
  attribute: string;
  condition: string;
  value: string;
}

const CONDITIONS = [
  { value: 'contains', label: 'Contient' },
  { value: 'equals', label: 'Est égal à' },
  { value: 'startsWith', label: 'Commence par' },
  { value: 'endsWith', label: 'Se termine par' },
];

const ACTIVE_Options = [
  { value: 'true', label: 'Actif' },
  { value: 'false', label: 'Inactif' }
]

const DATE_CONDITIONS = [
  { value: '<', label: 'Avant' },
  { value: '=', label: 'Égal à' },
  { value: '>', label: 'Après' },
];

export default function TableFilter({
  onFilters,
  onResetFilters,
  initialColumns,
  type,
  isChild = false,
}: TableFilterProps) {
  const popover = usePopover();
  const { localFilters, addFilter, removeFilter, updateFilter, clearFilters } = useTableFilter();
  const attributes = useMemo(
    () =>
      initialColumns.map((col) => ({
        id: col.id,
        value: col.id,
        label: col.label,
        type: col.type,
        options: col.options,
      })),
    [initialColumns]
  );

  const applyFilters = React.useCallback(() => {
    onResetFilters();
    const appliedColumns = localFilters
      .filter((row) => row.attribute && row.value)
      .map((row) => {
        const column = attributes.find((attr) => attr.value === row.attribute);
        if (column) {
          onFilters(row.attribute, row.value, row.condition);
        }
        return column ? { id: column.value, label: column.label } : null;
      })
      .filter((col): col is Column => col !== null);

    popover.onClose();
  }, [onResetFilters, localFilters, popover, attributes, onFilters]);

  const handleClearFilters = useCallback(() => {
    clearFilters();
    onResetFilters();
  }, [clearFilters, onResetFilters]);

  const renderFilterCondition = (filter: FilterRow, attribute: Column) => {
    if (!attribute) return null;

    switch (attribute.type) {
      case 'text':
        return (
          <>
            <Grid item xs={6}>
              <StyledSelect
                fullWidth
                value={filter.condition || 'contains'}
                onChange={(e) => updateFilter(filter.id, 'condition', e.target.value as string)}
              >
                {CONDITIONS.map((condition) => (
                  <StyledMenuItem key={condition.value} value={condition.value}>
                    {condition.label}
                  </StyledMenuItem>
                ))}
              </StyledSelect>
            </Grid>
            <Grid item xs={6}>
              <StyledTextField
                fullWidth
                placeholder="Saisissez une valeur..."
                value={filter.value}
                onChange={(e) => updateFilter(filter.id, 'value', e.target.value)}
              />
            </Grid>
          </>
        );
      case 'date':
        return (
          <>
            <Grid item xs={6}>
              <StyledSelect
                fullWidth
                value={filter.condition || '='}
                onChange={(e) => updateFilter(filter.id, 'condition', e.target.value as string)}
              >
                {DATE_CONDITIONS.map((condition) => (
                  <StyledMenuItem key={condition.value} value={condition.value}>
                    {condition.label}
                  </StyledMenuItem>
                ))}
              </StyledSelect>
            </Grid>
            <Grid item xs={6}>
              <CustomDatePicker
                value={filter.value ? dayjs(filter.value) : null}
                onChange={(newValue: Dayjs | null) => {
                  newValue &&
                    newValue.isValid() &&
                    updateFilter(filter.id, 'value', newValue.format('YYYY-MM-DD'),);
                }}
                onClear={() => updateFilter(filter.id, 'value', '')}
              />
            </Grid>
          </>
        );
      case 'boolean':
        const booleanOptions = type === TableType.Contrat || type === TableType.Avenant || type === TableType.Demande ? 'Actif' : 'Archiver';
        return (
          <Grid item xs={12}>
              <StyledSelect
                fullWidth
                value={filter.value}
                onChange={(e) => updateFilter(filter.id, 'value', e.target.value as string)}
                displayEmpty
                renderValue={(selected) => {
                  if (selected === '') {
                    return <Typography sx={{ color: '#A2A6AB' }}>Sélectionnez une option</Typography>;
                  }
                  return ACTIVE_Options.find(option => option.value === selected)?.label || '';
                }}
              >
                {ACTIVE_Options.map(option => (
                  <StyledMenuItem key={option.value} value={option.value}>
                    {option.label}
                  </StyledMenuItem>
                ))}
              </StyledSelect>
          </Grid>
        );
      case 'status':
        let statusOptions;
        if(attribute.options) {
          statusOptions = attribute.options;
        } else {
          switch (type) {
            case TableType.Trajet:
              if (['peages', 'rotation'].includes(filter.attribute)) {
              statusOptions = _BINARY_Qst;
            } else if (filter.attribute === 'sensAR') {
              statusOptions = _SENS_AR;
            } else if (filter.attribute === 'typeTrajet') {
              statusOptions = _TRAJET_TYPE;
            } else {
              statusOptions = _TRAJET_ETAT;
            }
            break;
          case TableType.Contrat:
            statusOptions = _CONTRACT_STATUS;
            break;
          case TableType.AbsenceUsager:
            statusOptions = _OPTION_DEMANDE;
            break;
          case TableType.Vacance:
            statusOptions = ZONES;
          break;
          case TableType.Equipe:
            statusOptions = _TEAM_STATUS;
          break;
          case TableType.Agent:
            statusOptions = _AGENT_STATUS;
          break;
          case TableType.Role:
            statusOptions = ROLE_STATUS;
          break;
            case TableType.Appointment:
              statusOptions = APPOINTMENT_STATUS;
              break;
          case TableType.Export:
            if ('downloaded'===filter.attribute) {
              statusOptions = _BINARY_Qst;
            } else {
              statusOptions = _EXPORT_OPTION_STATUT;
            }
            break;
          default:
            statusOptions = _CIRCUIT_STATUS;
          }
        }
        return (
          <Grid item xs={12}>
            <StyledSelect
              fullWidth
              value={filter.value}
              onChange={(e) => updateFilter(filter.id, 'value', e.target.value as string)}
              displayEmpty
              renderValue={(selected) => {
                if (selected === '') {
                  return <Typography sx={{ color: '#A2A6AB' }}>Sélectionnez une option</Typography>;
                }
                return statusOptions.find(option => option.value === selected)?.label || '';
              }}
          >
              {statusOptions.map((status) => (
                <StyledMenuItem key={status.value} value={status.value}>
                  {status.label}
                </StyledMenuItem>
              ))}
            </StyledSelect>
          </Grid>
        );
      default:
        return null;
    }
  };

  return (
    <>
      <CustomTooltip title="Filtrer" arrow>
        <IconButton
          sx={ 
            isChild ? lightColor 
            : type === 'document'
                ? iconButtonStyles
                : WhiteIconButtonStyle
          }
          onClick={popover.onOpen}
        >
          <FontAwesome icon={faFilter} width={16} />
        </IconButton>
      </CustomTooltip>
      <CustomPopover
        arrow="top-right"
        hiddenArrow={true}
        open={popover.open}
        onClose={popover.onClose}
        sx={{
          width: {
            xs: 465,
            lg: 525,
            xl: 585,
          },
          borderRadius: {
            xs: 3,
            lg: 4,
          },
          px: {
            xs: 1.5,
            lg: 2,
          },
          py: {
            xs: 1.5,
            lg: 2,
          },
          mt: {
            xs: 1.5,
            lg: 2,
          },
        }}
      >
        <Box display="flex" sx={{ pb: 2 }} justifyContent="space-between" alignItems="center">
          <Button
            variant="text"
            onClick={handleClearFilters}
            sx={{
              color: 'text.disabled',
              textTransform: 'none',
            }}
          >
            Effacer tout
          </Button>
          <Box>
            <Button
              variant="text"
              onClick={addFilter}
              startIcon={<AddIcon sx={{ color: (theme) => theme.palette.primary.main }} />}
              sx={{
                color: (theme) => theme.palette.primary.main,
                textTransform: 'none',
              }}
            >
              Ajouter un filtre
            </Button>
          </Box>
        </Box>

        {localFilters.map((filter) => (
          <Grid container key={filter.id} spacing={1} alignItems="center" sx={{ mb: 2 }}>
            <Grid item xs={5}>
              <StyledSelect
                fullWidth
                value={filter.attribute}
                startAdornment={
                  <InputAdornment sx={{ m: 0 }} position="start">
                    <SvgColor src="/assets/icons/ic_table.svg" sx={{ width: '20px' }} />
                  </InputAdornment>
                }
                onChange={(e) => updateFilter(filter.id, 'attribute', e.target.value as string)}
                displayEmpty
              >
                <StyledMenuItem value="" disabled>
                  Attribut
                </StyledMenuItem>
                {attributes.map((attr) => (
                  <StyledMenuItem key={attr.value} value={attr.value}>
                    {attr.label}
                  </StyledMenuItem>
                ))}
              </StyledSelect>
            </Grid>
            <Grid container item xs={6} spacing={1} alignItems="center">
              {filter.attribute &&
                renderFilterCondition(
                  filter,
                  attributes.find((attr) => attr.value === filter.attribute)!
                )}
            </Grid>
            <Grid item xs={1}>
              <IconButton
                onClick={() => removeFilter(filter.id)}
                disabled={localFilters.length === 1}
                size="small"
              >
                <FontAwesome icon={faXmark} />
              </IconButton>
            </Grid>
          </Grid>
        ))}
        <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 3 }}>
          <Button
            size="medium"
            variant="contained"
            onClick={applyFilters}
            disabled={!localFilters.some((f) => f.attribute && f.value)}
            sx={{
              bgcolor: (theme) => theme.palette.primary.main,
              textTransform: 'none',
              boxShadow: 'none',
              '&:hover': {
                backgroundColor: (theme) => theme.palette.primary.dark,
              },
            }}
          >
            Appliquer les filtres
          </Button>
        </Box>
      </CustomPopover>
    </>
  );
}
