'use client';

import { useState, useCallback, useEffect } from 'react';
import { useOrderFilters } from '../hooks/useOrderFilters';
import { useOrders } from '../hooks/useOrders';
import {
  Box,
  TextField,
  MenuItem,
  Button,
  Grid,
  Autocomplete,
  Paper,
  Tooltip,
  Collapse,
  CircularProgress,
  Badge,
  type AutocompleteRenderInputParams,
} from '@mui/material';
import { useStores } from '../store/useStores';
import { useCustomers } from '../hooks/useCustomers';
import { useSellers } from '../hooks/useSellers';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
import {
  Search as SearchIcon,
  RestartAlt as ResetIcon,
  ExpandLess as ExpandLessIcon,
  ExpandMore as ExpandMoreIcon,
} from '@mui/icons-material';
import moment from 'moment';
import 'moment/locale/pt-br';

moment.locale('pt-br');

interface LocalFilters {
  status: string | null;
  orderId: number | null;
  customerId: number | null;
  customerName: string | null;
  createDateIni: string | null;
  createDateEnd: string | null;
  store: string[] | null;
  stockId: string[] | null;
  sellerId: string | null;
  sellerName: string | null;
}

const getInitialLocalFilters = (
  urlFilters: Partial<LocalFilters>
): LocalFilters => ({
  status: urlFilters.status ?? null,
  orderId: urlFilters.orderId ?? null,
  customerId: urlFilters.customerId ?? null,
  customerName: urlFilters.customerName ?? null,
  createDateIni: urlFilters.createDateIni ?? null,
  createDateEnd: urlFilters.createDateEnd ?? null,
  store: urlFilters.store ?? null,
  stockId: urlFilters.stockId ?? null,
  sellerId: urlFilters.sellerId ?? null,
  sellerName: urlFilters.sellerName ?? null,
});

export const SearchBar = () => {
  const [urlFilters, setUrlFilters] = useOrderFilters();

  const [localFilters, setLocalFilters] = useState<LocalFilters>(() =>
    getInitialLocalFilters(urlFilters)
  );

  const stores = useStores();
  const sellers = useSellers();
  const [customerSearchTerm, setCustomerSearchTerm] = useState('');
  const customers = useCustomers(customerSearchTerm);
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
  const { isFetching } = useOrders();
  const [touchedFields, setTouchedFields] = useState<{
    createDateIni?: boolean;
    createDateEnd?: boolean;
  }>({});

  useEffect(() => {
    setLocalFilters(getInitialLocalFilters(urlFilters));
  }, [urlFilters]);

  const updateLocalFilter = useCallback(
    <K extends keyof LocalFilters>(key: K, value: LocalFilters[K]) => {
      setLocalFilters((prev) => ({ ...prev, [key]: value }));
    },
    []
  );

  const handleReset = useCallback(() => {
    setTouchedFields({});
    setCustomerSearchTerm('');

    const resetState = {
      status: null,
      sellerName: null,
      sellerId: null,
      codfilial: null,
      codusur2: null,
      store: null,
      orderId: null,
      productId: null,
      stockId: null,
      hasPreBox: false,
      includeCheckout: false,
      createDateIni: null,
      createDateEnd: null,
      searchTriggered: false,
      customerId: null,
      customerName: null,
    };

    setLocalFilters(getInitialLocalFilters(resetState));
    setUrlFilters(resetState);
  }, [setUrlFilters]);

  const validateDates = useCallback(() => {
    if (!localFilters.createDateIni || !localFilters.createDateEnd) {
      return null;
    }
    const dateIni = moment(localFilters.createDateIni, 'YYYY-MM-DD');
    const dateEnd = moment(localFilters.createDateEnd, 'YYYY-MM-DD');
    if (dateEnd.isBefore(dateIni)) {
      return 'Data final não pode ser anterior à data inicial';
    }
    return null;
  }, [localFilters.createDateIni, localFilters.createDateEnd]);

  const handleFilter = useCallback(() => {
    if (!localFilters.createDateIni) {
      setTouchedFields((prev) => ({ ...prev, createDateIni: true }));
      return;
    }

    const dateError = validateDates();
    if (dateError) {
      setTouchedFields((prev) => ({ ...prev, createDateEnd: true }));
      return;
    }

    setUrlFilters({
      ...localFilters,
      searchTriggered: true,
    });
  }, [localFilters, setUrlFilters, validateDates]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        const isValid = !!localFilters.createDateIni;
        const dateErr = validateDates();
        if (isValid && !dateErr) {
          handleFilter();
        }
      }
    },
    [localFilters.createDateIni, validateDates, handleFilter]
  );

  const isDateValid = !!localFilters.createDateIni;
  const dateError = validateDates();
  const showDateIniError =
    touchedFields.createDateIni && !localFilters.createDateIni;
  const showDateEndError = touchedFields.createDateEnd && dateError;

  // Contador de filtros avançados ativos
  const advancedFiltersCount = [
    localFilters.store?.length,
    localFilters.stockId?.length,
    localFilters.sellerId,
  ].filter(Boolean).length;

  return (
    <Paper
      sx={{
        p: { xs: 2, md: 3 },
        mb: 2,
        bgcolor: 'background.paper',
        borderRadius: 2,
        boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
      }}
      elevation={0}
      onKeyDown={handleKeyDown}
    >
      <Grid container spacing={{ xs: 1.5, md: 2 }} alignItems="flex-end">
        {/* --- Primary Filters (Always Visible) --- */}

        {/* Campo de Texto Simples (Nº Pedido) */}
        <Grid size={{ xs: 12, sm: 6, md: 2 }}>
          <TextField
            fullWidth
            label="Nº do Pedido"
            variant="outlined"
            size="small"
            type="number"
            value={localFilters.orderId ?? ''}
            onChange={(e) => {
              const value = e.target.value ? Number(e.target.value) : null;
              updateLocalFilter('orderId', value);
            }}
            slotProps={{ htmlInput: { min: 0 } }}
            placeholder="Ex: 12345"
          />
        </Grid>

        {/* Select do MUI (Situação) */}
        <Grid size={{ xs: 12, sm: 6, md: 2 }}>
          <TextField
            select
            fullWidth
            label="Situação"
            size="small"
            value={localFilters.status ?? ''}
            onChange={(e) => {
              const value = e.target.value || null;
              updateLocalFilter('status', value);
            }}
          >
            <MenuItem value="">Todos</MenuItem>
            <MenuItem value="P">Pendente</MenuItem>
            <MenuItem value="F">Faturado</MenuItem>
            <MenuItem value="C">Cancelado</MenuItem>
          </TextField>
        </Grid>

        {/* Autocomplete do MUI para Cliente */}
        <Grid size={{ xs: 12, sm: 6, md: 2 }}>
          <Autocomplete
            size="small"
            options={customers.options}
            getOptionLabel={(option) => option.label}
            isOptionEqualToValue={(option, value) => option.id === value.id}
            value={
              customers.options.find(
                (option) => localFilters.customerId === option.customer?.id
              ) || null
            }
            onChange={(_, newValue) => {
              if (!newValue) {
                updateLocalFilter('customerName', null);
                updateLocalFilter('customerId', null);
                setCustomerSearchTerm('');
                return;
              }

              updateLocalFilter('customerId', newValue.customer?.id || null);
              updateLocalFilter(
                'customerName',
                newValue.customer?.name || null
              );
            }}
            onInputChange={(_, newInputValue, reason) => {
              if (reason === 'clear') {
                updateLocalFilter('customerName', null);
                updateLocalFilter('customerId', null);
                setCustomerSearchTerm('');
                return;
              }

              if (reason === 'input') {
                setCustomerSearchTerm(newInputValue);
                if (!newInputValue) {
                  updateLocalFilter('customerName', null);
                  updateLocalFilter('customerId', null);
                  setCustomerSearchTerm('');
                }
              }
            }}
            loading={customers.isLoading}
            renderInput={(params: AutocompleteRenderInputParams) => (
              <TextField
                {...params}
                label="Cliente"
                placeholder="Digite para buscar..."
              />
            )}
            noOptionsText={
              customerSearchTerm.length < 2
                ? 'Digite pelo menos 2 caracteres'
                : 'Nenhum cliente encontrado'
            }
            loadingText="Buscando clientes..."
            filterOptions={(x) => x}
            clearOnBlur={false}
            selectOnFocus
            handleHomeEndKeys
          />
        </Grid>

        {/* Campos de Data */}
        <Grid size={{ xs: 12, sm: 12, md: 3.5 }}>
          <LocalizationProvider
            dateAdapter={AdapterMoment}
            adapterLocale="pt-br"
          >
            <Box display="flex" gap={{ xs: 1.5, md: 2 }} flexDirection={{ xs: 'column', sm: 'row' }}>
              <Box flex={1}>
                <DatePicker
                  label="Data Inicial"
                  value={
                    localFilters.createDateIni
                      ? moment(localFilters.createDateIni, 'YYYY-MM-DD')
                      : null
                  }
                  onChange={(date: moment.Moment | null) => {
                    setTouchedFields((prev) => ({
                      ...prev,
                      createDateIni: true,
                    }));
                    updateLocalFilter(
                      'createDateIni',
                      date ? date.format('YYYY-MM-DD') : null
                    );
                  }}
                  format="DD/MM/YYYY"
                  maxDate={
                    localFilters.createDateEnd
                      ? moment(localFilters.createDateEnd, 'YYYY-MM-DD')
                      : undefined
                  }
                  slotProps={{
                    textField: {
                      size: 'small',
                      fullWidth: true,
                      required: true,
                      error: showDateIniError,
                      helperText: showDateIniError
                        ? 'Data inicial é obrigatória'
                        : '',
                      onBlur: () =>
                        setTouchedFields((prev) => ({
                          ...prev,
                          createDateIni: true,
                        })),
                      inputProps: {
                        'aria-required': true,
                      },
                    },
                  }}
                />
              </Box>
              <Box flex={1}>
                <DatePicker
                  label="Data Final (opcional)"
                  value={
                    localFilters.createDateEnd
                      ? moment(localFilters.createDateEnd, 'YYYY-MM-DD')
                      : null
                  }
                  onChange={(date: moment.Moment | null) => {
                    setTouchedFields((prev) => ({
                      ...prev,
                      createDateEnd: true,
                    }));
                    updateLocalFilter(
                      'createDateEnd',
                      date ? date.format('YYYY-MM-DD') : null
                    );
                  }}
                  format="DD/MM/YYYY"
                  minDate={
                    localFilters.createDateIni
                      ? moment(localFilters.createDateIni, 'YYYY-MM-DD')
                      : undefined
                  }
                  slotProps={{
                    textField: {
                      size: 'small',
                      fullWidth: true,
                      error: !!showDateEndError,
                      helperText: showDateEndError || '',
                      onBlur: () =>
                        setTouchedFields((prev) => ({
                          ...prev,
                          createDateEnd: true,
                        })),
                      inputProps: {
                        placeholder: 'Opcional',
                      },
                    },
                  }}
                />
              </Box>
            </Box>
          </LocalizationProvider>
        </Grid>

        {/* Botão Mais Filtros - inline com filtros primários */}
        <Grid
          size={{ xs: 12, sm: 12, md: 2.5 }}
          sx={{ display: 'flex', alignItems: 'flex-end', justifyContent: { xs: 'flex-start', md: 'flex-end' } }}
        >
          <Badge
            badgeContent={advancedFiltersCount}
            color="primary"
            invisible={advancedFiltersCount === 0}
          >
            <Button
              size="small"
              onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
              endIcon={
                showAdvancedFilters ? <ExpandLessIcon /> : <ExpandMoreIcon />
              }
              aria-label={showAdvancedFilters ? 'Ocultar filtros avançados' : 'Mostrar filtros avançados'}
              sx={{ textTransform: 'none', color: 'text.secondary', minHeight: 40 }}
            >
              {showAdvancedFilters ? 'Menos filtros' : 'Mais filtros'}
            </Button>
          </Badge>
        </Grid>

        {/* Botões de Ação - nova linha abaixo */}
        <Grid
          size={{ xs: 12 }}
          sx={{ display: 'flex', justifyContent: 'flex-end', mt: 1 }}
        >
          <Box sx={{ display: 'flex', gap: 1, width: { xs: '100%', sm: 'auto' }, flexWrap: 'nowrap' }}>
            <Tooltip title="Limpar filtros" arrow>
              <span>
                <Button
                  variant="outlined"
                  color="inherit"
                  size="small"
                  onClick={handleReset}
                  aria-label="Limpar filtros"
                  sx={{
                    minWidth: { xs: 'auto', sm: 90 },
                    minHeight: 32,
                    px: 1.5,
                    flexShrink: 0,
                    flex: { xs: 1, sm: 'none' },
                    fontSize: '0.8125rem',
                    '&:hover': {
                      bgcolor: 'action.hover',
                    },
                  }}
                >
                  <ResetIcon sx={{ mr: 0.5, fontSize: 18 }} />
                  Limpar
                </Button>
              </span>
            </Tooltip>
            <Tooltip
              title={
                isDateValid
                  ? 'Buscar pedidos'
                  : 'Preencha a data inicial para buscar'
              }
              arrow
            >
              <span>
                <Button
                  variant="contained"
                  color="primary"
                  size="small"
                  onClick={handleFilter}
                  disabled={!isDateValid || !!dateError || isFetching}
                  aria-label="Buscar pedidos"
                  sx={{
                    minWidth: { xs: 'auto', sm: 90 },
                    minHeight: 32,
                    px: 1.5,
                    flexShrink: 0,
                    flex: { xs: 1, sm: 'none' },
                    fontSize: '0.8125rem',
                    '&:disabled': {
                      opacity: 0.6,
                    },
                  }}
                >
                  {isFetching ? (
                    <CircularProgress size={16} color="inherit" />
                  ) : (
                    <>
                      <SearchIcon sx={{ mr: 0.5, fontSize: 18 }} />
                      Buscar
                    </>
                  )}
                </Button>
              </span>
            </Tooltip>
          </Box>
        </Grid>

        {/* --- Advanced Filters (Collapsible) --- */}
        <Grid size={{ xs: 12 }}>
          <Collapse in={showAdvancedFilters}>
            <Grid container spacing={2} sx={{ pt: 2 }}>
              {/* Autocomplete do MUI para Múltiplas Filiais (codfilial) */}
              <Grid size={{ xs: 12, sm: 6, md: 3 }}>
                <Autocomplete
                  multiple
                  size="small"
                  options={stores.options}
                  getOptionLabel={(option) => option.label}
                  isOptionEqualToValue={(option, value) =>
                    option.id === value.id
                  }
                  value={stores.options.filter((option) =>
                    localFilters.store?.includes(option.value)
                  )}
                  onChange={(_, newValue) => {
                    updateLocalFilter(
                      'store',
                      newValue.map((option) => option.value)
                    );
                  }}
                  loading={stores.isLoading}
                  renderInput={(params: AutocompleteRenderInputParams) => (
                    <TextField
                      {...params}
                      label="Filiais"
                      placeholder={
                        localFilters.store?.length
                          ? `${localFilters.store.length} selecionadas`
                          : 'Selecione'
                      }
                    />
                  )}
                />
              </Grid>

              {/* Autocomplete do MUI para Filial de Estoque */}
              <Grid size={{ xs: 12, sm: 6, md: 3 }}>
                <Autocomplete
                  multiple
                  size="small"
                  options={stores.options}
                  getOptionLabel={(option) => option.label}
                  isOptionEqualToValue={(option, value) =>
                    option.id === value.id
                  }
                  value={stores.options.filter((option) =>
                    localFilters.stockId?.includes(option.value)
                  )}
                  onChange={(_, newValue) => {
                    updateLocalFilter(
                      'stockId',
                      newValue.map((option) => option.value)
                    );
                  }}
                  loading={stores.isLoading}
                  renderInput={(params: AutocompleteRenderInputParams) => (
                    <TextField
                      {...params}
                      label="Filial de Estoque"
                      placeholder={
                        localFilters.stockId?.length
                          ? `${localFilters.stockId.length} selecionadas`
                          : 'Selecione'
                      }
                    />
                  )}
                />
              </Grid>

              {/* Autocomplete do MUI para Vendedor */}
              <Grid size={{ xs: 12, sm: 6, md: 3 }}>
                <Autocomplete
                  size="small"
                  options={sellers.options}
                  getOptionLabel={(option) => option.label}
                  isOptionEqualToValue={(option, value) =>
                    option.id === value.id
                  }
                  value={
                    sellers.options.find(
                      (option) =>
                        localFilters.sellerId === option.seller.id.toString()
                    ) || null
                  }
                  onChange={(_, newValue) => {
                    updateLocalFilter(
                      'sellerId',
                      newValue?.seller.id.toString() || null
                    );
                    updateLocalFilter(
                      'sellerName',
                      newValue?.seller.name || null
                    );
                  }}
                  loading={sellers.isLoading}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Vendedor"
                      placeholder="Selecione um vendedor"
                    />
                  )}
                  renderOption={(props, option) => {
                    const { key, ...otherProps } = props;
                    return (
                      <li key={option.id} {...otherProps}>
                        {option.label}
                      </li>
                    );
                  }}
                />
              </Grid>
            </Grid>
          </Collapse>
        </Grid>
      </Grid>
    </Paper>
  );
};
